fork download
  1. % 色の定義
  2. color(red).
  3. color(green).
  4. color(blue).
  5. color(yellow).
  6.  
  7. % 隣接関係(横浜18区の隣接を以下のように定義、実際は調整してください)
  8. adjacent(鶴見, 神奈川).
  9. adjacent(鶴見, 港北).
  10. adjacent(神奈川, 西).
  11. adjacent(神奈川, 港北).
  12. adjacent(西,).
  13. adjacent(,).
  14. adjacent(, 港南).
  15. adjacent(港南, 磯子).
  16. adjacent(磯子, 金沢).
  17. adjacent(金沢,).
  18. adjacent(, 港南).
  19. adjacent(, 保土ケ谷).
  20. adjacent(保土ケ谷, 西).
  21. adjacent(保土ケ谷,).
  22. adjacent(, 瀬谷).
  23. adjacent(瀬谷,).
  24. adjacent(, 戸塚).
  25. adjacent(戸塚,).
  26. adjacent(都筑, 港北).
  27. adjacent(都筑, 青葉).
  28. adjacent(都筑,).
  29. adjacent(港北, 鶴見).
  30. adjacent(, 青葉).
  31. adjacent(保土ケ谷,).
  32.  
  33. % 隣接は双方向である
  34. adjacent_undirected(X,Y) :- adjacent(X,Y).
  35. adjacent_undirected(X,Y) :- adjacent(Y,X).
  36.  
  37. % 隣接区と色がかぶらないか確認
  38. safe_color(_, _, []).
  39. safe_color(District, Color, [OtherDistrict-OtherColor | Rest]) :-
  40. (adjacent_undirected(District, OtherDistrict) -> Color \= OtherColor ; true),
  41. safe_color(District, Color, Rest).
  42.  
  43. % 順番に色を割り当てる
  44. assign_colors([], Assigned, Assigned).
  45. assign_colors([D|Ds], AssignedSoFar, Assigned) :-
  46. color(Color),
  47. safe_color(D, Color, AssignedSoFar),
  48. assign_colors(Ds, [D-Color|AssignedSoFar], Assigned).
  49.  
  50. % 18区リスト(順序固定)
  51. districts([鶴見, 神奈川, 西,,, 港南,
  52. 磯子, 金沢,, 保土ケ谷,, 瀬谷,
  53. , 戸塚, 都筑, 港北,, 青葉]).
  54.  
  55. % 結果表示
  56. print_colors([]).
  57. print_colors([D-C|Rest]) :-
  58. write(D), write(' -> '), write(C), nl,
  59. print_colors(Rest).
  60.  
  61. % 実行
  62. run :-
  63. districts(Ds),
  64. assign_colors(Ds, [], Assigned),
  65. write('4色で塗り分け可能です。'), nl,
  66. reverse(Assigned, AssignedReversed),
  67. print_colors(AssignedReversed).
  68.  
  69.  
Success #stdin #stdout #stderr 0.05s 7100KB
stdin
Standard input is empty
stdout
4色で塗り分け可能です。
鶴見 -> red
神奈川 -> green
西 -> red
中 -> green
南 -> red
港南 -> green
磯子 -> red
金沢 -> green
栄 -> red
保土ケ谷 -> blue
旭 -> red
瀬谷 -> green
泉 -> red
戸塚 -> green
都筑 -> red
港北 -> blue
緑 -> green
青葉 -> blue
stderr
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit