如何创建与特定数字相加的数字列表 [英] How to create a list of numbers that add up to a specific number

查看:38
本文介绍了如何创建与特定数字相加的数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助在 Prolog 中编写一个谓词,该谓词将一个数字作为输入,返回一个列表列表,其中的数字相加.

I need some help writing a predicate in Prolog that, given a number as input, returns a list of lists with numbers that add up to it.

让我们调用谓词 addUpList/2,它应该是这样工作的:

Let's call the predicate addUpList/2, it should work like this:

?- addUpList(3,P).
P = [[1,2], [2,1], [1,1,1]].       % expected result

我很难弄清楚这一点,我开始认为这是不可能的.有任何想法吗?提前致谢.

I'm having so much trouble figuring this out I'm beginning to think it's impossible. Any ideas? Thanks in advance.

推荐答案

试试这个:

condense([], Rs, Rs).
condense([X|Xs], Ys, Zs) :-
    condense(Xs, [X|Ys], Zs).
condense([X, Y|Xs], Ys, Zs) :-
    Z is X + Y,
    condense([Z|Xs], Ys, Zs).

condense(Xs, Rs) :-
    condense(Xs, [], Rs).

expand(0, []).
expand(N, [1|Ns]) :-
    N > 0,
    N1 is N - 1,
    expand(N1, Ns).

addUpList(N, Zs) :-
    expand(N, Xs),
    findall(Ys, condense(Xs, Ys), Zs).

让我知道我得到了什么分数.:-)

Let me know what marks I get. :-)

这篇关于如何创建与特定数字相加的数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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