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;
}
}
CodePudding user response:
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.
CodePudding user response:
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;
}