challenge データの整列

(x, y) の座標情報を以下の2種類の方法で整列する機能を実現してください。

  • (x, y) の辞書順(まず x で昇順に整列して、x が同じデータに対して y で昇順に整列する)
  • (0, 0) からの距離の昇順

データの表現方法はタプルなり構造体/オブジェクトなり各自で適当に選んで下さい。

Posted feedbacks - PostScript

PostScript で。 比較手続の定義を変えれば他の順で並べるのも可。バブルソートですが、スタックがぐるぐるまわります...
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
%!PS

/CompareXY { % [x1 y1] [x2 y2] CompareXY x2-x1 (or y2-y1)
    2 copy 0 get exch 0 get sub % [x1 y1] [x2 y2] x2-x1
    dup 0 eq {
        pop 1 get exch 1 get sub % y2-y1
    } {
        exch pop exch pop
    } ifelse
} bind def

/CompareDistance { % [x1 y1] [x2 y2] CompareDistance r2^2-r1^2
    dup 0 get dup mul exch 1 get dup mul add exch
    dup 0 get dup mul exch 1 get dup mul add sub
} bind def

/Sort { % [[x y] [x1 y1] Array Data ] {CompareFunction}  Sort [ArrayData]
    cvx [ 3 -1 roll
    aload length
    % func -mark- [] [] ... [] len
    -1 2 { % func -mark- [] [] ... [] len2
        -1 2 {
            3 1 roll
            2 copy counttomark 1 add index exec  %% Compare
            0 gt { exch } if
            3 -1 roll
            1 roll
        } for
        counttomark 1 roll
    } for
    counttomark 1 roll
    ] exch pop
} bind def

% ------------ Test Code ---------------
/TestSample [
    [1 3]
    [2 4]
    [3 1]
    [2 2]
    [0 2]
    [2 0]
] def

TestSample /CompareXY Sort ==

TestSample /CompareDistance Sort ==

Index

Feed

Other

Link

Pathtraq

loading...