如何从 Prolog 中的数组中删除特定外观的元素?

发布于 2024-10-01 00:40:36 字数 165 浏览 3 评论 0原文

我想仅删除给定数组中每个元素的第二次出现并将结果返回到新数组中。给定的数组可以包含原子元素,但也可以包含类似列表的元素。
谓词应该这样调用:delete_second(L1,L2).
L1=[1,2,4,1,[1,2,3,[4]],2,1]
L2=[1,2,4,[1,3,[]],2,1]。

I want to delete only second appearance of each element in given array and return the result in a new array. The given array can have have atomic elements but also can have list like element within it.

the predicate should be called like this: delete_second(L1,L2).
L1=[1,2,4,1,[1,2,3,[4]],2,1]
L2=[1,2,4,[1,3,[]],2,1].

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溺孤伤于心 2024-10-08 00:40:36

您可以使用两个累加器列表。在一个累加器中,您将拥有仅出现一次的项目,而在另一个累加器上,您将拥有出现多次的项目。
因此,您必须遍历输入列表的所有项目,更新这些累加器,并根据需要从输出列表中选择和丢弃该项目。

像这样的东西:

delete_second(In, Out):-
delete_second(In, [], [], _, _, Out).

delete_second([], Once, Twice, Once, Twice, []):- !.
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [Y|Out]):-
  delete_second(X, Once, Twice, MOnce, MTwice, Y),
  !,
  delete_second(Tail, MOnce, MTwice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
  member(X, Twice),
  !,
  delete_second(Tail, Once, Twice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, Out):-
  append(OnceP, [X|OnceT], Once),
  append(OnceP, OnceT, MOnce),
  !,
  delete_second(Tail, MOnce, [X|Twice], NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
  !,
  delete_second(Tail, [X|Once], Twice, NOnce, NTwice, Out).

You might use two accumulator lists. In one accumulator you would have the items that appeared just once, and on the other accumulator you would have the items that appeared more than once.
So you would have to go through all the items of the input list updating those accumulators and selecting and discarding the item from the output list if required.

Something like:

delete_second(In, Out):-
delete_second(In, [], [], _, _, Out).

delete_second([], Once, Twice, Once, Twice, []):- !.
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [Y|Out]):-
  delete_second(X, Once, Twice, MOnce, MTwice, Y),
  !,
  delete_second(Tail, MOnce, MTwice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
  member(X, Twice),
  !,
  delete_second(Tail, Once, Twice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, Out):-
  append(OnceP, [X|OnceT], Once),
  append(OnceP, OnceT, MOnce),
  !,
  delete_second(Tail, MOnce, [X|Twice], NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
  !,
  delete_second(Tail, [X|Once], Twice, NOnce, NTwice, Out).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文