How do I count the number of occurrences in an array?

后端 未结 2 520
旧巷少年郎
旧巷少年郎 2021-01-21 08:31

I have generated an array of 5 random integers from 1-5. Here is what the array looks like now: myArray[5] = {3, 3, 1, 4, 5}

I have now sorted the array of

相关标签:
2条回答
  • 2021-01-21 08:58

    Make a hash and initialize with zero.

    int hash[10000]={0};
    for(int i=0;i<n;i++)
    {  
         hash[arr[i]]++;
    }
    

    the hash at index arr[i] will hold value which is the count of occurrence of that number. As hash[arr[i]]++ will increment the count at index equal to the value of arr[i]. This way we can check which value occurred how many times by checking hash[arr[i]] where arr[i] is value to be checked.

    0 讨论(0)
  • 2021-01-21 09:05

    Use a std::map to map integers to their counts.

    std::map<int, int> counts;
    for (int i = 0; i < 5; i++) {
        counts[myArray[i]]++; // increment the counter for the current value
    }
    

    Now you can print the keys and values in counts. See How to loop through a C++ map of maps? for how to do this.

    You can do it with an array instead of a map. The only difference is that it won't automatically expand to handle larger values (unless you use malloc and realloc to make it dynamically sized).

    #define MAX_VALUE 9
    int counts[MAX_VALUE+1] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    for (int i = 0; i < ARRAY_SIZE; i++) {
        if (myArray[i] <= MAX_VALUE) {
            counts[myArray[i]]++; // increment the counter for the current value
        }
    }
    for (int j = 0; j <= MAX_VALUE; j++) {
        cout << "Number: " << j << "Number of Occurances: " << counts[j] << endl;
    }
    
    0 讨论(0)
提交回复
热议问题