fjidsanfklxingdwsf fjidsanfklxingdwsf - 3 months ago 9
C Question

Wrote my code to look for a mode but gives me the largest number

I'm trying to find the mode of an sorted array, so I wrote the following code; However, it gives me the largest number in that array.

Can anyone help me out?

typedef struct mode {
int self;
int size;
} mode;

mode findmode(int *arr, int size) {
mode x;
int i = 0;
int count = 1;
for (i = 0; i < size; i++) {
if (i > 1 && i < size) {
if (arr[i] == arr[i - 1]) ++count;
if (arr[i] != arr[i - 1]) {
x.size = count;
x.self = arr[i - 1];
count = 0;
++count;
}
if (arr[i] != arr[i + 1]) {
if (count > x.size) x.size = count;
x.self = arr[i];
}
}
}
return x;
}

Answer

I've modified your code using if and else combo to count the number of occurrences of a given number or else start over by setting the counter to one. In the last if you can check whether or not the current occurrence count is bigger than the one we've stored before and swap the current mode and size.

#include <stdio.h>

typedef struct mode
{
  int self;
  int size;
} mode;

mode findmode(int *arr, int size) 
{
  mode x;
  x.self = arr[0];
  x.size = 1;
  int i;
  int count = 1;
  for (i = 1; i < size; i++) 
  {
      if(arr[i - 1] == arr[i])
      {
          count++;
      }
      else
      {
          count = 1;
      }
      if(count >= x.size)
      {
          x.self = arr[i];
          x.size = count;
      }
  }
  return x;
}

int main()
{
   int  arr[20] = {1,1,1,4,4,4,4,5,5,5,5,5,5,6,6,7,7,7,8,8};
   mode m = findmode(arr, 20);

   printf("The mode is %d with a occurrence count of %d\n", m.self, m.size);
}