Non Unique Elements
K5, 5 bytes
Assuming the input is already in a variable called d
,
?d^?d
Take the distinct elements (?
) of d except (d^
) the distinct elements of d (?d
). Nicely symmetrical, no? This works because the "except" operator removes only the first occurrence of the right argument from the left argument.
More generally,
nu: {?x^?x}
In action:
nu'(();-1 0 1;1 1;3 0 0 1 1 0 5 3;-34 0 1 -34 4 8 4)
(()
()
,1
0 1 3
-34 4)
Edit:
If we wanted to preserve the order of the first occurrence of non-unique elements, we could reverse the source list before and after we remove the unique elements via except at the cost of 4 extra bytes:
nu: {?|(|x)^?x}
nu'(();-1 0 1;1 1;3 0 0 1 1 0 5 3;-34 0 1 -34 4 8 4)
(()
()
,1
3 0 1
-34 4)
CJam, 10
Assuming the array is already in variable D (based on this comment):
D{De=(},_&
Try it online
Explanation:
D{…}, filter items of D based on the block
De= count occurrences in D
( decrement (resulting in true/false for duplicate/unique)
_& remove duplicates from the results
Note: append a p
if you want pretty printing, otherwise the resulting array is just printed out with no delimiters by default. That is acceptable since the question specifies the snippet only needs to "evaluate to the correct result".
Standard input/output version, 13:
q~_{1$e=(},&p
Try it online
Explanation:
q~ read and evaluate the input array
_ duplicate the array
{…}, filter items based on the block
1$ copy the array
e= count occurrences
( decrement (resulting in true/false for duplicate/unique)
& set intersection with the initial array (removes duplicates)
p pretty print
Haskell - 32
import Data.List;f l=nub$l\\nub l
Pretty short, even with the import. a \\ b
removes the first occurrence of each element of b
from a
, and nub
makes all elements of a list unique.