0

Does anybody know how I can go about determining/ensuring that there is exactly one duplicate element in a prolog list?

I am studying for a test.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • I have written a method called count(X,Y,Z), which binds Z to the number of times X occurs in the list Y. I am trying to work off that but I am not sure which direction to go in – user1895814 Oct 15 '13 at 06:55

2 Answers2

6

Sort the list using sort/2. It removes duplicates, so if the sorted list is exactly one shorter, you had exactly one pair.

one_duplicate(L) :-
    sort(L, Sorted),
    length(L, Len),
    length(Sorted, SortedLen),
    Len =:= SortedLen + 1.

Finding the duplicate pair is another question altogether.

  • Nice! I have an urge to put sort/2 last, even, if this would not improve the program. – false Oct 15 '13 at 11:54
  • @false I thought about it. I wrote the code after I wrote the free text, so hence the order. It would also make it necessary to use `is` or `succ` for the length of _SortedLen_ and that feels a bit strange. –  Oct 15 '13 at 11:58
  • 1
    The biggest downside of putting sort/2 last, would be that there is no longer a clean instantiation error for a partial list. Think of `one_duplicate(L)` or `one_duplicate([a|L])`. – false Oct 15 '13 at 12:01
-2
one_duplicate(L) :-
    sort(L, Sorted),
    length(L, Len),
    length(Sorted, SortedLen),
    Len =:= SortedLen + 1.
user2807083
  • 2,962
  • 4
  • 29
  • 37