配列の統一


24

前書き

同じ長さの2つの配列、たとえばA = [0,1,0,2]とを考えますB = [-1,1,2,2]。それらのコンテンツがアイテムごとに何らかの意味で同等であることを知っていると仮定します:

  • 0に相当し-1
  • 1に相当し1
  • 0と同等2であり、
  • 2はと同等2です。

等価性は推移的です:-1および0は等価であり0、および2は等価であるため-1、および2は等価です。and の統合A、(または)のB各項目がそれに相当する最大数に置き換えられた配列です。この場合、統合はになります。AB[2,1,2,2]

タスク

等しい長さの2つの空でない整数配列を取り、それらの統一を出力するプログラムまたは関数を作成します。戻る代わりに、入力の1つを変更することもできます。最も低いバイトカウントが優先されます。

テストケース

[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
なぜあなたはその操作を統一と呼んだのかよくわかりません。
16

4
@Fatalize 型の統一に触発されました。
ズガルブ

回答:


6

JavaScript(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うん。もっと良い方法があるかもしれません。少し興味深い事実:最初の2つも同様にa.map置き換えることができますb.map
アーナウルド

状況に合わせて新しいテストケースを追加しました。
ズガルブ

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

Python、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])

最初のリストの各値を2番目のリストの対応する要素で置き換えると、両方のリストが同時に更新されます。置換はmap、辞書のgetmethodで行われます。次に、リストを交換し、それらが等しくなるまで繰り返します。


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);
}



0

Java、273 263バイト

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

Python、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値の左端の要素を選択し、その値が等価で、0かつを0持っていると仮定02ます。0すでに訪れているので、に行き2ます。2の等価性は次のとおり0です。したがって、の左端の要素を選択するための最良の結果a2です。これがツリーです:

   0   
 /   \
0     2
       \
        0

そして、あなたはそこで最大の値を取得したいので、結果はになり2ます。


PPCGへようこそ!では、コード・ゴルフ、あなたはあなたのプログラムの中で最短:バイトを取得することを目指しています。これは、関数名と変数名を短縮し、プログラム内の不要な空白を削除することを意味します。
クリチキシリトス

また、ハードコーディングする代わりに、ユーザー入力として2つの配列を使用する必要があります。
ズガルブ

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];}

2つの配列を取る匿名関数。

これは、チャレンジの出力で指定されているように、「所定の配列の1つを変更する」という私の見解です。これは、2つの配列のそれぞれをループし、現在の配列が保存されている配列よりも大きい場合に等価性を記録し、最初の配列をループして、すべての値を最大の等価物で置き換えます。最初の配列は参照によって取得されるため(したがって&$a)、渡される配列は「その場で」変更されます。


0

Java、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[]引数として2つのを取り、を返す無名関数int[]

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.