Find the unique twins

You will be given two Arrays / Lists / Vectors of non-negative integers A and B. Your task is to output the highest integer N that appears in both A and B, and is also unique in both A and B.

Test Cases:

A, B -> Output

[6], [1, 6] -> 6
[1, 2, 3, 4], [4, 5, 6, 7] -> 4
[0, 73, 38, 29], [38, 29, 73, 0] -> 73
[1, 3, 4, 6, 6, 9], [8, 7, 6, 3, 4, 3] -> 4
[2, 2, 2, 6, 3, 5, 8, 2], [8, 7, 5, 8] -> 5
[12, 19, 18, 289, 19, 17], [12, 19, 18, 17, 17, 289] -> 289
[17, 29, 39, 29, 29, 39, 18], [19, 19, 18, 20, 17, 18] -> 17
[17, 29, 39, 29, 29, 39, 18, 18], [19, 19, 18, 20, 17, 18] -> 17


Python 3, 6156 54 bytes

Saved 7 bytes thanks to @Mr.Xcoder, @pizzapants184 and @ovs

lambda a,b:max(f*(a.count(f)==b.count(f)<2)for f in a)


Try it online!

• Beat me by a minute! Nov 2, 2017 at 18:11
• 57 bytes Nov 2, 2017 at 18:14
• 56 bytes Nov 2, 2017 at 18:15
• 54 bytes
– ovs
Nov 2, 2017 at 21:59

Jelly, 7 bytes

fċ@ÐṂ;Ṁ


Try it online!

How it works

fċ@ÐṂ;Ṁ  Main link. Left argument: A. Right argument: B

f        Filter; keep those elements of A that appear in B.
ÐṂ    Yield all elements of the result for which the link to left yields a
minimal value (2).
ċ@        Count the occurrences of the element...
;     in the concatenation of A and B.
Ṁ  Take the maximum.


Bash + coreutils, 49 bytes

U()(sort -rn|uniq -u$1) (U<<<$1;U<<<$2)|U D|sed q  Thanks to @seshoumara for golfing off 1 byte! Try it online! How it works uniq takes sorted input and performs one or several actions, depending on the command-line flags. U<<<$1 and U<<<$2 call the function U with the first and second command-line argument as input. For each one, sort -rn|uniq -u is executed, sorting the input numerically (-n) and in descending order (-r) for uniq, which will print only unique lines (-u). The output of both (unique elements of each array) is concatenated and piped to U D, i.e., sort -rn|uniq -uD. This time, uniq will only print duplicate lines (-D), and only the first repetition of each. While the man page says it will print all repetitions, the added -u causes -D to print only the first occurrence of duplicated lines. This behavior is normally achieved with uniq -d. Finally, sed q quits immediately, reducing its input (unique elements of both arrays) to its first line. Since the output was sorted in descending order, this is the maximum. Pyth, 12 9 bytes Try it [email protected]/d  Saved 3 bytes thanks to Mr. Xcoder. Explanation [email protected]/d m /d Count the occurrences of each element. .m Take only those that appear the minimum number of times. @F Apply the above to A and B and take the intersection. eS Take the largest.  • Nice! My solution was also 12 bytes. Nov 2, 2017 at 18:24 • Golfing my solution down a bit, 9 bytes (using [email protected]/d) and taking input as a list of two lists. Nov 2, 2017 at 18:29 • @Mr.Xcoder That seems different enough to be its own answer. – user48543 Nov 2, 2017 at 18:53 • Since I am the OP of the challenge, I am reluctant about posting it. You can just use it and give credit, mentioning your current approach as an alternative (if want to of course) Nov 2, 2017 at 18:54 05AB1E, 9 8 bytes -1 byte thanks to Erik the Outgolfer εÐ¢Ï}Ãà  Try it online! ε } # For each input Ð¢Ï # Get the unique elements Ã # Keep only the elements that appear in both lists à # Keep the greatest element # Implicit print  Husk, 7 bytes →►≠OfEΠ  Takes input as a list of two lists, works for any number of lists as well (returning the highest number that occurs exactly once in each, if possible). Try it online! Explanation This is the first Husk answer to (ab)use the new "maximum by" function ►. →►≠OfEΠ Implicit input, say [[3,2,1,3],[1,2,3,4]] Π Cartesian product: [[3,1],[2,1],[3,2],[2,2],[1,1],[3,3],[1,2],[3,1],[3,4],[2,3],[1,3],[3,2],[2,4],[3,3],[1,4],[3,4]] fE Keep those that have equal elements: [[2,2],[1,1],[3,3],[3,3]] O Sort: [[1,1],[2,2],[3,3],[3,3]] ►≠ Find rightmost element that maximizes number of other elements that are not equal to it: [2,2] → Take last element: 2  Bash + coreutils, 60 bytes f()(sort -rn<<<"$1"|uniq -u);grep -m1 -wf<(f "$1") <(f "$2")


