用于确定列表中任意两对是否具有相同和的 prolog 程序 [英] prolog program for determining whether any two pairs in a list have the same sum

查看:47
本文介绍了用于确定列表中任意两对是否具有相同和的 prolog 程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 prolog 中编写一个关系来确定列表中是否有任何两对具有相同的总和.如果不存在总和相等的对,则该关系应该失败.如果列表包含少于四个元素,该关系也应该失败.

How can I write a relation in prolog that determines if there are any two pairs in a list with the same sum. The relation should fail if there exist no pairs whose sums are equal. The relation should also fail if the list contains less than four elements.

  • list([1 2 3]) 失败,因为它只有 3 个元素
  • list([2 3 4 1]) 成功,因为 2+3=4+1
  • list([3 1 2 4 5 6]) 成功,因为 5+1=2+4
  • list([1 8 20 100]) 失败,因为没有相等的对

推荐答案

所以我咨询了我的教授,因为我们的截止日期已过,他同意我发布我对此问题的解决方案.这可能不是解决问题的最简洁的方法,我有点依赖我的 Scheme,但它似乎有效:

So I checked with my professor and since our deadline has passed, he is OK with me posting my solution to this problem. This is probably not the most succinct way to solve the problem, and I'm leaning on my Scheme a bit, but it appears to work:

%car operations
    car([],null).
    car([X|_],X).
   cadr([_|L],R) :-
    car(L,R).
  caddr([_|L],R) :-
    cadr(L,R).

%cdr operations
   cdr([],[]).
   cdr([_|L],L).
  cddr([_|L],R) :-
    cdr(L,R).
 cdddr([_|L],R) :-
    cddr(L,R).

%two-pair operation
%  This algorithm is based on the provided example
%  solution for CSC388FA09HW4.
long-enough(L,_) :-
    length(L,X),
    X>3.
too-long(L,_) :-
    length(L,X),
    X>4.
two-pair([Head|Tail]) :-
    long-enough([Head|Tail],_),
    (
        (car(Tail,N2),cadr(Tail,N3),caddr(Tail,N4),Head+N2=:=N3+N4);
        (cadr(Tail,N2),car(Tail,N3),caddr(Tail,N4),Head+N2=:=N3+N4);
        (caddr(Tail,N2),car(Tail,N3),cadr(Tail,N4),Head+N2=:=N3+N4)
    );
    too-long([Head|Tail],_),
    (
        two-pair(Tail);
        cdr(Tail,N2),two-pair([Head|N2]);
        car(Tail,N2),cddr(Tail,N3),two-pair([Head|[N2|N3]]);
        car(Tail,N2),cadr(Tail,N3),cdddr(Tail,N4),two-pair([Head|[N2|[N3|N4]]])).

这篇关于用于确定列表中任意两对是否具有相同和的 prolog 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