challenge データの整列

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

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

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

Posted feedbacks - JavaScript


	
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function Point(x, y){
    this.x=x;
    this.y=y;
    this.size=Math.sqrt(x*x+y*y);
    this.toString=function(){ return "(" + this.x + "," + this.y + ")" }
}

var data = new Array(
    new Point(0,0),
    new Point(1,0),
    new Point(2,0),
    new Point(0,1),
    new Point(1,1),
    new Point(2,1),
    new Point(0,2),
    new Point(1,2),
    new Point(2,2)
);

data.sort(function(a,b){ return(a.size - b.size) });
print(data.join());
data.sort(function(a,b){ return (a.x == b.x) ? a.y - b.y :a.x - b.x });
print(data.join());

1
2
3
var _arr = [[1,2],[2,2],[3,2],[14,1],[2,1]];
WScript.Echo(  _arr.sort().join(" ") );
WScript.Echo(  _arr.sort( function(a,b){ return (a[0]* a[0]+ a[1]*a[1] )>(b[0]* b[0]*+ b[1]*b[1]);} ).join(" ") );

Index

Feed

Other

Link

Pathtraq

loading...