【问题标题】:List containing indexes of equal elements包含相等元素索引的列表
【发布时间】:2017-04-10 22:58:48
【问题描述】:

我正在尝试定义一个谓词,它将 3 个列表作为参数,第三个列表包含其他两个列表中的元素相同的索引。

这是我解决问题的尝试。

sameIndex(List1, List2, List3) :- findIndex(List1,List2,0, List3).

% Helper Function 

% Base cases
findIndex([],_,_,[]).
findIndex(_,[],_,[]).

findIndex([Head1|Tail1], [Head2|Tail2], Count, List4):-
    Head1 == Head2, append([Count], List4, FinalList), NewCount is Count+1,
    findIndex(Tail1,Tail2,NewCount,FinalList); NewCount is Count+1,
    findIndex(Tail1,Tail2,NewCount, List4).

示例测试用例:

sameIndex([1,2,3,4], [6,2,4,4], 列表)

应该返回

列表 = [1,3]

我的逻辑是:如果列表的头部相等,则将 Count(跟踪我们所在的索引)附加到我们的空 List4,递增 Count,然后递归调用带有两个列表尾部的谓词。否则,递增 Count 并递归调用带有尾部的谓词。

我假设我的代码在 prolog 中对算术的使用不当,但我就是无法让它工作。任何建议/帮助表示赞赏。

【问题讨论】:

  • 您需要的是一个累加器模式,这样在每个递归步骤中,您都会构建一个有效索引列表,然后将其传递到下一步。一旦您达到基本情况,您的List4 应该会统一到累积列表中。您在这里执行的方式,List4 是您最初传入的任何内容,然后附加内容,这不是您想要的。更不用说,即使您使用变量调用它,您也永远不会尝试将 List4 与任何东西统一。

标签: list indexing prolog


【解决方案1】:

这是您的代码已更正并重新格式化,使用“标准”缩进

findIndex([Head1|Tail1], [Head2|Tail2], Count, List4):-
    ( Head1 == Head2,
      append([Count], FinalList, List4),
      NewCount is Count+1,
      findIndex(Tail1,Tail2,NewCount,FinalList)
    ; NewCount is Count+1,
      findIndex(Tail1,Tail2,NewCount, List4)
    ).

您的错误是将参数反转为 append/3。 另一个问题是返回多个解决方案 - 其中一些是错误的,因此您应该使用 if/then/else 构造,并区分两种基本情况:

findIndex([],_,_,[]) :- !.
findIndex(_,[],_,[]).

findIndex([Head1|Tail1], [Head2|Tail2], Count, List4):-
    ( Head1 == Head2
    ->append([Count], FinalList, List4),
      NewCount is Count+1,
      findIndex(Tail1,Tail2,NewCount,FinalList)
    ; NewCount is Count+1,
      findIndex(Tail1,Tail2,NewCount, List4)
    ).

但代码可以简单得多,使用一些库助手:

sameIndex(List1, List2, List3) :-
  findall(P, (nth0(P,List1,E), nth0(P,List2,E)), List3).

与您的解决方案不同,此解决方案适用于任何长度的列表...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2020-02-08
    相关资源
    最近更新 更多