Skip to content

Instantly share code, notes, and snippets.

@devnoo
Created January 6, 2012 12:14
Show Gist options
  • Save devnoo/1570316 to your computer and use it in GitHub Desktop.
Save devnoo/1570316 to your computer and use it in GitHub Desktop.
seven languages in seven weeks prolog day 3
% The valid methods valdiates that every elements (that should be a list) contains only different numbers.
% this is copied from the book.
valid([]).
valid([Head|Tail]) :-
fd_all_different(Head),
valid(Tail).
% Splits a list in to mutliple lists of length N.
split_head_tail(_,[],[],[]).
split_head_tail(0,Tail,[],Tail).
split_head_tail(N,[Head|Tail],[Head|Y],Z):-
N1 is N-1,
split_head_tail(N1,Tail,Y,Z),
!.
split_in_to_rows(N, [], []).
split_in_to_rows(N, List, [List]) :-
length(List, N).
split_in_to_rows(N, List, Result) :-
split_head_tail(N, List, Row, Rest),
split_in_to_rows(N, Rest, Rows),
append([Row], Rows, Result),
!.
% takes the n-th column from the rows.
col_row([Row], ColNumber, [Element]) :-
nth(ColNumber, Row, Element), !.
col_row([First|Rest], ColNumber, [Element|Column]) :-
nth(ColNumber, First, Element),
col_row(Rest, ColNumber, Column),!.
col_rows(Rows, Columns) :-
length(Rows, NumberOfRows),
col_rows(NumberOfRows, Rows, Columns).
% splits rows into columns
col_rows(0, _, []).
col_rows(NumberOfRows, Rows, Result) :-
NumberOfRows > 0,
col_row(Rows, NumberOfRows, Column),
Number is (NumberOfRows - 1),
col_rows(Number, Rows, Columns),
append(Columns, [Column], Result),
!.
% solves the 4x4 Sudoku
sudoku4(Puzzle, Solution) :-
Solution = Puzzle,
Puzzle = [S11, S12, S13, S14,
S21, S22, S23, S24,
S31, S32, S33, S34,
S41, S42, S43, S44],
Square1 = [S11, S12, S21, S22],
Square2 = [S13, S14, S23, S24],
Square3 = [S31, S32, S41, S42],
Square4 = [S33, S34, S43, S44],
solveSudoku(4, [Square1, Square2, Square3, Square4], Puzzle, Solution).
% solves the 6x6 sudoku
sudoku6(Puzzle, Solution) :-
Solution = Puzzle,
Puzzle = [S11, S12, S13, S14, S15, S16,
S21, S22, S23, S24, S25, S26,
S31, S32, S33, S34, S35, S36,
S41, S42, S43, S44, S45, S46,
S51, S52, S53, S54, S55, S56,
S61, S62, S63, S64, S65, S66
],
Square1 = [S11, S12, S13, S21, S22, S23],
Square2 = [S14, S15, S16, S24, S25, S26],
Square3 = [S31, S32, S33, S41, S42, S43],
Square4 = [S34, S35, S36, S44, S45, S46],
Square5 = [S51, S52, S53, S61, S62, S63],
Square6 = [S54, S55, S56, S64, S65, S66],
solveSudoku(6, [Square1, Square2, Square3, Square4, Square5, Square6], Puzzle, Solution).
% solves a sudoku of Number X Number
solveSudoku(Number, Squares, Puzzle, Solution) :-
fd_domain(Solution, 1, Number),
split_in_to_rows(Number, Puzzle, Rows),
col_rows(Rows, Columns),
append(Rows, Columns, RowsAndCols),
append(RowsAndCols, Squares, Validatables),
valid(Validatables),
write_list(Rows).
write_list([]).
write_list([Head|Tail]) :-
nl,
write(Head),
write_list(Tail).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment