배열 통일


24

소개

같은 길이의 두 배열 (예 : A = [0,1,0,2]and)을 고려하십시오 B = [-1,1,2,2]. 각 항목의 내용이 항목별로 의미가 있다고 가정합니다.

  • 0동등 -1,
  • 1동등 1,
  • 0에 해당 2하며
  • 2와 같습니다 2.

등가는 타동사이다 : -10동일하고, 0그리고 것은 2그래서, 동일 -12도 동일합니다. 및 의 통합 은 (또는 ) 의 각 항목이 이에 해당하는 가장 큰 숫자로 대체 된 배열 입니다. 이 경우 통일은입니다 .ABAB[2,1,2,2]

작업

길이가 같은 두 개의 비어 있지 않은 정수 배열을 사용하여 통합을 출력하는 프로그램 또는 함수를 작성하십시오. 반환하는 대신 입력 중 하나를 수정할 수도 있습니다. 가장 낮은 바이트 수가 이깁니다.

테스트 사례

[0] [0] -> [0]
[1] [2] -> [2]
[0,-1] [-1,-1] -> [0,0]
[0,1,0] [2,1,0] -> [2,1,2]
[1,2,3] [0,0,1] -> [3,3,3]
[0,1,0,2] [-1,1,2,2] -> [2,1,2,2]
[1,0,1,-4] [-3,-1,-2,2] -> [1,0,1,2]
[1,2,3,-2] [1,0,-3,-2] -> [1,2,3,-2]
[-3,-2,-1,0,1] [-1,-1,-1,-1,-1] -> [1,1,1,1,1]
[-3,-2,-1,0,1] [2,-1,0,1,-3] -> [2,2,2,2,2]
[-3,5,5,3,1] [4,2,3,1,2] -> [4,5,5,5,5]
[4,0,2,-5,0] [0,4,-5,3,5] -> [5,5,3,3,5]
[-2,4,-2,3,2,4,1,1] [-2,4,1,2,2,3,1,-2] -> [1,4,1,4,4,4,1,1]
[-10,-20,-11,12,-18,14,-8,-1,-14,15,-17,18,18,-6,3,1,15,-15,-19,-19] [-13,6,-4,3,19,1,-10,-15,-15,11,6,9,-11,18,6,6,-5,-15,7,-11] -> [-8,14,18,14,19,14,-8,-1,-1,15,14,18,18,18,14,14,15,-1,18,18]
[20,15,2,4,-10,-4,-19,15,-5,2,13,-3,-18,-5,-6,0,3,-6,3,-17] [-18,7,6,19,-8,-4,-16,-1,13,-18,8,8,-16,17,-9,14,-2,-12,7,6] -> [20,15,20,19,-8,-4,20,15,17,20,17,17,20,17,-6,14,15,-6,15,20]

3
왜 당신이 그 작전 통일을 불렀는지 잘 모르겠습니다.
페이탈 라이즈

4
@Fatalize 타입 통일에서 영감을 얻었습니다 .
Zgarb

답변:


6

자바 스크립트 (ES6) 100 90 110 102 96 바이트

a=>b=>a.map(v=>t[v],a.map((_,k)=>a.map((x,i)=>t[x]=t[y=b[i]]=Math.max(k?t[x]:x,k?t[y]:y)),t={}))

내 초기 솔루션은 90 바이트였습니다.

a=>b=>a.map(v=>t[v],a.map(_=>a.map((x,i)=>t[x]=t[y=b[i]]=Math.max(t[x]||x,t[y]||y)),t={}))

제공된 모든 테스트 사례를 통과했지만 다음과 같은 경우에는 실패합니다.

A = [0, -1], B = [-1, -1]

테스트 사례


즉 많은입니다 a.map...
ETHproductions

@ETHproductions 예. 더 좋은 방법이있을 수 있습니다. 약간 흥미로운 사실 ​​: 처음 두 가지도 마찬가지로 a.map대체 될 수 있습니다 b.map.
Arnauld

상황에 맞는 새로운 테스트 사례를 추가했습니다.
Zgarb

5

CJam , 27 바이트

l~_])\z_,*f{{_2$&,*|}/:e>}p

온라인으로 사용해보십시오! 테스트 스위트.

설명

