Reputation: 151
I have the exact same Elem
and List
class as defined on http://www.cplusplus.com/forum/beginner/73928/
Can you suggest some tips on how to write a function that returns true
in case all of the values have been repeated two or more times? E.g.
1,1,1,2,2 - true
1,2 - false
I kinda feel it will surely require a dynamic array but cannot think of the algorithm.
Upvotes: 2
Views: 458
Reputation: 1651
the function will look something like this (untested):
std::map<int,int> m_mapCount;
std::map<int,int>::iterator m_Iterator;
for (l.start(); !l.end(); l.next()) // put the content of your linkedlist to map
{
m_mapCount[l.current->num] += 1;
}
for (m_Iterator=m_mapCount.begin(); m_Iterator!=m_mapCount.end(); m_Iterator++)
{
if(m_Iterator->second >= 2) return true;
}
Upvotes: 0
Reputation: 151
bool twoormore()
{
int count = 0;// for counting elements in list
int temp;// temprorary element for sorting and logical part
int cik;// how much times the value has been mentioned
bool res = true;// function result
int * arr;// pointer for the upcoming dynamic array
for(start();!end();next())
{
count++;// counting the elements
}
if(count != 0){
arr = new int[count];//creating array
int i = 0;
for(start();!end();next())
{
arr[i++] = current->num;//filling array
}
/** array sorting **/
for(int i = 0;i < count;i++)
for(int j = 0; j < count; j++)
{
if(arr[j] > arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
/** sort ends **/
temp = arr[0]; // setting first element ar temp.. for upcoming check
cik = 1;// it's been its first time
for(int i = 1;i < count;i++)
{
if(arr[i] == temp)
{
cik++; continue;// if upciming element is equal to temprorary , then add 1 to counter.. and continue looping
}else
{
if(cik > 1)
{
temp = arr[i];// if everything ok, but element value changes.
cik = 1;// sets defualt
continue;
}
else
{
res = false;// other way, the value wasnt there two times
break;
}
}
}
delete arr;//deleting allocated space for array
return res;// returning bool, true or false.
}
}
Upvotes: 0
Reputation: 2662
Yes, make a std::map<int,int>
where you count the occurence count of each number in the list. This computation requires one pass over all the list.
Afterwards, make another pass over the std::map
you've just created and find out if all the values are greater or equal to 2.
Upvotes: 2