challenge データの整列

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

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

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

Posted feedbacks - OCaml

OCamlで書いてみた。こんなんでいいのかな。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type point = Poiont of float * float


let compare_point a b =
  match (a, b) with
    (Point (x1, y2), Point (x2, y2)) -> if x1 = x2 then compare y1 y2
                                                   else compare x1 x2

let distance = function
    Point (x, y) -> sqrt (x *. x +. y *. y)


let sort_by_dic = List.sort compare_point


let sort_by_dis = List.sort (fun a b -> compare (distance a) (distance b))

やっつけコード。

1
2
let dict_sort = List.sort (fun (x1,x2) (y1,y2) -> match x1 - y1 with 0 -> x2 - y2 | d -> d);;
let dist_sort = List.sort (fun (x1,x2) (y1,y2) -> (x1*x1 + x2*x2) - (y1*y1 + y2*y2));;

うわっ,typoしたままのを貼り付けてしまいました(今頃気づいた)。改めて張り直しておきます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type point = Point of float * float


let compare_point a b =
  match (a, b) with
    (Point (x1, y1), Point (x2, y2)) -> if x1 = x2 then compare y1 y2
                                                   else compare x1 x2

let distance = function
    Point (x, y) -> sqrt (x *. x +. y *. y)


let sort_by_dic = List.sort compare_point


let sort_by_dis = List.sort (fun a b -> compare (distance a) (distance b))

Index

Feed

Other

Link

Pathtraq

loading...