l~       e# Read and evaluate input, dumping arrays A and B on the stack.
_        e# Copy B.
])\      e# Wrap in array, pull off B, swap. Gives B [A B] on the stack.
z        e# Transpose the [A B] matrix to get a list of all equivalent pairs.
_,*      e# Repeat this list by the number of pairs. This is to ensure that the
         e# following procedure is applied often enough to allow transitive
         e# equivalences to propagate.
f{       e# Map this block over B, passing in the list of pairs each time...
  {      e#   For each pair...
    _2$  e#     Copy both the pair and the current value/list.
    &,   e#     Get the length of their intersection. If this is non-zero,
         e#     the current pair belongs to the current equivalence class.
    *    e#     Repeat the pair that many times.
    |    e#     Set union between the current value/list and the repeated pair.
         e#     This adds the pair to the current list iff that list already
         e#     contains one value from the pair.
  }/
  :e>    e#   Get the maximum value of this equivalence class.
}
p        e# Pretty print.

4

파이썬 2, 91 바이트

f=lambda a,b:[a<x>b.update(b&set(x)and x)and b or max(f(zip(a,b)*len(a),{x})[0])for x in a]

4

파이썬, 86 바이트

f=lambda a,b:a*(a==b)or f(*[map({x:y for x,y in zip(a,b)if x<y}.get,x,x)for x in b,a])

첫 번째 목록의 각 값을 더 큰 경우 두 번째 목록의 해당 요소로 대체하여 두 목록을 동시에 업데이트합니다. 대체는 map사전의 get방법으로 수행 됩니다. 그런 다음 목록을 바꾸고 같을 때까지 반복합니다.


2

Pyth, 13 바이트

