1

在我陈述这一点之前,我从逻辑上理解了这个问题的解决方案,只是很难对其进行编码。一家四口试图在夜间过桥。一个人过桥需要手电筒,只能两个人同时过桥,以两人中较慢的速度移动。父亲在 1 分钟内过桥,母亲在 2 分钟内过桥,孩子在 5 分钟内过桥,奶奶在 10 分钟内过桥。我正在尝试编写一个 Prolog 程序来处理此类问题,但适用于以任何速度移动的任何规模的家庭。总穿越时间必须小于最大指定时间。我们以事实形式获得了这些家庭family(Name,[X1/T1,X2/T2...etc])。我们被要求定义一个谓词MoveFamily(FamilyName, MAxTime, Moves, Time)wherefamilyNameMax time是绑定变量,moves 绑定到将每个人从一侧穿越到另一侧所采取的移动,time 绑定到它所花费的总时间。这是我到目前为止所拥有的:

moveSouth(North,South,Moves,Time):-
   member(X/T1,North), % x is a member of the north list
   member(Y/T2,North), %y is a member of the north list
   X \= Y, 
   Big is max(T1,T2),
   select(X/T1, North, List2), %List2 is North with x removed
   select(Y/T2, List2, NewNorth), %newNorth is north with x and y removed
   New is Time+Big, %new time is old time plus maximum time
   moveNorth(NewNorth, [X/T1,Y/T2|South], [X+Y|Moves], New).

moveNorth([],_,[],_,_). %this will be the last move
moveNorth(North,South,Moves,Time):-
   member(X/T1,South),
   select(X/T1, South, NewSouth),
   New is Time + T1,
   moveSouth([X/T1|North], NewSouth, [X|Moves], New).

getList(Name,List):-
   family(Name,List).

moveFamily(Name, Max, Moves, Time):-
   getList(Name,People),
   Time =< Max,
   moveSouth(People, [], Moves, Time).

family(two, [fred/1, george/2]).

当我运行这个事实时family(two, [fred/1, george/2])。我得到:

[debug]  ?- moveFamily(two,20,Moves,Time).
ERROR: Arguments are not sufficiently instantiated
ERROR: In:
ERROR:    [9] _10170=<20
ERROR:    [8] moveFamily(two,20,_10200,_10202) 
ERROR:    [7] <user>
Exception: (9) _9500=<20 ? creep
Exception: (8) moveFamily(two, 20, _9498, _9500) ? creep

有谁知道为什么这不起作用?

编辑:一次穿过两个时,它们以较慢成员的速度移动

编辑2:家庭“二”是family(two, [fred/1, george/2])

edit3:查询的所需输出moveFamily(two,20,Moves,Time)应该是

  Moves = [fred+george],
  Time = 2 

编辑4:我把家庭事实放在代码块中,我是个傻瓜,应该意识到这就是你的意思哈哈

4

1 回答 1

1

一夜之间出现了一些奇怪的评论。

这似乎有效:

moveFamily(Name,Max,Moves,Time) :-
  getList(Name,People),
  moveSouth(People,[],Moves,Time),
  Time =< Max.

getList(Name,List) :-
  family(Name,List).

moveSouth(North,South,[X+Y|Moves],New) :-
  member(X/T1,North), member(Y/T2,North), X \= Y,
  Big is max(T1,T2),
  select(X/T1,North,List2), select(Y/T2,List2,NewNorth),
  moveNorth(NewNorth,[X/T1,Y/T2|South],Moves,Time), New is Time + Big.
moveSouth([],_,[],0).

moveNorth(North,South,[X|Moves],New) :-
  member(X/T1,South), select(X/T1,South,NewSouth),
  moveSouth([X/T1|North],NewSouth,Moves,Time), New is Time + T1.
moveNorth([],_,[],0).

加法:当你[X|Moves]在递归调用的参数 #3 中说时,这意味着你正在从调用中分离返回值,但你想要做的是添加X到它,当你把它放在头部时会发生这种情况子句代替。

于 2018-04-06T11:23:00.903 回答