0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Prolog演習 ハノイの塔を解くコード

0
Posted at

swi-prologがインストールされている環境を想定しています。
swipl hanoi.plで実行してください。 底まで来たときには、カットオペレータ!を使っています。

hanoi.pl
:- encoding(utf8).
% hanoi.pl
% カットオペレータ (!) を使ってハノイの塔を解く
%
% 使い方:  swipl hanoi.pl
%   ?- hanoi(3).

:- initialization(main, main).

%% hanoi(+N) : N 枚の円盤を「左」から「右」へ「中」を経由して移動する
hanoi(N) :-
    format("~w 枚の円盤を移動します~n", [N]),
    move(N, '左', '右', '中', 0, Count),
    format("合計 ~w 手で完了しました~n", [Count]).

%% move(+N, +From, +To, +Via, +C0, -C)
%  C0: これまでの手数, C: 移動後の手数
%  N = 0 のときは何もしない。カットで再帰節への後戻りを防ぐ
move(0, _, _, _, C, C) :- !.
move(N, From, To, Via, C0, C) :-
    N1 is N - 1,
    move(N1, From, Via, To, C0, C1),          % 上の N-1 枚を経由地へ
    C2 is C1 + 1,
    format("~w 手目: 円盤 ~w を ~w から ~w へ~n", [C2, N, From, To]),
    move(N1, Via, To, From, C2, C).           % N-1 枚を目的地へ

main :-
    hanoi(3). % ()内は円盤の数
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?