eMumS{s@#dGGC

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

설명:

각 쌍으로 시작하십시오. 겹치는 목록으로 각 쌍 (목록)을 반복적으로 확장하고 요소를 중복 제거하고 정렬합니다. 이 프로세스가 수렴되면 중지하십시오. 각 목록의 최대 값을 인쇄하십시오.


2

PHP, 266 241 213 200 바이트

해결책:

function u($x,$y){foreach($x as$i=>$j){$k[$y[$i]][]=$j;$k[$j][]=$y[$i];}$h=function($c,&$w)use($k,&$h){$w[]=$c;foreach($k[$c]as$u)!in_array($u,$w)&&$h($u,$w);return max($w);};return array_map($h,$x);}

사용법 : u([1,2,3], [0,0,1]);원하는 배열을 반환합니다.

골프가 아닌 :

function unify($x, $y)
{
    foreach($x as $i=>$j) {
        $k[$y[$i]][] = $j;
        $k[$j][] = $y[$i];
    }

    $h = function ($c, &$w=[]) use ($k, &$h) {
        $w[] = $c;
        foreach($k[$c] as $u)
            !in_array($u, $w) && $h($u, $w);
        return max($w);
    };

    return array_map($h, $x);
}


1

매스 매 티카, 56 바이트

#/.($|##->Max@##&@@@ConnectedComponents@Thread[#<->#2])&

0

자바, 273263 바이트

interface Z{int z(int x);default Z g(int m,int n){return x->{for(int t;x!=(t=x==m?z(n):z(x));)x=t;return x;};}static void f(int[]a,int[]b){Z y=x->x;int i=0,v;for(int u:a){u=y.z(u);v=y.z(b[i++]);if(u<v)y=y.g(u,v);if(v<u)y=y.g(v,u);}i=0;for(int u:a)a[i++]=y.z(u);}}

이 방법 f(int[]a,int[]b)은 문제를 해결합니다.

interface Z{

  //should return an "equivalent" integer
  int z(int x);

  //return a Z lambda where the 1st arg is "equivalent" to the 2nd arg
  default Z g(int m,int n){
    return x->{
      for(int t;x!=(t=x==m?z(n):z(x));) //always find the last equivalent number for x
        x=t;
      return x;
    };
  }

  //solve the challenge
  static void f(int[]a,int[]b){
    Z y=x->x; //start off with all numbers only equivalent only to themselves
    int i=0,v;
    for(int u:a){
      u=y.z(u); //get a's element's equivalent number
      v=y.z(b[i++]); //get b's element's equivalent number
      if(u<v)y=y.g(u,v); //if a's was smaller than b's, make a's equivalent to b's
      if(v<u)y=y.g(v,u); //if b's was smaller than a's, make b's equivalent to a's
    }
    i=0;
    for(int u:a) //overwrite a with each element's equivalent value
      a[i++]=y.z(u);
  }

}

먼저 두 배열을 모두 통과하고 동등한 숫자를 추적하십시오. 그런 다음 첫 번째 배열의 모든 요소를 ​​수정하여 동등한 숫자를 저장하십시오.


0

파이썬, 522 바이트

a = [-2,4,-2,3,2,4,1,1]
b = [-2,4,1,2,2,3,1,-2]
m = {}
visited = {}
for i in range(len(a)):
    if a[i] in m:
        if b[i] not in m[a[i]]:
            m[a[i]].append(b[i])
    else:
        l = []
        l.append(b[i])
        m[a[i]] = l
    if b[i] in m:
        if a[i] not in m[b[i]]:
            m[b[i]].append(a[i])
    else:
        l = []
        l.append(a[i])
        m[b[i]] = l

def dfs(v, maximum):
    if v > maximum:
        maximum = v
    visited[v] = True
    for n in m[v]:
        if not visited[n]:
            d = dfs(n, maximum)
            if d > v:
                maximum = d
    return maximum

result = []
for k in range(len(a)):
    for q in m:
        visited[q] = False
    result.append(max(dfs(a[k], a[k]), dfs(b[k], b[k])))

print(result)

설명

두 배열에서 (각각의 고유 요소에 대응하는 값의 표를 확인 a하고 b,이 경우에). 예를 들어

a = [0,1,0] 
b = [2,1,0]

다음 테이블은 다음과 같습니다.

0:[0,2]
1:[1]
2:[0]

다음 그래서, 예를 들어, 내가 가장 왼쪽 요소 선택 가정, 깊이 우선 탐색을 적용 a값이 다음입니다 00균등 한을 가지고 02. 때문에 0이미 방문한 된 사이트로 이동 2. 2는 다음과 같습니다 0. 가장 왼쪽에있는 요소를 선택하는 가장 좋은 결과 a2입니다. 여기 나무가 있습니다 :

   0   
 /   \
0     2
       \
        0

그리고 거기에서 가장 큰 가치를 원하고 결과는 2입니다.


PPCG에 오신 것을 환영합니다! 에서 코드 골프 , 당신은 당신의 프로그램에서 최단 bytecount가 얻을 것을 목표로하고 있습니다. 이것은 함수와 변수 이름을 줄이고 프로그램에서 불필요한 공백을 제거하는 것을 의미합니다.
Kritixi Lithos

또한 두 배열을 하드 코딩하는 대신 사용자 입력으로 사용해야합니다.
Zgarb

0

PHP, 132 바이트

function(&$a,$b){for(;$i<count($a);$i++){$r=$a[$i];$s=$b[$i];$r<$c[$s]?:$c[$s]=$r;$s<$c[$r]?:$c[$r]=$s;}foreach($a as&$v)$v=$c[$v];}

두 개의 배열을 취하는 익명 함수.

이것은 도전 과제의 결과에 지정된대로 '어레이 중 하나를 수정하십시오'에 대한 나의 견해입니다. 이것은 두 배열 각각을 반복하고 현재 배열이 저장된 배열보다 큰 경우 등가를 기록한 다음 첫 번째 배열을 반복하여 모든 값을 가장 큰 값으로 바꿉니다. 첫 번째 배열은 참조로 사용되므로 &$a전달 된 배열은 '제자리에서'수정됩니다.


0

자바, 170 바이트

골프

(a,b)->{int[]d=a.clone();for(int i=0,y;i<d.length;i++){y=0;for(int j=0;j<a.length;j++)if(a[j]==d[i]||b[j]==d[i])y=Integer.max(y,Integer.max(a[j],b[j]));d[i]=y;}return d;}

언 골프

(a, b) -> {                                        // Two argument lambda
    int[] d = a.clone();                           // We clone our first array for modification
    for (int i = 0,y; i < d.length; i++) {         // Going through the elements of d...
        y = 0;                                     // We initialize our 'highest' equivalent
        for (int j = 0; j < a.length; j++) {       // Going through each of our arrays (a and b)...
            if (a[j] == d[i] || b[j] == d[i]) {    // If either of them is the number we're trying to match for equivalence...
                y = Integer.max(y, Integer.max(a[j], b[j])); // We see if the new number is bigger than the largest we've found.
            }
        }
        d[i] = y;                                  // We then assign the largest equivalent number for the current position in our output array.
    }
    return d; // And return!
}

두 개의 int[]s를 인수로 사용하여int[] .

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