简体   繁体   中英

C - Find most frequent element in char array

i'm developing a little function to display the most frequent character in a (char) array. This is what I've accomplished so far, but I think i'm on the wrong way.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{

char test[10] = "ciaociaoci";
max_caratt(test, 10);

}

int max_caratt(char input[], int size)
{
int i;
char max[300];
max[0] = input[0];

for (i=0; i<size; i++)
{

    if(strncmp(input,input[i],1) == 1)
    {
        printf("occourrence found");
        max[i] = input[i];
    }


}

}

Any help?

Actually, the correct code is this.
It's just a corrected version of IntermediateHacker's below snippet.

void main()
{

int array[255] = {0}; // initialize all elements to 0

char str[] = "thequickbrownfoxjumpedoverthelazydog";

int i, max, index;

for(i = 0; str[i] != 0; i++)
{
   ++array[str[i]];
}


// Find the letter that was used the most
max = array[0];
index = 0;
for(i = 0; str[i] != 0; i++)
{
     if( array[str[i]] > max)
     {
         max = array[str[i]];
         index = i;
     }
}

printf("The max character is: %c \n", str[index]);

}

The easiest way to find the most common character is to create an int array of 255 and just increment the arraly element that corresponds to the character. For example: if the charcter is 'A', then increment the 'A'th element (if you look at any ascii table you will see that the letter 'A' has a decimal value of 65)

int array[255] = {0}; // initialize all elements to 0
char str[] = "The quick brown fox jumped over the lazy dog.";
int i, max, index;
// Now count all the letters in the sentence
for(i = 0; str[i] != 0; i++)
{
   ++array[str[i]];
}
// Find the letter that was used the most 
max = array[0];
index = 0;
for(i = 0; str[i] != 0; i++)
{
     if( array[i] > max)
     {
         max = array[i];
         index = i;
     }
}

printf("The max character is: %c \n", (char)index);

Assuming an input array of 0-127, the following should get you the most common character in a single pass through the string. Note, if you want to worry about negative numbers, shift everything up by +127 as needed...

char mostCommonChar(char *str) {

  /* we are making the assumption that the string passed in has values 
   * between 0 and 127.
   */
  int cnt[128], max = 0;
  char *idx = str;

  /* clear counts */
  memset((void *)cnt, 0, sizeof(int) * 128);

  /* collect info */
  while(*idx) {
    cnt[*idx]++;
    if(cnt[*idx] > cnt[max]) {
        max = *idx;
    }
    idx++;
  }

  /* we know the max */
  return max;
}

You're passing a (almost) string and a char to strncmp() . strncmp() takes two strings (and an integer). Your program shouldn't even compile!

Suggestion: increase the warning level of your compiler and mind the warnings .

You may want to look at strchr() ...

I made a working version using structs. It works fine, I guess, but I think there's a MUCH better way to write this algorithm.

#include <stdio.h>
#include <stdlib.h>

struct alphabet {
    char letter;
    int times;
};

typedef struct alphabet Alphabet;

void main() {

    char string[300];

    gets(string);


    Alphabet Alph[300];

    int i=0, j=0;

    while (i<=strlen(string)) {
        while(j<=300) {
            if(string[i] != Alph[j].letter) {
                Alph[i].letter = string[i];
                Alph[i].times = 1;
            }
            else {
                Alph[j].times++;
            }
            j++;
        }

        j=0;
        i++;
    }



    int y,max=0;
    char letter_max[0];
    for (y=0; y<strlen(string); y++) {

        printf("Letter: %c, Times: %d \n", Alph[y].letter, Alph[y].times);

        if(Alph[y].times>max) {
            max=Alph[y].times;
            letter_max[0]=Alph[y].letter;
        }

    }

    printf("\n\n\t\tMost frequent letter: %c - %d times \n\n", letter_max[0], max);


}

I saw you all creating big arrays and "complex" stuff so here I have easy and simple code xD

char most_used_char (char s[]) {

    int i; //array's index
    int v; //auxiliary index for counting characters 

    char c_aux; //auxiliary character
    int sum = 0; //auxiliary character's occurrence 

    char c_max; //most used character
    int max = 0; //most used character's occurrence

    for (i = 0; s[i]; i++) { 

        c_aux = s[i];  

        for (v = 0; s[v]; v++) 
            if (c_aux == s[v]) sum++; /* responsible cycle for counting
                                         character occurrence */

        if (sum > max) { //checks if new character is the most used
            max = sum;
            c_max = c_aux;
        }

        sum = 0; /* reset counting variable so it can counts new  
                    characters occurrence */

    }

    return c_max; //this is the most used character!

}

If you don't need to preserve the input array, you could sort the input array first, then find the longest contiguous run of a single character. This approach is slower, but uses less space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM