Home > OS >  count of count of recurunces in an array using c
count of count of recurunces in an array using c

Time:07-07

i am trying to get the total amounts of numbers occurunces , my main problem is that i messed up some where and i cant read numbers that are higher than 12 , as in my count wont see it other than that works perfectly , doesnt matter if sorted on not array doesnt affect the program(for my random array example)

*** int Count(int r[], int n, int x) {
    int res = 0;
    for (int i = 0; i <n; i  )
        if (x == r[i])
            res  ;
    return res;
}



int main() {

    int count = 0;
    int r[12] = { 1, 1, 2, 3, 4, 5, 6, 6, 7, 8,13,13  };
    int n = sizeof(r) / sizeof(r[0]); 


    for (int i = 0; i < n; i  )
    {
        for (int j = 0; j < n; j  ) {

            if (r[i] > r[j])
            {
                swap(r[i], r[j]);
            }
        }
    }
    for (int i = 0; i <= n; i  ) {
        if (Count(r, n, i) >= 2) {
            count  ;
            cout << "number" << i << "-" << Count(r, n, i) << " Recurrences" << endl;
        }
    }
    cout << "count is " << count;

    return 0;

} ***

CodePudding user response:

Try an easier and more optimized way using map:

int r[12] = { 1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 13, 13 };
int n = sizeof(r) / sizeof(r[0]);
map<int, int> map;

for (int i = 0; i < n; i  )
{
    if (map.find(r[i]) != map.end())
    {
        map[r[i]]  ;
    }
    else
    {
        map[r[i]] = 1;
    }
}

for (auto const& x: map)
{
    cout << x.first << ':' << x.second << std::endl;
}

output

1:2
2:1
3:1
4:1
5:1
6:2
7:1
8:1
13:2

CodePudding user response:

You can't read numbers higher than 12 because i <=n==12 before if (Count(r, n, i) >= 2),and the i is the x in function Count which compare with r[i]. So you will lose numbers higher than the length of r[].I guess this is what you want.

for (int i = 0; i < n; i  ) {
    if (Count(r, n, r[i]) >= 2) {
  •  Tags:  
  • c
  • Related