First of all, I'd like to point out that this is server-side Node.js code, not plain client-side Javascript. I don't want to use jQuery but using any native Node.js methods (if there are any potentially useful ones you know) is fine.
This is code for a robot player in a card game. The robot has a hand of cards structured as follows:
[ '9H', '10S', 'KD', '9D', '7D', 'QC', 'JC', '7C' ]
So each of the 8 cards is given as a value+suit string. This can't be changed, as the whole application works with this structure.
Now, the robot has to analyze this hand to search for certain card combinations. For example, it should find any "third kings" (king with at least 2 smaller cards of the same suit), "second tens" (queen with at least 1 smaller card of the same suit) or "third queens".
In the example above, it should come up with: third king of diamonds and third queen of clubs.
I'm looking at implementing a search algorithm to find these combinations, but I'm worried it would be very inefficient. My first idea is to iterate through the array to find all kings, queens and 10s and save this data somewhere, then iterate through it again to count how many other cards of the same suit we have. For example, for the king:
var kingsuits = [];
for(var i=0;i<8;i++){
if(hand[i].substr(0,1) == "K")
kingsuits.push(hand[i].substr(-1));
}
//now kingsuits has the suits of all kings, and we can go through our hand again and check how many cards we have in each of these suits...
My question is, is there a more efficient way to accomplish this? The thing is, there are quite a few other combinations that should also be looked for, not just the ones I named as examples above.
Also - perhaps more importantly - if we find a "third king" we don't need to look for a "third queen" or "second 10" at all. There's a clear hierarchy of these combinations, so if we find the first one we don't need to care about the others at all.