ハウスドルフ距離の計算


21

前書き

ハウスドルフ距離は、距離空間の2つのサブセットの間の差を測定します。直観的には、距離空間は組み込みの距離関数を備えた単なるセットです。この課題では、通常の距離の自然数を使用しますd(a, b) := abs(a - b)。二つの非空有限集合間のハウスドルフ距離ABによって与えられます。

max(max(min(d(a, b) for b in B) for a in A),
    max(min(d(a, b) for a in A) for b in B))

Pythonのような表記法で。ハウスドルフ距離がの要素見つけることによって計算することができるAそのための最も近い要素までの距離がB最大との要素であるBの最も近い要素にする距離A最大であり、そして、これらの距離の最大値を取っています。ハウスドルフ距離が言い換えれば、d後のすべての要素は、A距離内にあるdいくつかの要素のB、およびその逆。

入力

入力は整数の単一リストです。それだけの要素が含まれ0,1,2,3、リストの指定されたインデックスは、どちらの要素であるかどうかを意味し、AでもB、のみA、のみB、または両方AB。たとえば、0から始まるインデックスを使用する場合、入力[0,1,1,0,2,3]A = {1,2,5}andを意味しB = {4,5}ます(メトリックは翻訳不変なので、違いはありません)。

出力

出力は、Aとの間のハウスドルフ距離Bです。上記の例では、です3。いずれかのセットが空の場合、距離は定義されていないため、を返し-1ます。

ルール

完全なプログラムまたは関数を作成できます。最小のバイトカウントが優先され、標準の抜け穴は許可されません。

テストケース

[] -> -1
[0] -> -1
[0,1,0] -> -1
[2,0,0,2] -> -1
[0,1,2,3] -> 1
[0,3,3,0,0,0,0,3] -> 0
[1,0,0,1,0,0,1,3,1] -> 7
[1,0,0,0,0,3,0,0,0,0,2] -> 5
[0,1,1,3,1,3,2,1,1,3,0,3] -> 2
[2,2,2,1,2,0,3,1,3,1,0,3] -> 3
[1,3,0,2,0,2,2,1,0,3,2,1,1,2,2] -> 2
[1,0,1,1,2,0,1,2,3,1,0,0,0,1,2,0] -> 4

あなたの方程式では、私はそれが長すぎると信じていmax(max(min(d(a, b) for b in B) for a in A))ます。これはd(a,b)、絶対値を返すため、両方のmax関数が毎回同じ数を返すためです。
ネイサンメリル

6
@NathanMerrillのすべての要素はのAいずれかに非常に近いかもしれませんがBB非常に遠い要素がある場合がありますA(たとえば、Aのサブセットである場合B)。その場合、短い式は正しくありません。
ズガルブ

回答:


7

CJam、53 52 46 38 37バイト

3,q~f{f&:L,{L=},}$~ff{-z}_z+::e<W+:e>

STDINの入力をCJamスタイルの配列として受け取ります。

[0 1 2 3]

すべてのテストケースをこの形式に変換し、それらでコードを実行するテストハーネス次に示します。結果は入力フィールドにありますが、コードでは使用されません(信頼していない場合は削除してください:))。

説明

まず、入力を解析して2つのセットAとBを取得します。

3,q~f{f&:L,{L=},}$~
3,                  "Push [0 1 2]. 1 is for A, 2 is for B, and 0 we can luckily ignore
                     as we'll see later.";
  q~                "Read and evaluate the input.";
    f{          }   "Map this block onto the [0 1 2] array, copying in the input for
                     each iteration.";
      f&:L          "Take the bitwise AND with each element of the input and store the
                     result in L.";
          ,{  },    "Get the length N, and filter the range [0 .. N-1] by evaluating
                     the block for each element.";
            L=      "Check if the bitwise AND at that index yielded something non-zero.
                     This gives an empty array for 0, A for 1 and B for 2.";
                 $  "Sort the three arrays. This has two important effects: a) it moves
                     the empty array resulting from 0 to the front, and b) if only one
                     of A and B is empty, it moves the non-empty one to the end.";
                  ~ "Unwrap the array, dumping all three sets on the stack.";

そして今、私たちは絶対的な差を見つけ、最小の最大値を選択します:

