Prolog 可能删除列表中的元素 [英] Prolog possible removal of elements in a list

查看:28
本文介绍了Prolog 可能删除列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求尝试搜索所有可能的结果,从列表中的任何单个元素中删除任何数字.

I have been asked to try to search for all possible outcomes of, removing any numbers from any single elements from a list.

例如,如果我有一个列表 X = [1,2,3]

For example, if I have a list X = [1,2,3]

remove(X, Y)

我的结果是:

Y = [2,3]
Y = [1,1,3]
Y = [1,3]
Y = [1,2,2]
Y = [1,2,1]
Y = [1,2]

为此,我已经编写了 2 个解决方案,但我真的不知道我的解决方案有什么缺点.我的教授一直告诉我有更好的方法来做到这一点.

For this, I have already written 2 solutions, but I don't really know what is the cons of my solutions. My professor keeps telling me that there is a better way of doing this.

我的第一种方法:

test(S1, S2):-
    length(S1, L),
    M is L -1,
    between(0, M, N),
    remove(S1, S2, N).
remove([H|T], [H2|T2], Heap):-
    (
        Heap>0->
        H2 = H,
        remove(T, T2, Heap-1);
        between(1, H, N),
        H2 is H - N,
        T2 = T
    ).

我的第二种方法:

remove1([H|T], [H|TY]):-
    not(T=[]),
    remove1(T, TY).
remove1([H|T], S2):-
    between(1, H, X),
    HY is H - X,
    (   HY = 0-> S2 = T; S2=[HY|T]).

这两种方法都给出了相同的结果,但我真的很想知道如何才能做得更好.有人介意给我一些建议吗?

Both of the approaches are giving the same result, but I do really want to know how I can do it better. Would anyone mind giving me some advice please?

推荐答案

你必须:

  • 从列表中选择一项(数字)
  • 用小于所选项目的数字替换所选项目
  • 或者完全删除所选项目

例如:

remove([N|Tail], [NX|Tail]):-
  succ(N1, N),
  between(1, N1, NX).
remove([_|Tail], Tail).
remove([N|Tail], [N|NTail]):-
  remove(Tail, NTail).

第一个子句选择列表中的第一项,并将该项替换为小于该项的数字.

The first clause selects the first item in the list, and replaces that item with a number which is less than the item.

第二个子句从列表中删除该项目(如您的示例所示,当您将 N 减去所选项目 (N) 时,它不会出现在第二个列表中.

The second clause removes the item from the list (as shown in your examples when you subtract N to the selected item (N) it does not appear in the second list.

第三个子句应用递归,将头项保持原样并将过程应用于其余列表.

The third clause applies recursion, leaving the head item as-is and applies the procedure to the remaining list.

这篇关于Prolog 可能删除列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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