1

I have a large array of numbers that range from 1-5. I need to get the total of each number in the array and and place it into another array, with the total of number of 1s in the first position of the array, total number of 2s in the second position, etc.

So if I had arr1[10] = {1,4,3,1,2,4,5,4,1,3}, I would want to get to arr2[5] = {3,1,2,3,1}.

However, with my current code, I get

1,0,0,1,0

Here is my code below:

n = 10
arr1[n] = {1,4,3,1,2,4,5,4,1,3}
arr2[5] = {0,0,0,0,0}

for (int i = 0; i < n; i++)
    {
        int rate = arr1[i];
        if (arr2[i] == 0)
        {
            int count = 0;
            if (rate == 1)
            {
                count += 1;
                arr2[i] = count;
            }
            cout << count << endl;
        }
    }
1
  • Please explain how you think the code you wrote is anywhere close to doing what the assignment requires from you. It seems to have nothing in common with it (and it also invokes undefined behavior by accessing arr2 beyond its bounds) Commented Oct 23, 2021 at 18:21

2 Answers 2

1

Simply loop over the numbers in arr1 and increment the appropriate counter in arr2. Be aware that C arrays start at index 0 ;)

Only print the counts at the very end, once everything is tallied.

Sign up to request clarification or add additional context in comments.

Comments

0

If you're allowed to use C++:

#include <vector>
#include <map>
#include <iostream>
using namespace std;

int main(void)
{
    // Do count sort

    // Init vector
    vector<unsigned char> a = {1,5,3,4,2,2,4,5,1,1};

    map<unsigned char, size_t> a_map;

    // Populate map
    for (size_t i = 0; i < a.size(); i++)
        a_map[a[i]]++;

    vector<unsigned char> b;

    // Rebuild vector from map
    for (map<unsigned char, size_t>::const_iterator ci = a_map.begin(); ci != a_map.end(); ci++)
    {
        for (size_t i = 0; i < ci->second; i++)
            b.push_back(ci->first);
    }

    // Print sorted vector
    for (size_t i = 0; i < b.size(); i++)
        cout << static_cast<int>(b[i]) << endl;

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.