Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.68 KB | None | 0 0
  1. % lights_out_io.pl
  2.  
  3. :- module(lights_out_io, [
  4.               read_board/3,
  5.               write_solution/1
  6.              ]).
  7. :- use_module(lights_out_board).
  8.  
  9. % A line of input is made of
  10. % characters representing lights on (W, * or 1)
  11. % and characters that represent lights off (everything else).
  12.  
  13. % light_on_code(?C).
  14. %
  15. % True if C when C is a character code for a "light on" character.
  16.  
  17. light_on_code(87). % W
  18. light_on_code(42). % *
  19. light_on_code(49). % 1
  20.  
  21. % codes_to_lights(+Y, +Cs, -Ls).
  22. %
  23. % Translates a list of characters representing the lights of
  24. % a line in a (possibly empty) list of lights structures l(X, Y)
  25. % for each light on.
  26.  
  27. codes_to_lights(Y, Cs, Ls) :- codes_to_lights_impl(Y, Cs, 0, Ls).
  28.  
  29. codes_to_lights_impl(_, [], _, []).
  30. codes_to_lights_impl(Y, [C|Cs], X, Ls) :-
  31.     (   light_on_code(C) -> Ls = [l(X, Y)|Rs] ; Ls = Rs   ),
  32.     X1 is X + 1, codes_to_lights_impl(Y, Cs, X1, Rs).
  33.  
  34.  
  35. % read_line_to_lights(+Y, -Ls).
  36. %
  37. % Read a line from the console
  38. read_line_to_lights(Y, Ls) :-
  39.     current_input(S), read_line_to_codes(S, Cs),
  40.     codes_to_lights(Y, Cs, Ls).
  41.  
  42. % read_board(+W, +H, -B).
  43. %
  44. % Read a board of size WxH from the console and unify it with B.
  45.  
  46. read_board(W, H, b(W, H, Ls)) :-
  47.     W > 0, H > 0, read_board_impl(W, H, 0, [], Ls0),
  48.     sort(Ls0, Ls).
  49.  
  50. read_board_impl(W, H, Y, AccLs, Ls) :-
  51.     Y >= 0, Y < H,
  52.     read_line_to_lights(Y, LineLs),
  53.     append(AccLs, LineLs, NextAccLs),
  54.     NextY is Y + 1,
  55.     read_board_impl(W, H, NextY, NextAccLs, Ls).
  56. read_board_impl(_, H, Y, Ls, Ls) :- Y >= H.
  57.  
  58.  
  59. % write_solution(+Ms)
  60. %
  61. % Write a solution to the console.
  62.  
  63. write_solution(Ms) :- ignore(write_solution_impl(Ms)).
  64.  
  65. write_solution_impl(Ms) :-
  66.     member(l(X,Y), Ms),
  67.     write((X,Y)), nl,
  68.     fail.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement