Non Unique Elements

24

2

Write a program which finds the non-unique elements of an array of signed integers. The resulting array can be in any order.

Your answer may be a snippet which assumes the input to be stored in a variable (d, say) and evaluates to the correct result.

Test Cases

Each test case is a single line in the format input => output. Note that other permutations of the output are valid as well.

[]                        => []
[-1, 0, 1]                => []
[1, 1]                    => [1]
[3, 0, 0, 1, 1, 0, 5, 3]  => [3, 0, 1]
[-34, 0, 1, -34, 4, 8, 4] => [-34, 4]

Order of the elements doesn't matter.

This is code golf, so the shortest answer (in bytes) wins.

garg10may

Posted 2015-10-13T10:06:35.697

Reputation: 629

4Related – Sp3000 – 2015-10-13T10:11:37.837

1since this is for array of integers code would be different. I think much shorter. That is for a string. – garg10may – 2015-10-13T10:21:01.480

1Are we allowed to accept input as lines instead of as an array? For example, instead of [-1, 0, 1], can we input (replace \n with newlines): "-1\n0\n1"? – Addison Crump – 2015-10-13T15:01:39.413

1Does the output have to be a list or would a set be acceptable? – Dennis – 2015-10-13T15:06:12.190

And does it have to output in that format? – Addison Crump – 2015-10-13T15:06:59.623

Yes, the output needs to be an array, otherwise if iterable is allowed people would start producing 301 as results. – garg10may – 2015-10-14T01:59:47.760

Answers

16

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)

JohnE

Posted 2015-10-13T10:06:35.697

Reputation: 4 632

10

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

aditsu quit because SE is EVIL

Posted 2015-10-13T10:06:35.697

Reputation: 22 326

