Prolog Card Game: Valid sets
<p>I am working on a simple card game, which involves laying cards on the table in particular groups. I would like to write a predicate which tries to find out whether a set of cards can be arranged into valid groups.</p>

<p>Cards in a valid group must exclusively either:
a) of the same suit, and of consecutive numbers (hearts 1,2,3) or 
b) of different suits and the same number (1 of hearts, 1 of diamonds and 1 of clubs)
The smallest allowable group is three.</p>

<p>Step one is to define what the cards are, and the obvious approach is to define them in predicate form:</p>

<pre><code>%hearts:
card(1,h).
card(2,h).
% etc.....

%diamonds:
card(1,d).
card(2,d).
%etc...
</code></pre>

<p>and so on for the clubs and spades.</p>

<p>Secondly I have defined a series of predicates to specify the rules. How cards can connect, and how to test for a valid group. For example I have defined the following to check whether two cards are valid and have the same suit and the same number:</p>

<pre><code>card_will_connect((N1,S1),(N2,S2)):-
    %firstly check that the cards exist:
    card(N1,S1),
    card(N2,S2),
    %same_suit
    S1=S2,
        consecutive_number(S1,S2).
</code></pre>

<p>I have also written some predicates that run through a group of cards to see whether the connections between them are valid.</p>

<p>The problem is, if I have a random set of cards - how do I try to group them in valid ways without exhaustive searching?</p>

<p>My idea to approach this is:
a) find out if any of the cards have zero possible connections within the set. If so fail and don't continue
b) find out if any cards have only 1 valid connection, move these to groups
c) now with the remaining cards, try to allocate them to these groups by using my card connection predicates to meet the required rules</p>