计算列表中正好三个值的总和是否等于 N [英] Calculate whether the sum of exactly three values in a list is equal to N

查看:52
本文介绍了计算列表中正好三个值的总和是否等于 N的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:([1,2,3,7,6,9], 6). 应该打印 True,如 1+2+3=6.

Examples: ([1,2,3,7,6,9], 6). should print True, as 1+2+3=6.

([1,2,3,7,6,9], 5). 应该打印 False 因为没有三个数字之和为 5.

([1,2,3,7,6,9], 5). should print False as there are no three numbers whose sum is 5.

([],N) 其中 N 等于任何东西都应该是假的.

([],N) where N is equal to anything should be false.

只需要使用这些结构:

  • 必须定义一个单个子句(不允许超过一个子句).
  • 只允许以下内容:

  • A single clause must be defined (no more than one clause is allowed).
  • Only the following is permitted:

+, ,, ;, ., !, :-, is, Lists -- 列表类型、变量的头部和尾部语法.

+, ,, ;, ., !, :-, is, Lists -- Head and Tail syntax for list types, Variables.

根据我的理解,我已经完成了一个基本的编码.

I have done a basic coding as per my understanding.

findVal([Q|X],A) :-
   [W|X1]=X,
   [Y|X2]=X,
   % Trying to append the values.
   append([Q],X1,X2),
   % finding sum.
   RES is Q+W+Y,
   % verify here.
   (not(RES=A)->

   % finding the values.

   (findVal(X2,A=)->

true   

;
(findVal(X,A)->   

% return result.

true
;
% return value.

false))
;
% return result.

true
).

它似乎没有运行抛出以下错误.

It does not seem to run throwing the following error.

错误:

未定义过程:findVal/2(DWIM 无法纠正目标)

Undefined procedure: findVal/2 (DWIM could not correct goal)

有人可以帮忙吗?

推荐答案

您可以使用 append/3 [swi-doc] 在这里从列表中选择一个元素,并访问其余元素(该元素之后的元素).通过三次应用这种技术,我们从列表中获得了三个项目.然后我们可以匹配这些元素的总和:

You can make use of append/3 [swi-doc] here to pick an element from a list, and get access to the rest of the elements (the elements after that element). By applying this technique three times, we thus obtain three items from the list. We can then match the sum of these elements:

sublist(L1, S) :-
    append(_, [S1|L2], L1),
    append(_, [S2|L3], L2),
    append(_, [S3|_], L3),
    S is S1 + S2 + S3.

这篇关于计算列表中正好三个值的总和是否等于 N的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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