113: q~$e\{((<~}%p` – Sp3000 – 2015-10-13T10:29:19.273

3@Sp3000 I found another 13-byte version before reading your comment :) It preserves the order too. – aditsu quit because SE is EVIL – 2015-10-13T10:30:35.683

9

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.

C. Quilley

Posted 2015-10-13T10:06:35.697

Reputation: 546

7

Pyth, 7 bytes

S{.-Q{Q

Try it online.

How it works

Pyth automatically stores the evaluated input in Q and prints all unused return values.

     {Q  Convert Q into a set. This removes duplicates.
  .-Q    Perform "bagwise" difference of Q and set(Q).
         This removes the first occurrence of all elements in Q.
 {       Convert to set to deduplicate.
S        Sort. Returns a list.

Dennis

Posted 2015-10-13T10:06:35.697

Reputation: 196 637

7

SQL, 44 42 bytes

SELECT*FROM D GROUP BY I HAVING COUNT(*)>1

I hope it is OK to assume the integers are stored in table D? This will work in both SQLServer, PostgreSQL and possibly others. Thanks to @manatwork from the 2 bytes.

MickyT

Posted 2015-10-13T10:06:35.697

Reputation: 11 735

Assuming i is the only field in table d, in PostgreSQL you can reduce it to select*from d group by 1having count(*)>1. (MySQL and SQLite's parser will also handle the unseparated select*from part, but they not understand 1having.) – manatwork – 2015-10-14T10:04:45.507

@manatwork cheers for that, sql server also understands the select*from. Doesn't like the 1having though.. will leave that as I having – MickyT – 2015-10-14T18:25:26.357

6

Matlab / Octave, 40

I'm assuming input values are real (not complex). The input is in a variable d.

unique(d(sum(triu(bsxfun(@eq,d,d')))>1))

Try it online in Octave.

Luis Mendo

Posted 2015-10-13T10:06:35.697

Reputation: 87 464

No need to input, you can assume data in variable 'd' – garg10may – 2015-10-13T10:49:25.910

1@garg10may Thanks. Updated. You should specify that in your post – Luis Mendo – 2015-10-13T10:56:00.987

The output is incorrect when d = [3, 0, 0, 1, 1, 0, 5, 3]. There are two 0s. – alephalpha – 2015-10-13T13:23:15.900

@alephalpha Thanks! corrected (8 more bytes) – Luis Mendo – 2015-10-13T16:19:05.420

Shorter: d(sum(triu(bsxfun(@eq,d,d')))==2). Or in Octave: d(sum(triu(d==d'))==2) – alephalpha – 2015-10-14T02:59:35.023

@alephalpha Good idea! You should post that as an answer yourself – Luis Mendo – 2015-10-14T09:14:05.067

6

Mathematica, 29 26 bytes

Assuming that input is stored in d:

Select[d⋃d,d~Count~#>1&]

Otherwise, it's 29 bytes as an unnamed function:

Cases[#⋃#,n_/;#~Count~n>1]&

Here, d⋃d (or #⋃#) is a golfing trick to remove duplicates - by taking the set union with itself, Mathematica interprets the list as a set, removing duplicates automatically, while the actual union doesn't do anything.

Afterwards, both methods simply filter those elements which appear in the original list at least twice.

Martin Ender

Posted 2015-10-13T10:06:35.697

Reputation: 184 808

6

APL (Dyalog Unicode), 13 9 bytesSBCS

Anonymous tacit prefix function.

∊(⊂1↓⊣¨)⌸

Try it online!

()⌸ for each unique element (left argument) and the indices where it occurs (right argument), apply the following tacit function:

⊣¨ one of the left (the unique element) for each on the right (the indices)

1↓ drop one

 enclose (prevents padding with zeros to create a non-ragged matrix)

ϵnlist (flatten)

Adám

Posted 2015-10-13T10:06:35.697

Reputation: 37 779

6

PowerShell, 31 29 Bytes

($d|group|?{$_.Count-1}).Name

Assumes that $d is already populated (as given) -- e.g., $d=@(-34,0,1,-34,4,8,4).

Pipes the array into the Group-Object cmdlet, which groups like-items together and spits out an object that's essentially an array of arrays. We pipe that to a Where-Object (the ? operator) that has Count greater than one (i.e., there are duplicates), and output the .Name of those items. Has a side bonus of preserving the initial ordering, too.

Edit - saved two bytes thanks to Danko Durbić

AdmBorkBork

Posted 2015-10-13T10:06:35.697

Reputation: 41 581

1I think you can replace $_.Count-gt1 with $_.Count-1 which would be true for any Count greater than one. – Danko Durbić – 2015-10-13T22:03:51.187

@DankoDurbić Excellent! – AdmBorkBork – 2015-10-14T12:39:11.790

6

JavaScript (ES6), 37 bytes

Run this in the JavaScript console:

e={};d.filter(x=>(e[x]=1+e[x]||0)==1)

Cristian Lupascu

Posted 2015-10-13T10:06:35.697

Reputation: 8 369

It's generally accepted that JavaScript needs some sort of explicit "output/print" function (such as console.log, alert, etc) to be considered complete. If a challenge says "write a program or function", then function returns also suffice. Aside that, very efficient solution! – Mwr247 – 2015-10-13T14:08:02.450

1@Mwr247 The question states that the anwer may be a snippet which evaluates to the correct result. – Cristian Lupascu – 2015-10-13T14:09:52.753

1It seems I misinterpreted that paragraph. Apologies then =) – Mwr247 – 2015-10-13T14:12:19.420

@Mwr247 No problem! :) – Cristian Lupascu – 2015-10-13T14:13:18.013

6

Python 3.5, 30

[x for x in{*d}if~-d.count(x)]

Uses Python 3.5's set unpacking. The ~- subtracts 1, which takes a count of 1 to 0 which is Falsy.

This gives a list. If giving a set is OK, then we use a set comprehension, saving 1 char and not needing version 3.5:

{x for x in d if~-d.count(x)}

xnor

Posted 2015-10-13T10:06:35.697

Reputation: 115 687

SyntaxError: invalid syntax for Python 3 is it valid only for 3.5? When has python started becoming esoteric. – garg10may – 2015-10-14T02:08:03.693

@garg10may Just wait til you see what 3.6 has in store...

– Sp3000 – 2015-10-14T07:45:09.787

1@Sp3000 Awesome. Looks like the same set-up as Scala. Infinitely more readable than more alternatives. – Carcigenicate – 2015-10-15T18:19:34.240

5

Python 2.7, 36 42

list(set(filter(lambda x:d.count(x)>1,d)))

edit : surrounded the expression with list(..) in order to comply with the format required in the question

dieter

Posted 2015-10-13T10:06:35.697

Reputation: 2 010

this will output set not a list – garg10may – 2015-10-13T12:49:27.103

So shall I surround my snippet with a call to list(...) ? – dieter – 2015-10-13T13:33:16.650

Yes the output should be an array only. – garg10may – 2015-10-14T01:59:16.497

5

Python 3 - 33 30 bytes

{_ for _ in d if d.count(_)>1}

Repl output, d as input.

pppery

Posted 2015-10-13T10:06:35.697

Reputation: 3 987

5

R, 31 24 bytes

Thanks to flodel for the 7 bytes.

Assuming the input is already in d.

code:

unique(d[duplicated(d)])

edit: now it outputs correctly if there are more than 2 duplicates as pointed by aditsu.

Mutador

Posted 2015-10-13T10:06:35.697

Reputation: 1 361

2That looks beautiful! But the 4th test case doesn't seem to be correct... – aditsu quit because SE is EVIL – 2015-10-13T14:51:39.283

1You can remove which since [ also accepts a logical argument. – flodel – 2015-10-14T04:31:37.447

5

Julia, 30 29 bytes

∪(d[find(sum(d.==d',1)-1)])

d.==d' creates a symmetric matrix with the value at i,j being true if d[i]==d[j] and false otherwise. summing in one dimension and then subtracting 1 will produce zero if there's only one of the element and nonzero if there's more than one. find will obtain the indexes of the non-zero elements, which are then used to index the array d itself. (union) acts like unique when used in this way, removing the repeats.

Old solution:

∪(filter(i->sum(d.==i)>1,d))

Simple - for each entry, it checks if there's more than one of it in the array. Those for which there are more than one are returned by "filter", and then (union) acts like unique when used in this way, removing the repeats.

Note: originally had it as a function, but question allows array to be stored in a variable, for which I've chosen d as suggested in the question.

Glen O

Posted 2015-10-13T10:06:35.697

Reputation: 2 548

5

Octave, 22 bytes

Based on Luis Mendo's answer.

d(sum(triu(d==d'))==2)

alephalpha

Posted 2015-10-13T10:06:35.697

Reputation: 23 988

4

K (oK), 7 bytes

Solution:

&1<#:'=

Try it online!

Explanation:

&1<#:'= / the solution
      = / group, key => value (index)
   #:'  / count length of each group
 1<     / 1 less than 
&       / keys where true

streetster

Posted 2015-10-13T10:06:35.697

Reputation: 3 635

4

Mathematica, 31 29

Cases[{s_,t_/;t>1}:>s]@*Tally

alephalpha

Posted 2015-10-13T10:06:35.697

Reputation: 23 988

4

Pyth, 7 bytes

ft/QT{Q

Explanation:

ft/QT{Q
           Q = eval(input())
     {Q    set(Q) - deduplicate
f          filter - with T as the filter variable.
  /QT      count in Q of T
 t         minus 1.

The filter removes all elements that appear exactly once from the set of elements.

isaacg

Posted 2015-10-13T10:06:35.697

Reputation: 39 268

4

LINQ,62 54 bytes

Kinda new here, but here goes nothing.

d.GroupBy(c=>c).Where(g=>g.Count()>1).Select(g=>g.Key)

noisyass2

Posted 2015-10-13T10:06:35.697

Reputation: 211

Welcome to the site! I don't know LINQ, but there's some whitespace you can probably remove from this to improve your score. – DLosc – 2015-10-14T02:05:32.017

3

JavaScript, 35 28 bytes

a=>a.filter(o=x=>!(o[x]^=1))

Try It Online!

After posting this, I realised that it was very similar to w0lf's solution.

Shaggy

Posted 2015-10-13T10:06:35.697

Reputation: 24 623

3

Ruby, 30 28 bytes

In the Interactive Ruby Shell:

d.select{|x|d.count(x>1)}|[]

Saved 2 bytes thanks to Kirill L.

Cristian Lupascu

Posted 2015-10-13T10:06:35.697

Reputation: 8 369

1Save 2 bytes: d.select{|x|d.count(x>1)}|[] – Kirill L. – 2018-08-30T09:05:12.723

3

Shell + GNU coreutils, 12

sort|uniq -d

Test output:

$ printf "%s\n" -34 0 1 -34 4 8 4 | ./nonuniq.sh 
-34
4
$ 

Digital Trauma

Posted 2015-10-13T10:06:35.697

Reputation: 64 644

3

Mathematica, 23 bytes

With input stored in d:

Pick[#,#2>1]&@@@Tally@d

As a function, 24 bytes:

Pick[#,#2>1]&@@@Tally@#&

for example, with

d = {3, 0, 0, 1, 1, 0, 5, 3}
Tally@d

returns this:

   {{3, 2},
    {0, 3},
    {1, 2},
    {5, 1}}

(first element of each sublist is the element, second one is frequency of occurrence). Applying to this list Pick[#,#2>1]&@@@ transforms it to

{Pick[3,2>1], Pick[0,3>1], Pick[1,2>1], Pick[5,1>1]}

And where the second argument of Pick evaluates to True the first argument is returned.

LLlAMnYP

Posted 2015-10-13T10:06:35.697

Reputation: 361

3

K (not K5), 10 bytes

x@&1<#:'=x

Assumes input is in x. I thought it'd be fun to do a non-K5 answer!

kirbyfan64sos

Posted 2015-10-13T10:06:35.697

Reputation: 8 730

3

Perl 6, 16 bytes

Assuming the list is stored in $_ you could use any of the following snippets.
( which was specifically allowed )

(--«.BagHash).Set.keys # 23 bytes
keys .Bag (-) .Set # 18 bytes
# U+2216 SET MINUS
keys .Bag∖.Set # 16 bytes in utf8

If you don't care that you get a Bag you could leave off keys .

$_ = [3, 0, 0, 1, 1, 0, 5, 3];
.Bag∖.Set ∋ 3 # True
.Bag∖.Set ∋ 5 # False

None of these have the limitation of only working on signed integers, or even just numbers for that matter.

say keys .Bag∖.Set given |(<a b c d a a c>), 1/3, 2/3 - 1/3;
# (a c 0.333333)

Brad Gilbert b2gills

Posted 2015-10-13T10:06:35.697

Reputation: 12 713

2

Japt, 7 bytes

â £kX â

Try it online!

Explanation:

â £kX â
â         // Get all unique items from the input
  £       // Map X through the results
   kX     //   Remove X from the input
      â   //   Get unique items
-h        // Return the last item

Oliver

Posted 2015-10-13T10:06:35.697

Reputation: 7 160

2

Common Lisp, 57 bytes

(remove-duplicates(remove-if(lambda(x)(<(count x d)2))d))

nanny

Posted 2015-10-13T10:06:35.697

Reputation: 171

2

Octave, 33 bytes

[~,a]=unique(d);d(a)=[];unique(d)
  • Finds the indices of the first occurrence of each unique integer,
  • removes those occurrences, and
  • finds the unique elements of the remaining array.

Here it is on ideone. I've wrapped the snippet in a function so I could call it using all of the sample inputs.

beaker

Posted 2015-10-13T10:06:35.697

Reputation: 2 349

2

Java 8, 80 Bytes

x.stream().filter(i->x.indexOf(i)!=x.lastIndexOf(i)).collect(Collectors.toSet())

Assuming x contains the input List of numbers.

Rnet

Posted 2015-10-13T10:06:35.697

Reputation: 277

2

PHP, 35 37 bytes

Pretty straight forward:

array_diff_key($a,array_unique($a))

As a note: I didn't add the ; at the end of the line, as the questions states:

Your answer may be a snippet which assumes the input to be stored in a variable (d, say) and evaluates to the correct result

So this snippet could be used like this and evaluates to the correct result:

print implode(' ', array_diff_key($a,array_unique($a)));

Another note

The code above works for all test cases provided in the challenge. In those all non-unique characters are at most duplicates. If a element can occur more than two times, another array_unique() would be necessary, which increases the length to 49 bytes:

array_unique(array_diff_key($a,array_unique($a)))

Edits

  • Saved 2 bytes by replacing array_diff_assoc with array_diff_key. Thanks to Jörg Hülsermann.

insertusernamehere

Posted 2015-10-13T10:06:35.697

Reputation: 4 551

1array_diff_key instead array_diff_assoc – Jörg Hülsermann – 2017-05-08T17:48:52.760

@JörgHülsermann Good catch. Thanks. Will take a look at your other suggestions within the next days. – insertusernamehere – 2017-05-10T14:20:43.210

1

Jelly, 4 bytes, language postdates challenge

œ-QQ

Try it online!

Same algorithm as the accepted answer, just a shorter syntax.

user62131

Posted 2015-10-13T10:06:35.697

Reputation:

This look so cryptic 0.o what is that first character? – garg10may – 2017-05-10T02:54:57.930

1

PHP, 75 bytes

function a($b){return array_unique(array_diff_assoc($b,array_unique($b)));}

Try it online!

Luis felipe De jesus Munoz

Posted 2015-10-13T10:06:35.697

Reputation: 9 639

1

Python 2.7, 36 bytes

list({x for x in i if i.count(x)>1})

Where i is the input

Khalil

Posted 2015-10-13T10:06:35.697

Reputation: 49

You'll need to make it a lambda function because snippets aren't allowed. – Nissa – 2018-06-06T17:45:13.833

3 other people did the same thing, and OP doesn't seem to mind – Khalil – 2018-06-06T18:08:40.570

5"Your answer may be a snippet which assumes the input to be stored in a variable". Note that this is not the default, but this question is old and the OP explicitly allowed it, so it is okay. – mbomb007 – 2018-06-06T18:39:18.970

1

05AB1E, 8 6 5 bytes

ʒ¢≠}Ù

Try it online or verify all test cases.

Explanation:

ʒ  }     # Filter the list by:
 ¢       #  Where the count of the current item in the input-list
         #   i.e. [1,2,3,2,1,1,6,4,5,6] and 1 → 3
         #   i.e. [1,2,3,2,1,1,6,4,5,6] and 5 → 1
  ≠      #  is not 1
         #   i.e. 3 → 1 (truthy)
         #   i.e. 1 → 0 (falsey)
    Ù    # After filtering, uniquify the remaining items
         #  i.e. [1,2,2,1,1,6,6] → [1,2,6]

Kevin Cruijssen

Posted 2015-10-13T10:06:35.697

Reputation: 67 575

1

Kotlin, 41 bytes

{it.filter{v->it.count{it==v}>1}.toSet()}

Try it online!

snail_

Posted 2015-10-13T10:06:35.697

Reputation: 1 982

1

Perl 6, 14 bytes

*.repeated.Set

Try it online!

Gets a Set of the repeated elements.

Jo King

Posted 2015-10-13T10:06:35.697

Reputation: 38 234

1

Hassium, 104 Bytes

func main(){r=[];i=[];foreach(e in d)if(!i.contains(e))i.add(e)else if(!r.contains(e))r.add(e);print(r)}

Run online and see expanded here

Jacob Misirian

Posted 2015-10-13T10:06:35.697

Reputation: 737

1

Python, 143 bytes

There are already some very good Python answers out there (see @dieters, @ppperry & @xnor answers) so I decided to take a different approach, have some fun with recursion and python lambda functions and see what could I come up with. This is not even close to the best answers here but it was fun to think.

The program takes the integer list as a parameter of function p and returns a list containing non-unique elements.

p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']

Two line version for better readability:

p=lambda i:[j for j in(lambda n:[]if len(n)<=1 else[(lambda x:x[0]if 
len([1 for o in x[1:]if x[0]==o])==1 else 'N')(n)]+p(n[1:]))(i) if j!='N']

Short Explanation

The inner lambda takes a list x as a parameter and returns the first element of such list if it is repeated only once in the rest of the list (x[1:]). If not it returns 'N'.

The lambda in between the outer and inner lambdas is the one in charge of the recursive search. This returns a list containing the non-unique elements and plenty of 'N's. This is the one which takes the integer list as a parameter.

The outer lambda filters the resulting list getting rid of the unwanted 'N's.

Test cases

p([])
[]
p([-1,0,1])
[]
p([3, 0, 0, 1, 1, 0, 5, 3])
[3,0,1]

Ioannes

Posted 2015-10-13T10:06:35.697

Reputation: 595

1

STATA, 18 bytes

bys v:drop if _n-2

Note that this requires the paid version of STATA.

Assumes the data is stored in a variable v and then the result will be in v at the end. It works by sorting by v and grouping duplicate values together. Each duplicate value will have at least two values, which means it can drop anything that is not the second element of each value. Third and subsequent elements will already be represented and the first element will either be unique or represented by the second.

For example, make a file a.b with data:

3
0
0
1
1
0
5
3

Then run the following code

insheet using a.b,clear
rename v1 v
bys v:drop if _n-2 //the actual code that does stuff
list v,noobs noheader

bmarks

Posted 2015-10-13T10:06:35.697

Reputation: 2 114

1

J, 12 14 13 bytes

~.d#~1<+/=/~d

Assumes the list is in d.

Explanation:

         =/~d   NB. compare each element in d to each element in d
       +/       NB. sum the columns (giving amount of occurrences)
     1<         NB. see which columns are greater than 1 (=not unique)
  d#~           NB. select those elements from d 
~.              NB. unique elements from that

If an anonymous function is OK as well, it can be shortened to 13 12:

~.#~1<+/"1@=

marinus

Posted 2015-10-13T10:06:35.697

Reputation: 30 224

1

C# - 40

i.GroupBy(g=>g).SelectMany(s=>s.Skip(1))

Using select many to be able to use Skip and skip the first occurrence if it exists.

Cooler Ranch

Posted 2015-10-13T10:06:35.697

Reputation: 21

0

JavaScript (Node.js), 60 bytes

f=>[...new Set(f.filter(e=>f.indexOf(e)!=f.lastIndexOf(e)))]

Try it online!

Kamil Naja

Posted 2015-10-13T10:06:35.697

Reputation: 121

0

JavaScript (Node.js), 43 bytes (another try)

a=>a.filter((t={},e=>!(1-(t[e]=++t[e]|0))))

Try it online!

Kamil Naja

Posted 2015-10-13T10:06:35.697

Reputation: 121

0

Burlesque, 9 bytes

peJNB\\NB

Try it online!

pe # Parse and push
J  # Duplicate
NB # Remove duplicate elements
\\ # Difference between nubbed and original lists
NB # Nub the difference

DeathIncarnate

Posted 2015-10-13T10:06:35.697

Reputation: 916