I have an array and I have integers in the array. I’m trying to count the number of times the integers in the array repeat themselves. After that I want to print the percentage. This is what I have so far.
for(i = 2; i < 8; i++){
mmblk[i] = (num[i] / bsize); //mmblk[i] =0,0,1,9,0,1
if(mmblk[i] == mmblk[i]){
count ++;
p = count/num[0];
percent = (p * 100);
}
}
printf("Highest possible hit rate = %d/%d = %d %\n", count, num[0], percent);//num[0]=6
For the output I get:
Highest possible hit rate = 0/6 = 0
The output should look like:
Highest possible hit rate = 3/6 = 50 %
I know there is something way wrong going on but I can’t figure out what it is. Any help will be greatly appreciated.
So if I understand correctly, you are looking for the maximum number of repeated values in the array.
To get the percentage, you simply divide this result by the length of the array.
The problem is your function is way too simple, and not really at all the solution.
The solution I’m coming up with on first approach, is to have another array called counts. This is the same length as your source array. It ends up being the number of times each number in the source array appears.
For each item in the source array, you count how many times that number appears, and store that result in counts. Then you find the maximum of the counts array, and you have a) the max repeats value you’re looking for, and b) the index of the corresponding maximum-repeated-value from the source array.
For the example {0,0,1,9,0,1} :
One optimization to this, is while you are counting, if you encounter the same number earlier in the array, you can stop, because you already have counted repeats for that value.
With that in place, your result is:
Another optimization is to only start counting from your current index in the array. This works for the same reason as the other optimization.
Results: