> Home > Computer Q & A
Q: I need to creat a c++ program that doesn't use pointers or structures to accept an unknown amount of integers and return the number or numbers that appeared the most. Eg: 1,1,2,1,2:would return"the number 1 appeared 3 times".
A: Why don't you want to use pointers or structures?
It's pretty hard to write C++ without these. Are you trying to write
a function for another language to call? You could write a function that
takes in a SafeArray and returns the results. From another language, you
would probably want a count of the integers, and then a pointer to the first
integer. You could solve the problem in a language like J with this
expression: (\: {:"1)@(~. ,. #/.~)
Also, your solution may depend on the expected size of the input. A few
hundred numbers could be done with a simple algorithm. If we're talking
millions, you will probably want to build some sort temporary tree.
Q: I am trying to make it a simple function :-). How about if I accepted only ten integers, how would I do it then? If you could shed some light on that, maybe I could figure out the rest. I am having problems recording the number that occurred most often and associating it with it's amount of occurrences in the array. Thanks for your responses.
A: //Here's a program that shows you one way to do this:
#include <iostream>
#define SWAP(a,b) { if (a != b) { (a) ^= (b); (b) ^= (a); (a) ^= (b); } }
int main(int argc, char* argv[])
{
const int sortList[] = {1,1,2,1,2 ,5,5,5,5};
const int sortLength = sizeof(sortList)/sizeof(int);
int uniqueList[sortLength];
int uniqueFreq[sortLength];
int uniqueSize = 0;
for(int i=0;i<sortLength;i++)
{
for(int j=0;j<uniqueSize;j++)
{
if
(sortList[i]==uniqueList[j])
{
uniqueFreq[j]++;
break;
}
}
if (j==uniqueSize)
// Not in unique list, so we need to add it.
{
uniqueList[uniqueSize]
= sortList[i];
uniqueFreq[uniqueSize]
= 1;
uniqueSize++;
}
}
for(i=0;i<uniqueSize;i++) //
Bubble sort the frequencies
for(int j=0;j<i;j++)
if
(uniqueFreq[i] > uniqueFreq[j])
{
SWAP(uniqueFreq[i],uniqueFreq[j]);
SWAP(uniqueList[i],uniqueList[j]);
}
for(i=0;i<uniqueSize;i++)
std::cout <<
uniqueList[i] << " occured " << uniqueFreq[i] <<
" times." << std::endl;
return 0;
}