독특한 쌍둥이 찾기


28

음이 아닌 정수 AB의 두 개의 배열 / 목록 / 벡터가 제공 됩니다. 당신의 작업은 출력에 정수 가장 높은 N 모두에서 나타납니다 와 B , 그리고도 모두 고유 와 B .


테스트 사례 :

A, B-> 출력

[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

답변:


7

젤리 , 7 바이트

fċ@ÐṂ;Ṁ

온라인으로 사용해보십시오!

작동 원리

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.

7

Bash + coreutils, 49 바이트

U()(sort -rn|uniq -u$1)
(U<<<$1;U<<<$2)|U D|sed q

1 바이트를 골라 낸 @seshoumara에게 감사합니다!

온라인으로 사용해보십시오!

작동 원리

uniq 는 명령 행 플래그에 따라 정렬 된 입력을 수행하고 하나 이상의 조치를 수행합니다.

U<<<$1그리고 첫 번째와 두 번째 명령 행 인수를 입력으로 U<<<$2하여 함수 U를 호출하십시오 . 각 항목에 대해 uniq의sort -rn|uniq -u 경우 입력을 숫자 ( -n) 및 내림차순 ( )으로 정렬하여 실행되며, 고유 한 행만 인쇄됩니다 (-r-u ) .

두 출력 (각 어레이의 고유 한 요소)의 출력은 연결되어 U D, 즉 파이프됩니다
sort -rn|uniq -uD. 이번에는 uniq 이 중복 행 ( -D) 만 인쇄 하고 각 행의 첫 번째 만 인쇄 합니다.

매뉴얼 페이지에 모든 반복이 인쇄된다고 표시되어 있지만 추가 된 -u원인 -D은 처음 발생한 중복 행만 인쇄합니다. 이 동작은 일반적으로로 수행됩니다 uniq -d.

마지막으로 sed q즉시 종료하여 입력 (두 어레이의 고유 한 요소)을 첫 번째 줄로 줄입니다. 출력은 내림차순으로 정렬되었으므로 최대 값입니다.


6

Pyth, 12 9 바이트

시도 해봐

eS@Fm.m/d

Mr. Xcoder 덕분에 3 바이트를 절약했습니다.

설명

eS@Fm.m/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.

좋은! 내 솔루션도 12 바이트 였습니다.
Mr. Xcoder

내 솔루션을 약간 9 바이트 내리고 (을 사용하여 eS@Fm.m/d) 두 목록의 목록으로 입력합니다.
Mr. Xcoder

@ Mr.Xcoder 자체 답변이 될만큼 충분히 다른 것 같습니다.

나는 도전의 OP이기 때문에 그것을 게시하는 것을 꺼려합니다. 당신은 그것을 사용하고 신용을 줄 수 있으며, 현재의 접근법을 대안으로 언급하고 있습니다 (물론 원한다면)
씨 Xcoder을



5

껍질 , 7 바이트

→►≠OfEΠ

입력을 두 목록의 목록으로 취하고, 임의의 수의 목록에서도 작동합니다 (가능한 경우 각 목록에서 정확히 한 번 발생하는 가장 높은 수를 반환 함). 온라인으로 사용해보십시오!

설명

이것은 새로운 "maximum by"기능을 사용하는 최초의 Husk 답변 입니다.

→►≠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

4

배쉬 + coreutils, 60 바이트

f()(sort -rn<<<"$1"|uniq -u);grep -m1 -wf<(f "$1") <(f "$2")

온라인으로 사용해보십시오

배쉬, 89 바이트

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


1
사용 sort -rnsed q말 대신 tail -1면도 한 바이트. grep -wfbtw 와 함께 잘 찾으십시오 . +1
seshoumara

@seshoumara, 팁 주셔서 감사합니다. 실제로 -m1 grep 옵션으로 3 바이트를 면도 할 수 있습니다.
Nahuel Fouilleul


3

J, 23 바이트

>./@([-.-.)&(-.-.@~:#])

(-.-.@~:#]) 반복 된 요소를 목록에서 제거

& 두 인수 모두 에이 작업을 수행

([-.-.) 우리는 A가 B를 교차하기를 원합니다. 이것은 같은 표현입니다 : "A 빼기 (A 빼기 B)"

>./ 최대를 가지고

온라인으로 사용해보십시오!


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

@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.
Jonah

2

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.


2

Javascript (ES6), 102 86 75 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.
Martin Ender

@MartinEnder Thanks! Edited the answer to reflect the details I missed!
Nate

1
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.
Justin Mariner

1
It seems that using (g=x=>x.filter(y=>y==e).length==1) is shorter.
tsh

1
I think this one is also passing all edge cases (71 bytes).
Arnauld

2

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.
Laikoni

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.
Laikoni

1
In-lining ! with and saves two more bytes: Try it online!
Laikoni

2

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.


2

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 */
}

2

F# (.NET Core), 117 115 114 111 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!



2

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

2

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.


1

MATL, 13 bytes

,iSY'1=)]X&X>

Try it online! Or Verify all test cases.

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

1

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.
Progrock

@Progrock That´s no valid input method.
Titus

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.)
Progrock

1

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

1

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.


1

JavaScript ES5, 122 121 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


2
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).
Mr. Xcoder

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,?
Piyin

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]}.
Mr. Xcoder

1
Yeah sure a string input would be fine
Mr. Xcoder

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
Piyin


1

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!


1

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

1

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!


1

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.


1
Nice idea! I really like it
aloisdg says Reinstate Monica



0

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.


당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.