Hi, i have a silly question, but i can't come up with the solution.
I have an array of 2, 2, 4, 2, 4.
My task is: To count how many of the same numbers are in the array. For example, the answer shall show, that there are 3 2's and 2 4's.
I've tried a function with something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int sum = 0;
int number;
int j;
for (int i = 1; i <= m; i++)
{
for (int j = i + 1; j <= m; j++)
{
if (Array[i] == Array[j])
{
number = Array[i];
sum++;
}
}
cout << sum << number << endl;
}
Arrays start at 0, so lines 4 & 6 will miss the first entry and go past the end of the array.
You only have 1 number variable which incremented. In your scenario sum will be 5, and number will be 4 - which not quite what you want.
To process a 2 dimensional array, do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int sum = 0;
int number;
constint NUMROWS = 5;
constint NUMCOLS = 10;
int Array[NUMROWS][NUMCOLS];
//code to initialise the array goes here
for (int Row = 0;Row < NUMROWS; Row++) {
for (int Col = 0; Col < NUMCOLS; Col++) {
//your code here
}
}
To count multiple numbers, you could have an array structs. The struct stores the number in question and it's count. Or have 2 arrays to do the same thing if this is too advanced for you. This is a C approach
A C++ approach would be to make use of a <vector>'s or <list>'s. Use push_back to put numbers in. You can read about how to do this in the reference section at the top left of this page.
Actually some of your ways are too advanced for me. I do not know such things as std::vector or std::map and i'm not supposed to know them yet. Therefore, there should be an easier way, like having another array (i'm not assessed with 2 dimensional arrays also). Though i'm having a hard time understanding, of how to use another array here.
What about my suggestion of 2 arrays? One for the numbers found - the other for the count of numbers found.
Declare the arrays so they are at least as big as your input array, and initialise them to zero.
When a new number is encountered - see if it is already in the array - need to write your own find function for this. If it is already there increment it's count in the count array. Otherwise put it in the numbers found array and increment it's count.
You need to know the maximum value that will be in your array.
Array { 2, 2, 4, 2, 4 } is no problem, perhaps we asumme that the array will be numbers 0-9.
1 2
int input[] = { 2, 2, 4, 2, 4 } ; // This array must have values between 0-9
int count[10]; // set each value here to zero
You then go through the input array, and increase the corresponding value in that index:
1 2 3 4 5 6 7
int i = 2;
int j = 2;
int k = 3;
count[i]++;
count[j]++;
count[k]++;
// count = { 0, 0, 2, 1, 0, 0, 0, 0, 0, 0 };