cvector

Print floats of an array and respective quantity of each


I've been trying to code a program in C that, given a float array, determines how many of each number there are, and then, prints each number and their respective frequency. This is an exercise from my college (computer science course). In total, I must have spent like 3 hours trying to think about a solution and I just can't think. I'm certain this is trivial, though.

I couldn't develop anything that I thought would work. If i go to VS and try to code something to solve this, my mind freezes at the moment I would need to think how to represent the mechanism that makes the computer "know" if a number in a given position and its frequency were already accounted for before in the (int) frequency array.

(For everyone's comprehension, I modified the text above after posting it because I forgot about the word "array" and mistranslated to english. In portuguese (my native language), it is "vetor", so I assumed it was "vector", which is another existing english word. However, that one for sure doesn't seem be used as much as "array" to represent this in english programming discussions.)

#include <stdio.h>

#define VEC_LEN 8

int main(void)
{
    int vFreq[VEC_LEN] = { 0, 0, 0, 0, 0, 0, 0 ,0 };
    float vNums[VEC_LEN] = { 1.5, -4.8, 2.9, 6.1, 4.2, 1.5, 2.9, 6.1 };

    for (int i = 0; i < VEC_LEN; i++)
    {
        float n = vNums[i];
        for (int j = 0; j < VEC_LEN; j++)
        {
            if (n == vNums[j])
                vFreq[i]++;

            // then my brain freezes
        }
    }
        


    return 0;
}

Solution

  • I'll not give a complete solution in C code. Since you are taking a "computer science course" I think it's best for you to solve it yourself. But here is a description of an algorithm you can implement.

    Start by sorting the array vNums. For that you'll use qsort.

    After sorting your array will be like:

    { -4.8, 1.5, 1.5, 2.9, 2.9, 4.2, 6.1, 6.1 }
    

    Then you iterate the sorted array and count consecutive equal elements. When two consecutive elements equals increase the counter and move to next element. When two consecutive elements differs, you print the first together with the counter value, and then restart the counting. In pseudo code something like:

    count = 1
    current_value = sorted_array[0]
    index = 1
    while index < number_of_element_in_sorted_array
    {
        if (current_value == sorted_array[index])
        {
            count = count + 1
        }
        else
        {
            print current_value and count
            count = 1
            current_value = sorted_array[index]
        }
        index = index + 1
    }
    print current_value and count