Reputation: 67
:- use_module(library(clpfd)).
go(Rows):-
foreach(J in 1..9, K in 1..9, Number = Rows[J,K],
Code is 0'A + Number - 1, char_code(Letter, Code), Rows[J,K] is Letter,nl)
sudoku(Rows) :-
append(Rows, Vs), Vs ins 1..9,
maplist(all_distinct, Rows),
transpose(Rows, Columns),
maplist(all_distinct, Columns),
Rows = [A,B,C,D,E,F,G,H,I],
blocks(A, B, C),
blocks(D, E, F),
blocks(G, H, I),
maplist(label, Rows),
blocks([], [], []).
blocks([A,B,C|Bs1], [D,E,F|Bs2], [G,H,I|Bs3]) :-
all_distinct([A,B,C,D,E,F,G,H,I]),
blocks(Bs1, Bs2, Bs3).
But this solves a sudoku containing numbers from 1 to 9 , I need to do something to convert the 1 to 9 into A to I
What I am thinking is to traverse each element in the grid and check the value accordingly replace it with the corresponding alphabet.
How can I traverse and replace the numbers or is there some better way to solve this?
Error :
Thanks! :D
Upvotes: 0
Views: 288
Reputation: 18663
To convert the numbers in the 1..9
interval to letters in the A..I
interval you can use the goal:
Code is 0'A + Number - 1, char_code(Letter, Code)
For example:
?- Number = 4, Code is 0'A + Number - 1, char_code(Letter, Code).
Number = 4,
Code = 68,
Letter = 'D'.
Assuming that the solution matrix is represented by a list of lists, the conversion can be accomplished using something like:
convert_matrix([], []).
convert_matrix([Row| Rows], [ConvertedRow| ConvertedRows]) :-
convert_row(Row, ConvertedRow),
convert_matrix(Rows, ConvertedRows).
convert_row([], []).
convert_row([Number| Numbers], [Letter| Letters]) :-
Code is 0'A + Number - 1,
char_code(Letter, Code),
convert_row(Numbers, Letters).
But the conversion code can be simplified using maplist
predicates. I leave that to you as an exercise. Hint: define an auxiliary predicate that takes a number and returns the corresponding letter.
Upvotes: 1