ff{-z}_z+::e<W+:e>
ff{-z}             "Turn A and B into a matrix of absolute differences.";
      _z           "Duplicate and transpose.";
        +          "Add the two together, so I've got one row of distances for
                    each element in either A or B.";
         ::e<      "Find the minimum of each row.";
             W+    "Add a -1 in case one set was empty.";
               :e> "Get the overall maximum.";

0スタックの一番下のイニシャルから生じる空の配列を常に保持しているが、空の配列は出力に何も寄与しないことに注意してください。


5

CJam、57 56 52バイト

私はこれは少しゴルフができると思うが、ここに行く:

q~ee_{W=2%},\{W=1>},]0ff=_W%]{~ff-{:z$1<~}%W+$W=}/e>

入力はCJamスタイルのリストのようになります。

[1 0 0 0 0 3 0 0 0 0 2]

5

仕組み

コードは2つの部分に分かれています。

リストに入力をパースするAB

q~ee_{W=2%},\{W=1>},]0ff=_W%]
q~                               "Eval the input array";
  ee                             "Enumerate and prepend index with each element. For ex:
                                  [5 3 6]ee gives [[0 5] [1 3] [2 6]]";
    _{W=2%},                     "Make a copy and filter out elements with value 1 or 3";
            \{W=1>},             "On the original, filter elements with value 2 or 3";
                    ]            "Wrap stack in an array. Stack right now contains
                                  enumerated A and B in an array";
                     0ff=        "Get the index of the enumerated arrays. Stack is [A B]";
                         _W%     "Make a copy and swap order. Stack is now [A B] [B A]";
                            ]    "Wrap this in an array";

二対の上の必要なアクションの実行AとをB

{~ff-{:z$1<~}%W+$W=}/e>
{                  }/            "Run this loop for both the pairs, [A B] and [B A]"
 ~ff-                            "Unwrap [A B] and take difference of every pair";
     {      }%                   "For each row in the matrix difference";
      :z$                        "abs each term and then sort";
         1<~                     "Take only the first element of the array";
              W+                 "Add -1 to compensate for an empty array";
                $W=              "Take max";
                     e>          "Take max of the two maximums";

こちらからオンラインでお試しください


5

Lua、235バイト

間違いなく勝者ではなく、少なくとも楽しいチャレンジです。

