As a generalization of DeleteDuplicates
, I want to delete duplicates from a list, but only after n
number of duplicates.
Say, n = 3
means that three duplicates are allowed.
I made my own function:
DeleteDuplicatesN[x_, n_] :=
x[[
Sort[
Flatten[#[[1 ;; Min[Length[#], n]]]& /@
(Flatten[Position[x, #]]& /@ DeleteDuplicates[x])]]]]
DeleteDuplicatesN[{1, 2, 3, 2, 1, 1, 1, 2, 3, 5, 5, 5, 5, 1, 7, 4, 7, 1}, 3]
{1, 2, 3, 2, 1, 1, 2, 3, 5, 5, 5, 7, 4, 7}
Is there a better method — faster or more elegant?
For example, using only DeleteDuplicates
or DeleteDuplicatesBy
?