I have an array of objects that I need to iterate through in order to get three items.
The parts of the object important in this context are: value and type.
I need to find the first three items from the array that have the greatest value sum and are of the same type.
Right now I've just used three "for" statements to iterate through the array and compare all the combinations of three items. However this is extremely inefficient and it seems like there should be a better solution. I thought sorting the array in descending order would give me the best match for the first compatible items, but that's not always true.
In the following I use a vector for the array and "compatible()" checks the type for three items:
int maxScore = 0, maxItems[3];
for(int i = 0; i < items.size() - 2; i++)
for(int j = i + 1; j < items.size() - 1; j++)
for(int k = j + 1; k < items.size(); k++)
if(compatible(items[i], items[j], items[k]))
if(maxScore < items[i].getScore() + items[j].getScore() + items[k].getScore())
{
maxScore = items[i].getScore() + items[j].getScore() + items[k].getScore();
maxItems[0] = i; maxItems[1] = j; maxItems[2] = k;
}
if(maxScore)
printBestMatch(items[maxWords[0]], items[maxWords[1]], items[maxWords[2]]);
else
cout<<"No matches found!"<<endl;
There has to be a better way of doing this.