Prolog GNU - 遇到困难,列表和递归
所以,我仍然不完全理解列表和递归在序言中是如何工作的,这可能就是我遇到问题的原因,但我什至不知道如何开始这个问题。
有一个朋友名单。
f(a,b).
f(a,c).
f(a,d).
f(b,c).
f(b,e).
f(b,f).
f(c,e).
f(c,g).
f(g,e).
etc..
我必须通过其他人最多两个朋友的朋友来查找某人是否是朋友。
例如,如果我这样做了
fof(a,e, List).
,那么我应该得到
List = [a, b, e];
List = [a, c, e];
List = [a, c, g, e]; <-- anything past this point won't work
所以基本上你检查自己,然后看看你的朋友是否是 person2 的朋友,然后看看他们的朋友是否是 person2 的朋友,如果他们被添加到列表中。
但不太确定如何执行此操作。
好的,所以我得到了与我需要的类似的东西。
fb(X,X,_).
fb(X,Y,List) :-
friend(X,Y),
X \== Y,
List = [X,Y].
fb(X,Y,List) :-
friend(X,Z),friend(Z,Y),
X \== Y, X \== Z, Z \== Y,
List = [X,Z,Y].
fb(X,Y,List) :-
friend(X,Z),friend(Z,Q),friend(Q,Y),
X \== Y,X \== Z, X \== Q, Z \== Q, Z \== Y, Q \== Y,
List = [X,Z,Q,Y].
这似乎有效,但似乎我可以用递归来压缩它,只是不确定如何。
So , i still don't completely understand how lists and recursion work in prolog, could be why i am having trouble with this, but i don't even know how to begin this problem.
There is a list of friends.
f(a,b).
f(a,c).
f(a,d).
f(b,c).
f(b,e).
f(b,f).
f(c,e).
f(c,g).
f(g,e).
etc..
I have to find if someone is a friend through someone else up to two friends of friends.
So example if i did
fof(a,e, List).
Then i should get
List = [a, b, e];
List = [a, c, e];
List = [a, c, g, e]; <-- anything past this point won't work
So basically you check yourself, then see if your friends is friends with person2, then see if their friends are friends with person2, if they are then add to a list.
not exactly sure how to execute this though.
Ok, so i got something similar to what i need.
fb(X,X,_).
fb(X,Y,List) :-
friend(X,Y),
X \== Y,
List = [X,Y].
fb(X,Y,List) :-
friend(X,Z),friend(Z,Y),
X \== Y, X \== Z, Z \== Y,
List = [X,Z,Y].
fb(X,Y,List) :-
friend(X,Z),friend(Z,Q),friend(Q,Y),
X \== Y,X \== Z, X \== Q, Z \== Q, Z \== Y, Q \== Y,
List = [X,Z,Q,Y].
This seems to work, but it seems i could condense this with recursion, just not sure how.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您已将
friend(X,Y)
定义为 true,如果f(X,Y)
或f(Y,X)
>。您的问题可以通过添加指定允许的最大路径长度的参数并在每次递归调用之前递减该参数来递归解决。
通过 max 联系朋友的朋友。两个中介,即分三步:
I assume you've defined
friend(X,Y)
to be true if eitherf(X,Y)
orf(Y,X)
.Your problem can be solved recursively by adding an argument that specifies the maximum path length allowed, and decrementing that before each recursive call.
To get to a friend of a friend via max. two intermediaries, i.e. in three steps: