0

I have a script to solve a sudoku, but i should read file who is in this format

1. 3. 5.
1. 4. 3.
1. 6. 6.
1. 7. 7.
2. 2. 9.
2. 5. 7.
2. 8. 1.
3. 1. 6.
3. 4. 1.
3. 6. 2.
3. 9. 5.
4. 1. 4.
4. 3. 9.
4. 7. 8.
4. 9. 3.
5. 2. 5.
5. 8. 6.
6. 1. 7.
6. 3. 6.
6. 7. 9.
6. 9. 1.
7. 1. 5.
7. 4. 7.
7. 6. 9.
7. 9. 8.
8. 2. 3.
8. 5. 2.
8. 8. 9.
9. 3. 1.
9. 4. 8.
9. 6. 3.
9. 7. 4.

my script get in parametre

suduko(A1,A2,A3,A4,A5,A6,A7,A8,A9,
B1,B2,B3,B4,B5,B6,B7,B8,B9,
C1,C2,C3,C4,C5,C6,C7,C8,C9,
D1,D2,D3,D4,D5,D6,D7,D8,D9,
E1,E2,E3,E4,E5,E6,E7,E8,E9,
F1,F2,F3,F4,F5,F6,F7,F8,F9,
G1,G2,G3,G4,G5,G6,G7,G8,G9,
H1,H2,H3,H4,H5,H6,H7,H8,H9,
I1,I2,I3,I4,I5,I6,I7,I8,I9)

and i should replace some of them by the value in the file, for example here A3= 5, and A4 =3

i don't know how can i read this file and use the variable in my code.

Thanks

Kevin Cox
  • 3,080
  • 1
  • 32
  • 32
parik
  • 2,313
  • 12
  • 39
  • 67

1 Answers1

2

after saving in a file named 'sudoku.txt' your data, read_file/2 yields the parameters list needed, then, using univ (=..) to join functor (predicate name) and arguments:

?- Pred = suduko(
    A1,A2,A3,A4,A5,A6,A7,A8,A9,
    B1,B2,B3,B4,B5,B6,B7,B8,B9,
    C1,C2,C3,C4,C5,C6,C7,C8,C9,
    D1,D2,D3,D4,D5,D6,D7,D8,D9,
    E1,E2,E3,E4,E5,E6,E7,E8,E9,
    F1,F2,F3,F4,F5,F6,F7,F8,F9,
    G1,G2,G3,G4,G5,G6,G7,G8,G9,
    H1,H2,H3,H4,H5,H6,H7,H8,H9,
    I1,I2,I3,I4,I5,I6,I7,I8,I9),
Pred =.. [_|B], read_file('sudoku.txt', B), call(Pred).

read_digit(Stream, Digit) :-
    read(Stream, Digit), integer(Digit), Digit >= 1, Digit =< 9.

read_cell(Stream, Matrix) :-
    read_digit(Stream, RowIx),
    read_digit(Stream, ColIx),
    read_digit(Stream, Val),
    CellIx is (RowIx-1)*9 + ColIx,
    nth1(CellIx, Matrix, Val),
    !, read_cell(Stream, Matrix).
read_cell(_Stream, _Matrix).

read_file(Path, Bindings) :-
    open(Path, read, Stream),
    read_cell(Stream, Bindings),
    close(Stream).

% test
read_file :- read_file('sudoku.txt', B), write(B), nl.
CapelliC
  • 59,646
  • 5
  • 47
  • 90
  • I did what you proposed, i have this error: | ?- read_file. uncaught exception: error(syntax_error('sudoku.txt:1 (char:7) } or operator expected'),read/2) – parik Jan 03 '16 at 15:57
  • I tested with latest GnuProlog. Maybe your sudoku.txt is not correct ? Each number must be *immediatly* followed by a dot – CapelliC Jan 03 '16 at 16:21
  • Yes, it was a error in format of file, but now i have this error: yes | ?- readfile. uncaught exception: error(existence_error(procedure,readfile/0),top_level/0) | ?- – parik Jan 03 '16 at 16:31
  • thanks a lot, it works, last question, why do you put ( .. ) after = in : Pred =.. [_|B], read_file('sudoku.txt', B), call(Pred). – parik Jan 03 '16 at 16:39
  • It's called univ, a specialized operator. See [=..](http://www.swi-prolog.org/pldoc/doc_for?object=%28%3D..%29/2) – CapelliC Jan 03 '16 at 17:00