Skip to content

Instantly share code, notes, and snippets.

@songfei1983
Last active May 6, 2016 10:35
Show Gist options
  • Save songfei1983/9812ea4225fc84866d701104babb9920 to your computer and use it in GitHub Desktop.
Save songfei1983/9812ea4225fc84866d701104babb9920 to your computer and use it in GitHub Desktop.
判断由参数中的四个点是否构成一个正方形。
package com.example
import scala.math._
object Square extends App {
case class Point(x: Int, y: Int)
implicit class CombinatorialList[A](l: List[A]) {
val xsize = l.size
def xcombinations(n: Int): List[List[A]] =
if (n > xsize) Nil
else l match {
case _ :: _ if n == 1 => l.map(List(_))
case hd :: tl => tl.xcombinations(n - 1).map(hd :: _) ::: tl.xcombinations(n)
case _ => Nil
}
}
def isSquare(p1: Point, p2: Point, p3: Point, p4: Point): Boolean = {
def apow(a: Int, b: Int) = pow(a - b, 2)
def distance(a: Point, b: Point) = sqrt(apow(a.x, b.x) + apow(a.y, b.y))
List(p1, p2, p3, p4).xcombinations(2).map(t => distance(t(0), t(1))).distinct.size == 2
}
assert(!isSquare(Point(1, 6), Point(6, 7), Point(2, 7), Point(9, 1)))
assert(!isSquare(Point(4, 1), Point(3, 4), Point(0, 5), Point(1, 2)))
assert(isSquare(Point(4, 6), Point(5, 5), Point(5, 6), Point(4, 5)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment