I have solved a problem of a game named 'Set'. The full problem is detailed on it's website: https://www.urionlinejudge.com.br/judge/en/problems/view/1090
However my code for the search algorithm is too slow, I'd like to achieve something around \$O(n)\$. How can I make SetGameManager::CountSet()
better?
This is not the full code, it's just so that you have an idea of what's going on:
#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
enum TYPE{
SQUARE,
CIRCLE,
TRIANGLE,
};
struct _card
{
TYPE type;
int amount;
_card( int a, TYPE t) { type = t; amount = a;};
};
inline bool canMatch(_card a, _card b)
{
return((a.type == b.type && a.amount != b.amount) || (a.type == b.type && a.amount == b.amount) );
}
inline bool canMatch3(_card a, _card b, _card c)
{
return((a.type == b.type && a.type == c.type)
&& ((a.amount != b.amount && b.amount != c.amount && a.amount != c.amount) ||
( a.amount == b.amount && a.amount == c.amount )));
}
inline bool cannotMatch(_card a, _card b)
{
return(a.type != b.type && a.amount != b.amount);
}
inline bool cannotMatch3(_card a, _card b, _card c)
{
return((a.type != b.type && b.type != c.type && a.type != c.type) &&
(a.amount != b.amount && b.amount != c.amount && a.amount != c.amount));
}
class SetGameManager {
public:
std::vector<_card> gameCards;
}
inline unsigned int SetGameManager::CountSet()
{
unsigned int SetMatches = 0;
unsigned int i1 = 0;
std::sort(this->gameCards.begin(), this->gameCards.end());
while(gameCards.size() > 2)
{
auto continue_outer_loop(true);
for(unsigned int i2=1; continue_outer_loop && (i2<gameCards.size()); i2++)
{
if(i2 == 2) continue;
auto const p_match_3_func
(
cannotMatch(gameCards.at(i1), gameCards.at(i2))
?
&cannotMatch3
:
&canMatch3
);
for(unsigned int i3=2; i3<gameCards.size(); i3++)
{
if((*p_match_3_func)(gameCards.at(i1), gameCards.at(i2), gameCards.at(i3)))
{
SetMatches++;
gameCards.erase(gameCards.begin()+i3);
gameCards.erase(gameCards.begin()+i2);
continue_outer_loop = false;
break;
}
}
}
gameCards.erase(gameCards.begin());
}
return SetMatches;
}
This is not the full code, it's just so that you have an idea of what's going on.
Full code here if you'd like: pastebin.com/z44bR8VL \$\endgroup\$