challenge データの整列

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

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

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

Posted feedbacks - Scala

Scalaで。

    CoordSort.lexical(List((1,2), (3,4), (1,3), (2,4), (1,8))).toList
    // => List((1,2), (1,3), (1,8), (2,4), (3,4))

    CoordSort.fromOrigin(List((1,2), (3,4), (1,3), (2,4), (1,8))).toList
    // => List((1,2), (1,3), (2,4), (3,4), (1,8))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
object CoordSort {
  import scala.util.Sorting.stableSort
  type Coord = Pair[int,int]

  def sort(f:(int, int, int, int) => boolean, lst:Seq[Coord]) = {
    stableSort(lst, (a:Coord, b:Coord) => f(a._1, a._2, b._1, b._2))
  }

  val lexical = Function.curried(sort _)((ax, ay, bx, by) => 
                  if(ax == bx) { ay < by } else { ax < bx }
                )

  val fromOrigin = Function.curried(sort _)((ax, ay, bx, by) => 
                     (ax*ax + ay*ay) < (bx*bx + by*by)
                   )

}

Index

Feed

Other

Link

Pathtraq

loading...