问题描述
我一直在尝试将给定列表拆分为两个不同的列表:唯一列表和重复列表.例如,如果我们有列表 [1, 1, 2, 3, 3, 4, 5]
我希望唯一列表是 [2, 4, 5]
并复制为 [1, 3]
.我不希望列表中的所有 1 都在重复列表中.我只需要其中之一.我现在的代码:
I have been trying to split a given list into two different lists: Unique and Duplicate.For example, if we have the list [1, 1, 2, 3, 3, 4, 5]
I want the Unique list to be [2, 4, 5]
and Duplicate to be [1, 3]
.I don't want all the 1's in the list to be in the Duplicate list. I just need one of it.The code I have right now:
compareL([_|[]], Unique, Dup).
compareL([X3,Y3 | Tail], [X3 | Unique], Dup) :-
X3 == Y3,
compareL([Y3 | Tail], Unique, Dup).
compareL([X3,Y3 | Tail], Unique, [X3 | Dup]) :-
X3 = Y3,
skipDups(X3, Tail, Unique, Dup).
skipDups(_, [], Unique, Dup).
skipDups(X3,[Y3 | Tail], Unique, Dup) :-
X3 == Y3,
compareL([Y3 | Tail], Unique, Dup).
skipDups(X3,[Y3 | Tail], Unique, Dup) :-
X3 = Y3,
skipDups(X3, Tail, Unique, Dup).
如果我运行 compareL([1, 1, 2, 3, 3, 4, 5], Unique, Dup),使用上面给出的示例列表.
我得到:
Using the example list given above if I run compareL([1, 1, 2, 3, 3, 4, 5], Unique, Dup).
I get:
Unique = [2, 4|_G1954],
Dup = [1, 3|_G1948].
我无法弄清楚为什么在两个列表的末尾我都会得到_G1954
"和_G1948
".任何帮助,将不胜感激.谢谢.
I can't figure out why towards the end of both lists I am getting '_G1954
' and '_G1948
'. Any help would be appreciated. Thanks.
推荐答案
这里有一个解决方案,关键是 take/4 消耗所有匹配的前导项,从而可以轻松测试列表( [_|_]
匹配任何包含至少 1 个元素的列表)
here is a solution, the key is take/4 that consumes all matching leading items, thus enabling easy testing of the list ( [_|_]
matches any list of at least 1 element )
compareL([], [], []).
compareL([X|Xs], U, D) :-
( take(X, Xs, [_|_], Ys)
-> compareL(Ys, U, B), D = [X|B]
; compareL(Xs, A, D), U = [X|A]
).
take(X, [X|Xs], [X|R], Ys) :-
!, take(X, Xs, R, Ys).
take(_, Ys, [], Ys).
这篇关于Prolog:将列表拆分为两个列表(唯一项/重复项)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!