A={}B={}c={}d={}m=math p=m.min q=m.max u=unpack for k=1,#arg do for h=0,1 do if
arg[k]/2^h%2>=1 then A[#A+1]=k for i=1,#B do l=m.abs(B[i]-k)d[i]=p(d[i]or
l,l)c[#A]=p(c[#A]or l,l)end end A,B=B,A c,d=d,c end end
print(q(q(-1,u(c)),u(d)))

入力は次のように機能します。

lua hausdorff.lua <space-separated-sequence>

...そしてテストスクリプトを次に示します。

local testcase = arg[1] or 'hausdorff.lua'
print('testing '..testcase)
local function run(args) 
    return function(expected)
        local result = tonumber(
            io.popen('lua.exe '..testcase..' '..args):read'*a':match'%S+')
        print(args..' -> '..expected..' :: '..result)
        assert(result == expected,
            ("for input %q expected %s but got %s"):format(
                args, expected, result))
    end
end
run''(-1)
run'0'(-1)
run'0 1 0'(-1)
run'2 0 0 2'(-1)
run'0 1 2 3'(1)
run'0 3 3 0 0 0 0 3'(0)
run'1 0 0 1 0 0 1 3 1'(7)
run'1 0 0 0 0 3 0 0 0 0 2'(5)
run'0 1 1 3 1 3 2 1 1 3 0 3'(2)
run'2 2 2 1 2 0 3 1 3 1 0 3'(3)
run'1 3 0 2 0 2 2 1 0 3 2 1 1 2 2'(2)
run'1 0 1 1 2 0 1 2 3 1 0 0 0 1 2 0'(4)

...生産...

testing hausdorff.lua
 -> -1 :: -1
0 -> -1 :: -1
0 1 0 -> -1 :: -1
2 0 0 2 -> -1 :: -1
0 1 2 3 -> 1 :: 1
0 3 3 0 0 0 0 3 -> 0 :: 0
1 0 0 1 0 0 1 3 1 -> 7 :: 7
1 0 0 0 0 3 0 0 0 0 2 -> 5 :: 5
0 1 1 3 1 3 2 1 1 3 0 3 -> 2 :: 2
2 2 2 1 2 0 3 1 3 1 0 3 -> 3 :: 3
1 3 0 2 0 2 2 1 0 3 2 1 1 2 2 -> 2 :: 2
1 0 1 1 2 0 1 2 3 1 0 0 0 1 2 0 -> 4 :: 4

4

Pyth、43 40 39 38バイト

J+m0yQQLq3.|Fb?eS.e&Yfy:J-kT+hkT0JyJ_1

私のアルゴリズムは入力文字列で直接動作し、これらの数値を変換することはありません。最大値は一度だけ計算され、最小値は計算されません。

1バイトを保存してくれた@isaacgに感謝します。

オンラインで試す:Pyth Compiler / Executor

説明:

最初に、入力の前に多くのゼロを挿入します。

          implicit: Q = input()
    yQ    powerset(Q)
  m0yQ    map each element of the powerset to 0 (creates 2^Q zeros, I said lots)
 +    Q   zeros + Q
J         assign to J

私は、ヘルパー関数を定義y(入力のような)リストのインデックスは両方のセットAとBEGに現れる場合に伝え、y([0, 1, 0, 0, 1, 1]) = Falseしかしy([0, 1, 0, 2]) = y([3]) = True

Lq3.|Fb
L          define a function y(b), which returns _
   .|Fb       fold b by bitwise or
 q3            == 3

その後、最初に結果がであるかどうかを確認し-1ます。

?...yJ_1   print ... if numbers appear in both sets (`yJ`) else -1   

興味深いものへ:

  .e              J    map each pair k,Y in enumerate(J) to:
    &Y                   Y and ... (acts as 0 if Y == 0 else ...)
      f          0       find the first number T >= 0, where:
       y                    indices appear in both sets in the substring
        :J-kT+hkT           J[k-T:k+T+1]
eS                     sort and take last element (maximum)

TインデックスはリストJの両方のセットに現れることがすでにわかっているため、常に番号を見つけますlength(Q)。番号は最大です。これは、ゼロを挿入する理由でもあります。少なくともlength(Q)ゼロが挿入されている場合、k-Tは常にです>= 0。これはリストのスライスに必要です。では、なぜ2^length(Q)ゼロの代わりにlength(Q)ゼロを挿入するのですか?テストケース[]では、少なくとも1つのゼロが必要yJです。それ以外の場合はエラーが返されます。


><Cabはと同じ:Cbaです。
-isaacg

テストケースに大きな入力が含まれていないのは良いことです
...-TLW

3

Mathematica、88バイト

Max[Min/@#,Min/@Thread@#,-1]/.∞->-1&@Outer[Abs[#-#2]&,p=Position;p[#,1|3],p[#,2|3],1]&

1
とてもいい答えです。ハウスドルフ距離のより一般的な発見のために、一つは使用することができm=MaxValue;Max[m[RegionDistance[#[[1]],s],s\[Element]#[[2]]]/.m[__]->-1&/@{#,Reverse@c}]& 、その後そのような多次元オブジェクトに適用することができる%@{Sphere[],Line[{{1,1,0},{3,3,3}}]}
ケリーLowder

3

ハスケル、145の 126 124バイト

s t x=[e|(e,i)<-zip[0..]x,t i]
d#e=maximum[minimum[abs$i-j|j<-e]|i<-d]
[]%_= -1
_%[]= -1
d%e=max(d#e)$e#d
f x=s(>1)x%s odd x

試運転:

*Main> map f [[], [0], [0,1,0], [2,0,0,2], [0,1,2,3],
              [0,3,3,0,0,0,0,3], [1,0,0,1,0,0,1,3,1],
              [1,0,0,0,0,3,0,0,0,0,2], [0,1,1,3,1,3,2,1,1,3,0,3],
              [2,2,2,1,2,0,3,1,3,1,0,3],
              [1,3,0,2,0,2,2,1,0,3,2,1,1,2,2],
              [1,0,1,1,2,0,1,2,3,1,0,0,0,1,2,0]]

[-1,-1,-1,-1,1,0,7,5,2,3,2,4]

s述語tと入力リストに従って自然数をフィルタリングしますx#パラメータの最大距離を計算しますdおよびe%空のセットAまたはBをキャッチするか、d#eandの最終的な最大値を取りますe#d。セットAとB fで呼び出すメイン関数です%

編集:@Zgarbは保存するバイトをたくさん見つけました。@ ali0sha another 2.ありがとう!


mod 2不要と思われます。またab明示的に定義しないことから恩恵を受けることもあります。
-Zgarb

[]%_= -1-で2バイト節約できますが、私の試みをこれに打ち負かします:)
alexander-brett

3

Perl、56 55

に+2を追加しました-lp

入力リストは、スペースなしで標準入力に指定する必要があります。例:

echo 1011201231000120 | perl -lp hausdorf.pl

hausdorf.pl

s%%$z=$_&=$p|=$'|P.$p;$q+=!!y/12/3/%eg;$_=$z=~3?$q:-1

入力リストの要素間のスペースをサポートするには、$q2ストロークのコストで最終を2で割るだけです


2

Python 2、124

これは間違いなく最適ではないと感じます。しかたがない。

lambda a,E=enumerate:-min([1]+[~l*(n<3)for i,n in E(a)for l,_ in E(a)if{0}|set(n*a+n/3*[5])>{0,n}>=set(a[max(i-l,0):i-~l])])

1

APL(49)

{(⊂⍬)∊∆←(↓2 2⊤⍵)/¨⊂⍳⍴⍵:¯1⋄⌈/{⌈/⌊/⍵}¨(+,⍉¨)|∘.-/∆}

テストケース:

      ({(⊂⍬)∊∆←(↓2 2⊤⍵)/¨⊂⍳⍴⍵:¯1⋄⌈/{⌈/⌊/⍵}¨(+,⍉¨)|∘.-/∆} ¨ testcases) ,⍨ '→',⍨ ↑ ⍕¨testcases
                               → ¯1
0                              → ¯1
0 1 0                          → ¯1
2 0 0 2                        → ¯1
0 1 2 3                        →  1
0 3 3 0 0 0 0 3                →  0
1 0 0 1 0 0 1 3 1              →  7
1 0 0 0 0 3 0 0 0 0 2          →  5
0 1 1 3 1 3 2 1 1 3 0 3        →  2
2 2 2 1 2 0 3 1 3 1 0 3        →  3
1 3 0 2 0 2 2 1 0 3 2 1 1 2 2  →  2
1 0 1 1 2 0 1 2 3 1 0 0 0 1 2 0→  4

説明:

  • ⍳⍴⍵:1から入力リストの長さまでの数値のリストを取得します
  • ↓2 2⊤⍵:入力リストの各値について、最初のバイトと2番目のバイトを取得します
  • ∆←(... )/⊂⍳⍴⍵:両方のバイトリストで、から対応する値を選択します⍳⍴⍵。これらをに保存します。
  • (⊂⍬)∊∆... :¯1:このリストに空のリストが含まれる場合、を返し-1ます。さもないと:

  • |∘.-/∆:値のすべてのペア間の絶対差を取得し、行列を与える

  • (+,⍉¨):その行列の回転コピーと非回転コピーを取得します
  • {⌈/⌊/⍵}:両方の行列について、行の最小値の最大値を取得します
  • ⌈/:その後、その最大値を取得します

@Optimizer:バグがあった以前のバージョンからテスト出力をなんとかコピーできました。コード自体は正しく、今でも正しいです。あなたが私を信じないなら、ここを試してください。(,Xスカラと区別するために、1要素リストをとして入力する必要があることに注意してくださいX。)
マリナス

ああ、なるほど。オンラインコンパイラーとテストに行かないのは怠け者
オプティマイザー

1

Perl、189 176 157B

状態が500%増えました。

use List::Util qw'max min';@I=<>;sub f{$n=($n%2)+1;map{$I[$_]&$n?$_:()}0..$#I}sub i{@t=f;max map{$b=$_;min map{abs$_-$b}@t}f}$r=max i,i;print defined$r?$r:-1

読みやすい:

use List::Util qw'max min';
@I=<>;
sub f {
    $n = ($n%2) + 1;
    map { $I[$_] & $n ? $_ : () } 0..$#I
}
sub i {
    @t = f;
    max map {
        $b = $_;
        min map { abs $_ - $b } @t
    } f
}
$r = max i,i;
print defined $r ? $r : -1

使用例:

入力

0
1
2
3

perl golf.pl < input


0

Clojure、167バイト

#(let[P apply F(fn[I](filter(fn[i](I(% i)))(range(count %))))A(F #{1 3})B(F #{2 3})d(fn[X Y](P min(for[x X](P max(for[y Y](P -(sort[x y])))))))](-(min(d A B)(d B A))))

もっと短い方法があるはずです...ありますか?

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