1.11M Members

Finding mode of an array of integers

 
0
 

Given an array A of length N, my task is to find the element which repeats in A maximum number of times as well as the corresponding count. In case of ties,I choose the smaller element first.
Input
First line of input contains an integer T, denoting the number of test cases. Then follows description of T cases. Each case begins with a single integer N, the length of A. Then follow N space separated integers in next line. Assume that 1 <= T <= 100, 1 <= N <= 100 and for all i in [1..N] : 1 <= A <= 10000
Output

For each test case, output two space separated integers V & C. V is the value which occurs maximum number of times and C is its count.

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

int l(int *a,int n)
{int large=a[0];
int i;
for( i=0;i<n;i++)
  {if(large<a[i])
        {
            large=a[i];
        }
  }
  return large;
}
int findMode(int *array, int size, int large)
{   if(size==1)
    {printf ("%d %d\n",array[0],1);
    return 0;
    }
	int *array2;
	int count;
	int x;
	int mode = 0;
	int highest = 0;

	array2 =(int *)malloc(sizeof(int)*large);

	for (count = 0; count < large; count++)
		array2[count] = 0;

	for (count = 0; count < size; count++)
	{
		x = array[count];
		array2[x]++;
	}

	for (count = 0; count < large; count++)
	{
		if (array2[count] > highest)
		{
			highest = array2[count];
			mode = count;
		}
		else if(array2[count]==highest&&mode>count)
        {
            highest = array2[count];
			mode = count;
        }
	}
		printf("%d %d\n",mode,highest);
		return 1;
}
int main()
{
    int t,n,j,k,i;
    int a[100];
    scanf("%d",&t);
    j=0;

    while(j<t)
    {
    scanf("%d",&n);
    k=0;
    for(i=0;i<n;i++)
    m[i]=0;
    i=0;
    while(k<n)
    {
        scanf("%d%*c",&a[k]);
       
        k++;
    }
    findMode(a,n,10000);
    j++;
    }
    return 0;
}
Input:
2
5
1 2 3 2 5
6
1 2 2 1 1 2

Output:
2 2
1 3

The thing is that although my code is working for the above test cases,the online compiler I am using shows my answer as the wrong answer.
Can anyone tell for which test case is my code not working?
Please assume that input need not be validated

 
0
 

Nothing jumps out at me for why it doesn't work. The algorithm isn't an efficient one, but at first glance it seems like it ought to give the desired results. You haven't listed the data set that DID NOT work.

Line 44 -- Can mode ever be higher than count? I don't see how. If not, this if statement will never be true.

Line 4 -- Is this function called?

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: