Skip to content

Instantly share code, notes, and snippets.

@aarroyoc
Created October 31, 2022 16:29
Show Gist options
  • Save aarroyoc/303da8ad86ad40a50d216d343ae83c9c to your computer and use it in GitHub Desktop.
Save aarroyoc/303da8ad86ad40a50d216d343ae83c9c to your computer and use it in GitHub Desktop.
:- use_module(library(clpz)).
:- use_module(library(lists)).
:- use_module(library(format)).
cols(6).
rows(6).
board([
c,c,2,c,3,c,
2,c,c,c,c,c,
c,c,2,4,c,3,
1,c,3,4,c,c,
c,c,c,c,c,3,
c,3,c,3,c,c
]).
run :-
% Data
board(Board),
% Variables and domains
length(Board, N),
length(Mines, N),
Mines ins 0..1, % 0 is no mine, 1 is mine
% Constraints
add_constraint(Board, Mines, 0, 0),
% Execution
label(Mines),
format("~d~d~d~d~d~d~n~d~d~d~d~d~d~n~d~d~d~d~d~d~n~d~d~d~d~d~d~n~d~d~d~d~d~d~n~d~d~d~d~d~d~n", Mines).
add_constraint([BoardCell|RestBoard], Mines, X, Y) :-
\+ BoardCell = c,
cols(NCols),
Index is Y*NCols + X,
nth0(Index, Mines, Mine),
Mine #= 0,
nth0_or_zero(X-1, Y, Mines, Mine1),
nth0_or_zero(X+1, Y, Mines, Mine2),
nth0_or_zero(X-1, Y-1, Mines, Mine3),
nth0_or_zero(X, Y-1, Mines, Mine4),
nth0_or_zero(X+1, Y-1, Mines, Mine5),
nth0_or_zero(X-1, Y+1, Mines, Mine6),
nth0_or_zero(X, Y+1, Mines, Mine7),
nth0_or_zero(X+1, Y+1, Mines, Mine8),
BoardCell #= Mine1 + Mine2 + Mine3 + Mine4 + Mine5 + Mine6 + Mine7 + Mine8,
NewX is X + 1,
(
NewX = NCols ->
(
NewY is Y + 1,
add_constraint(RestBoard, Mines, 0, NewY)
)
;
add_constraint(RestBoard, Mines, NewX, Y)
).
add_constraint([c|RestBoard], Mines, X, Y) :-
cols(NCols),
NewX is X + 1,
(
NewX = NCols ->
(
NewY is Y + 1,
add_constraint(RestBoard, Mines, 0, NewY)
)
; add_constraint(RestBoard, Mines, NewX, Y)
).
add_constraint([], _, _, _).
nth0_or_zero(X, Y, List, Value) :-
cols(NCols),
rows(NRows),
X >= 0,
Y >= 0,
X < NCols,
Y < NRows,
Index is Y*NCols + X,
nth0(Index, List, Value),!.
nth0_or_zero(_X, _Y, _List, 0).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment