0

I have an array with randomly generated numbers in it, and I need to find and store the numbers that are present at least x times. (I can easily find x, that is not important. It will be a set amount). The array will have around 100-200 elements.

I know I will have to use a loop, but I'm not sure how to structure the body of it. I'm relatively new to C programming, so this may be fairly trivial. Any help is appreciated.

Jens
  • 69,818
  • 15
  • 125
  • 179
Yuunia
  • 27
  • 3

2 Answers2

0

Here is a description of one way to do it.

Sort the array. For that you use qsort - it's simple and fast.

Iterate the sorted array while counting identical elementets, something like:

int cur = arr[0];
int count = 1;
for (size_t i = 1; i < SIZE_ARR; ++i)
{
    if (cur == arr[i])
    {
        ++count;
    }
    else
    {
        if (count >= X)
        {
            // Save cur to result array
        }
        count = 1;
        cur = arr[i];
    }
}
if (count >= X)
{
     // Save cur to result array
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
-1

I've added pseudocode which you can translate to C easily. This assumes that all random numbers are positive integers, and are not too big.

create an array count of maximum-possible-random-number int elements initialised to 0.

for every entry in rng array:
  count[entry]++

for every entry in count array:
  if(entry >= x)
    print(entry's index)

puio
  • 1,208
  • 6
  • 19
  • 1
    That is for known 200 different values, maybe for the specific values 0-199. For 200 entries of values from unknown and possibly much larger range it will not work. Think of 200 entries from 0 .. maxint. – Yunnosch Nov 05 '20 at 19:57
  • Theoretically useable now. Practically likely to kill RAM sizes. I think you should ask for clarification before answering. – Yunnosch Nov 05 '20 at 20:01
  • This works for 16 bit numbers, but with 32 bit numbers (let alone 64 bit numbers) the size if the array is far too large. – Jabberwocky Nov 05 '20 at 20:19
  • 1
    my point still stands. It's good enough for beginners to understand loops. – puio Nov 06 '20 at 07:32