Try It Online

c()(for e;{((e^$1||r++,2^r));});for x in$1 $2;{((x<r))||c$x $1||c$x $2||r=$x;};echo $r  TIO • Use sort -rn with sed q at the end instead of tail -1 to shave 1 byte. Great find with grep -wf btw. +1 Nov 4, 2017 at 6:48 • @seshoumara, thank you for the tip, in fact i could shave 3 bytes with -m1 grep option. Nov 4, 2017 at 19:57 Jelly, 11 bytes ċ@Ị¥Ðf€f/Ṁ  Try it online! • Clever usage of ! Nov 2, 2017 at 18:13 J, 23 bytes >./@([-.-.)&(-.-.@~:#])  (-.-.@~:#]) removes from a list any repeated elements & do this to both args ([-.-.) We want A intersect B. This is the equivalent phrase: "A minus (A minus B)" >./ Take the max Try it online! • Equivalently, you can replace the intersection part with e.~#]. Golfing this has proven to be tough... I tried using /.-key to no success (((1=#)/.~#~.) for the first part which is 2 bytes longer by my count) – cole Nov 3, 2017 at 16:37 • @cole, yeah, I tried a key approach as well, and also one with self-classify. I wasn't able to beat my submission above with any other approach though. Nov 3, 2017 at 16:38 PowerShell, 94 bytes param($a,$b)filter f($x){$x|group|?{$_.count-eq1}}
(f($a|sort|?{$_-in((f $b).Name)}))[-1].Name  Try it online! Takes input $a and $b as arrays. Constructs a filter that groups the input array elements together and pulls out only those with a count -equal to 1 (i.e., only those that are unique in the input array). The next line then constructs the algorithm. First we sort $a, then pull out those that are -in the unique items of $b. Those are then themselves unique-ified, the largest [-1] is chosen, and we take the .Name thereof. That's left on the pipeline and output is implicit. Java 8, 133 bytes a->b->{long r;for(java.util.Collections c=null;;a.remove(r))if(b.contains(r=c.max(a))&c.frequency(a,r)*c.frequency(b,r)==1)return r;}  Explanation: Try it here. a->b->{ // Method with two ArrayList<Long> parameters and long return-type long r; // Result-long for(java.util.Collections c=null; // Create a java.util.Collections to save bytes ; // Loop indefinitely a.remove(r)) // After every iteration, remove the current item if(b.contains(r=c.max(a)) // If the maximum value in a is present in b, &c.frequency(a,r)*c.frequency(b,r)==1) // and this maximum value is unique in both Lists: return r; // Return this value // End of loop (implicit / single-line body) } // End of method  Javascript (ES6), 1028675 71 bytes a=>b=>Math.max(...a.map(e=>(g=x=>x.map(y=>y-e||x--,x=1)|!x)(a)*g(b)*e))  Thanks @justinMariner for getting from 102 to 86 Thanks @tsh for getting from 86 to 75 Thanks @Arnauld for getting from 75 to 71 Try it online! • Welcome to PPCG! As far as I can tell this doesn't make sure that e shows up only once in a and b. Nov 2, 2017 at 22:21 • @MartinEnder Thanks! Edited the answer to reflect the details I missed! – Nate Nov 2, 2017 at 22:48 • I never thought of using lastIndexOf like that, that's pretty clever. You can get this down to 86 bytes: Try it online!. Check out the JS tips for more. Nov 3, 2017 at 0:03 • It seems that using (g=x=>x.filter(y=>y==e).length==1) is shorter. – tsh Nov 3, 2017 at 1:34 • I think this one is also passing all edge cases (71 bytes). Nov 3, 2017 at 14:46 Haskell, 57 53 bytes x?y|let v!x=filter(==v)x==[v]=maximum[a|a<-x,a!x,a!y]  Try it online! UPD: Thanks @Laikoni • Welcome to PPCG and Haskell golfing in particular! This is a nice first answer! Two small things: You can also declare f as infix operator and write [1|...]==[1] instead of sum[1|...]==1 to save some bytes. Nov 3, 2017 at 16:03 • In case you haven't seen them already, here are some links which might be interesting: Our collection of golfing tips in Haskell, the guide to golfing rules in Haskell and Of Monads and Men, our Haskell chat room. Nov 3, 2017 at 16:07 • In-lining ! with and saves two more bytes: Try it online! Nov 3, 2017 at 21:50 Wolfram Language (Mathematica), 40 bytes Max@Cases[Tally@#⋂Tally@#2,{x_,1}:>x]&  Try it online! How it works Tally@# gives a list of the unique elements of the first input, together with their counts: e.g., Tally[{2,2,2,6,3,5,8,2}] yields {{2,4},{6,1},{3,1},{5,1},{8,1}}. Tally@#2 does the same for the second list, and ⋂ finds pairs present in both. Then we pick out (with Cases) pairs ending in 1, taking the first element of each result, which gives us a list of all the unique twins. Finally, Max returns the largest unique twin. SQLite, 118 bytes SELECT MAX(x)FROM(SELECT X FROM A GROUP BY X HAVING COUNT(X)=1 INTERSECT SELECT X FROM B GROUP BY X HAVING COUNT(X)=1)  Try it online! First time in SQL, any help is welcome! Röda, 48 bytes {m={|n|sort|count|[_]if[_=n]};[_()|m 1]|m 2|max}  Try it online! Inspired by jq170727's jq answer. Explanation: { /* Anonymous function, takes input from the stream */ m={|n| /* Local function m with parameter n: */ sort|count| /* Count unique values in the stream */ [_]if[_=n] /* For each value, push it to the stream if its count is n */ }; [ /* For each list in the stream: */ _()| /* Flat it (push its values to the stream) */ m 1 /* Push values that appear only once to the stream */ ]| m 2| /* Push values that appear twice to the stream */ max /* Find the max value in the stream */ }  F# (.NET Core), 117115114111 108 bytes 115 114 bytes Another solution with countBy this time: let u x=x|>Seq.countBy id|>Seq.filter(fun a->snd a=1)|>Seq.map fst|>set let f x y=Set.intersect(u x)(u y)|>Seq.max  Try it online! 117 111 bytes let u x=x|>Seq.filter(fun a->x|>Seq.filter((=)a)|>Seq.length=1)|>set let f x y=Set.intersect(u x)(u y)|>Seq.max  Try it online! 100% F#! Any help is welcome! 6 byte won thanks to prefix notation! 108 bytes let f a b=Set.intersect(set a)(set b)|>Seq.filter(fun x->a@b|>Seq.filter(fun y->y=x)|>Seq.length<3)|>Seq.max  @ is the concat function! Thank you @Ayb4btu for this algorithm. Try it online! C# (.NET Core), 85 84 bytes x=>y=>x.Where(a=>x.Count(b=>b==a)<2).Intersect(y.Where(a=>y.Count(b=>b==a)<2)).Max()  Try it online! Naive solution with LINQ (using System;using System.Linq; +31chars so 116 bytes with header) 84! I forgot currying! Pip, 17 16 bytes MX{_Na=_Nb=1FIa}  This is a function that takes two lists as arguments. Try it online! Explanation  { } Define function, args are a & b: FIa Filter elements of a on this function: _Na Count of element in a =_Nb equals count of element in b =1 equals 1 This gives a function that returns a list of unique twins MX Modify it to take the max and return that instead  APL (Dyalog), 18 chars = 23 bytes* A full program body. Prompts for list of lists from STDIN. Works with any number of lists. Outputs to STDOUT. ⌈/∊∩/{⊂⍺⍴⍨1=≢⍵}⌸¨⎕  Try it online! ⎕ prompt for evaluated input from STDIN {}⌸¨ for each list, call the following function for each unique element in that list, using the unique element as left argument (⍺) and the list of indices of its occurrence as right argument (⍵): ≢⍵ the tally of indices (i.e. the number of occurrences) 1= equal to 1 ⍺⍴⍨ use that to reshape the specific element (i.e. gives empty list if non-unique) Now we have two lists of unique elements for each input list (although each element is a list, and there are empty lists as residue from the non-unique elements). ∩/ intersection (reduction) ∊ϵnlist (flatten) ⌈/ max (reduction) * in Classic, counting ⌸ as ⎕U2338. MATL, 13 bytes ,iSY'1=)]X&X>  Explanation , % Do twice i % Take input: array S % Sort array Y' % Run-length encode: pushes array of values and array of run lengths 1= % Compare each run length with 1 ) % Use as logical index. This keeps only values that have appeared once ] % End X& % Intersection of the two arrays X> % Maximum of array. Implicitly display  PHP, 98 bytes <?foreach(($c=array_count_values)($_GET[a])as$a=>$n)$n-1||$c($_GET[b])[$a]-1||$a<$r||$r=$a;echo$r;


Provide arrays as GET parameters a and b.

• Think you could swap those GET params for constants. Nov 6, 2017 at 8:37
• @Progrock That´s no valid input method. Nov 6, 2017 at 12:39
• The question phrases that A and B are given as arrays. And says any reasonable input and output method.... not that I can follow that link easily. Really like your recipe. (Chokes in obsolete Php 5.6 though.) Nov 6, 2017 at 16:53

R, 73 bytes

function(A,B)max(setdiff(intersect(A,B),c(A[(d=duplicated)(A)],B[d(B)])))


Try it online!

Computes A intersect B, then the maximum of the difference between that and the duplicated elements of A and B.

JavaScript ES5, 122121 114 bytes

function f(a,b){for(i=a.sort().length;--i+1;)if(a[i]!=a[i+1]&&a[i]!=a[i-1]&&!(b.split(a[i]).length-2))return a[i]}


I'm new here, so I don't really know if I can remove the function definition and just put its contents (which would save me 17 bytes)

Here's the working example: 122 121 114

122 to 121 bytes: Wrapping initialization in a for

121 to 114 bytes: b has to be a string

• Welcome to PPCG! You cannot remove the function definition, but you might be able to use a lambda function instead (I don't know JS so I cannot help you with that). Nov 3, 2017 at 16:18
• Thanks for clearing that out. I don't think lambda functions can save any characters, but I'll try. Also, since you say "Any reasonable Input and Output method / format is allowed", could I accept an string as b and save b=''+b,? Nov 3, 2017 at 16:24
• I did manage to get to 115 bytes although I don't know JavaScript: f=(a,b)=>{for(b=''+b,i=a.sort().length;--i+1;)if(a[i]!=a[i+1]&&a[i]!=a[i-1]&&!(b.split(a[i]).length-2))return a[i]}. Nov 3, 2017 at 16:24
• Yeah sure a string input would be fine Nov 3, 2017 at 16:24
• But that JavaScript you came up with would be ES5, not ES6. An ES6 answer is already posted, which is why I posted the ES5. And thanks for answering the second question hehe Nov 3, 2017 at 16:25

Jq 1.5, 76 bytes

def m(n):[.[indices(.[])|select(length==n)[]]]|unique[];[map(m(1))|m(2)]|max


Expanded

def m(n): # function to emit elements of multiplicity n
[
.[                         # select elements with
indices(.[])          # number of indices in the array
| select(length==n)[]   # equal to specified multiplicity
]
] | unique[]                 # emit deduped values
;

[
map(m(1))   # collect multiplicity 1 elements from each array
| m(2)        # collect multiplicity 2 elements
] | max         # choose largest of these elements


Try it online!

Here is another solution which is the same length:

def u:[keys[]as$k|[.[$k]]-(.[:$k]+.[$k+1:])]|add;map(u)|.[0]-(.[0]-.[1])|max


Expanded

def u: # compute unique elements of input array
[
keys[] as $k # for each index k | [.[$k]] - (.[:$k]+.[$k+1:])    # subtract other elements from [ .[k] ]
]                                  # resulting in [] if .[k] is a duplicate
| add                              # collect remaining [ .[k] ] arrays
;
map(u)                             # discard duplicates from each input array
| .[0]-(.[0]-.[1])                   # find common elements using set difference
| max                                # kepp largest element


Try it online!

APL, 47 bytes

{1↑R[⍒R←((1={+/⍵=A}¨A)/A←⍺)∩(1={+/⍵=B}¨B)/B←⍵]}


Declares an anonymous function that takes two vectors, eliminates duplicate elements, then finds the biggest element in the intersection of the results.

A←⍺ and B←⍵ store the arguments passed to the function in A and B.

a=b returns a vector with 1 in each index in which a is equal to b. If a is a scalar (i.e. single quantity and not a vector) this returns a vector with 1 wherever the element in b is a and 0 when it is not. For example:

Input: 1=1 2 3
Output: 1 0 0


{+/⍵=A}: nested anonymous function; find the occurrences of the argument in vector A and add them up i.e. find the number of occurrences of the argument in A

1={+/⍵=A}¨A: apply the nested anonymous function to each element in A and find the ones that equal 1 i.e. unique elements

((1={+/⍵=A}¨A)/A←⍺): having found the location of the unique elements, select just these elements in the original vector (/ selects from the right argument elements whose locations correspond to 1 in the left argument)

R←((1={+/⍵=A}¨A)/A←⍺)∩(1={+/⍵=B}¨B)/B←⍵: repeat the process for the second argument; now that we have just the unique elements, find the intersection i.e. common elements and store this in vector R

R[⍒R]: access the elements of R in decreasing order

1↑R[⍒R]: take the first element of R when it's sorted in decreasing order

Test case:

Input: 17 29 39 29 29 39 18 18 {1↑R[⍒R←((1={+/⍵=A}¨A)/A←⍺)∩(1={+/⍵=B}¨B)/B←⍵]} 19 19 18 20 17 18
Output: 17


J, 30 bytes

[:>./@,[*([*+/"1(1=*/)+/)@(=/)


How it works:

I start with testing where the two list overlap by =/ (inserts equality test between all the members of the lists:

   a =. 1 3 4 6 6 9
b =. 8 7 6 3 4 3
]c=. a =/ b
0 0 0 0 0 0
0 0 0 1 0 1
0 0 0 0 1 0
0 0 1 0 0 0
0 0 1 0 0 0
0 0 0 0 0 0


More than one 1 in the same column means that the number is not unique for the left argument (6 in this case); in the row - for the right argument (3)

Then I sum up all rows and all columns to find where are the duplicates:

   +/ c
0 0 2 1 1 1
+/"1 c
0 2 1 1 1 0


I find the cartesian product of the above lists and set the members greater than 1 to 0.

    m =. (+/"1 c) (1=*/) +/c
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 1 1
0 0 0 1 1 1
0 0 0 1 1 1
0 0 0 0 0 0


I mask the equality matrix c with m to find the unique elements that are common to both lists and multiply the left argument by this.

]l =. a * m * c
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 4 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0


Then I flatten the list and find the max element:

 >./,l
4


Try it online!

C# (.NET Core), 66+31=97 65+31=96 bytes

a=>b=>a.Intersect(b).Where(x=>a.Concat(b).Count(y=>y==x)<3).Max()


Try it online!

+31 bytes for using System;using System.Linq;

I took inspiration from @aloisdg's answer. However, instead of searching for unique values in both arrays, I inverted the order of operations so that intersect is first, and then find the max value of the items that occur twice when the arrays are concatenated and are in their intersect. I can use <3 as Count will be at least 2 for any value, as it will be in both arrays.

Acknowledgements

-1 byte thanks to @aloisdg and his suggestion to use Func currying.

Octave, 57 56 bytes

@(x)max(intersect(cellfun(@(x){x(sum(x'==x)==1)},x){:}))


Anonymous function that takes as input a cell array of two numerical arrays.

Try it online!

Explanation

For each (cellfun(@(x)...)) of the two input arrays, this creates a matrix of pairwise equality comparisons between its entries (x.'==x); keeps (x(...)) only the entries for which the column sum is 1 (sum(...)==1); and packs the result in a cell ({...}). The intersection (intersect) of the two results ({:}) is computed, and the maximum (max(...)) is taken.

Wolfram Language (Mathematica), 49 bytes

Last@Select[a=Join@##;Sort[#⋂#2],a~Count~#<3&]&


Try it online!