Virtual Chess tournament with Prolog
2020-12-07
Below my #swi #prolog solution for “Virtual Chess tournament” proposed by dmcommunity.org challenge Dec 2020
Player 1 is Fischer, player 2 is Kasparov and player 3 is Karpov.
I can find two solutions (Score1,Wins1,Draws1,Loses1 are Fischer’s score, number of wins, draws and loses,..) is:
?- time(solution([[Score1,Wins1,Draws1,Loses1],[Score2,Wins2,Draws2,Loses2],[Score3,Wins3,Draws3,Loses3]])).
% 1,297,058 inferences, 0.136 CPU in 0.136 seconds (100% CPU, 9557549 Lips)
Score1 = 15,
Wins1 = 4,
Draws1 = 7,
Loses1 = Draws2, Draws2 = 3,
Score2 = 13,
Wins2 = 5,
Loses2 = 6,
Score3 = 14,
Wins3 = Loses3, Loses3 = 2,
Draws3 = 10 ;
% 152,142 inferences, 0.021 CPU in 0.021 seconds (100% CPU, 7203556 Lips)
Score1 = 15,
Wins1 = Draws2, Draws2 = 4,
Draws1 = 7,
Loses1 = 3,
Score2 = 14,
Wins2 = Loses2, Loses2 = 5,
Score3 = 13,
Wins3 = 1,
Draws3 = 11,
Loses3 = 2 ;
?- time(findall([[Score1,Wins1,Draws1,Loses1],[Score2,Wins2,Draws2,Loses2],[Score3,Wins3,Draws3,Loses3]], solution([[Score1,Wins1,Draws1,Loses1],[Score2,Wins2,Draws2,Loses2],[Score3,Wins3,Draws3,Loses3]]), L)), length(L, TotSolutions).
% 2,401,046 inferences, 0.252 CPU in 0.252 seconds (100% CPU, 9530423 Lips)
L = [[[15, 4, 7, 3], [13, 5, 3, 6], [14, 2, 10, 2]], [[15, 4, 7, 3], [14, 5, 4, 5], [13, 1, 11, 2]]],
TotSolutions = 2.
Below my dec2020.pl script
tot_games(14).
tot_games_two_players(7).
match_two_players(Wins1, Draws, Wins2):-
%% constraint: 7 games agains each player
tot_games_two_players(TotGames),
Wins1 in 0..TotGames,
Draws in 0..TotGames,
Wins2 in 0..TotGames,
Wins1 + Draws + Wins2 #= TotGames.
tournament([[Score1, Wins1, Draws1, Loses1],
[Score2, Wins2, Draws2, Loses2],
[Score3, Wins3, Draws3, Loses3]
]):-
tot_games(TotGames),
match_two_players(Wins12, Draws12, Wins21),
match_two_players(Wins13, Draws13, Wins31),
match_two_players(Wins23, Draws23, Wins32),
Wins1 #= Wins12 + Wins13,
Wins2 #= Wins21 + Wins23,
Wins3 #= Wins31 + Wins32,
Loses1 #= Wins21 + Wins31,
Loses2 #= Wins12 + Wins32,
Loses3 #= Wins13 + Wins23,
Draws1 #= Draws12 + Draws13,
Draws2 #= Draws12 + Draws23,
Draws3 #= Draws13 + Draws23,
Wins1 + Draws1 + Loses1 #= TotGames,
Wins2 + Draws2 + Loses2 #= TotGames,
Wins3 + Draws3 + Loses3 #= TotGames,
Score1 #= Wins1 * 2 + Draws1,
Score2 #= Wins2 * 2 + Draws2,
Score3 #= Wins3 * 2 + Draws3,
%% constraint: Fischer (1) is the winner
Score1 #> Score2,
Score1 #> Score3,
%% constraint: Kasparov (2) is the most aggressive
Wins2 #> Wins1,
Wins2 #> Wins3,
%% constraint: Karpov (3) is the best defensive player
Loses1 #> Loses3,
Loses2 #> Loses3.
solution([[Score1,Wins1,Draws1,Loses1],
[Score2,Wins2,Draws2,Loses2],
[Score3,Wins3,Draws3,Loses3]]):-
tournament([[Score1,Wins1,Draws1,Loses1],
[Score2,Wins2,Draws2,Loses2],
[Score3,Wins3,Draws3,Loses3]]),
label([Score1, Score2, Score3,
Wins1,Wins2,Wins3,
Draws1,Draws2,Draws3,
Loses1,Loses2,Loses3]).