Skip to content

Instantly share code, notes, and snippets.

@Kuchitama
Forked from zerosum/Euler0009.scala
Last active December 11, 2015 09:18
Show Gist options
  • Save Kuchitama/4578521 to your computer and use it in GitHub Desktop.
Save Kuchitama/4578521 to your computer and use it in GitHub Desktop.
Other patterns of [zerosum's answer](https://gist.github.com/4578404)
/** try to use Tuple */
object Euler0009 {
private val max = 1000
def main(args: Array[String]) {
println(
triplet(1, 2).filter{ case(a, b, c) => a*a + b*b == c*c}
.map{case (a, b, c) => a * b * c}
)
}
def triplet(a: Int, b: Int, triplets: List[(Int, Int, Int)] = Nil): List[(Int, Int, Int)] = {
val c = max - a - b
if(a > max/3) {
triplets
} else if(b < c) {
triplet(a, b+1, (a, b, c) :: triplets)
} else {
triplet(a+1, a+2, triplets)
}
}
}
/** try to use pattern match */
object Euler0009 {
private val max = 1000
def main(args: Array[String]): Unit = {
println(
triplet(1, 2).filter{case a :: b :: c :: Nil => a*a + b*b == c*c}
.map(_.product)
)
}
def triplet(a: Int, b: Int, triplets: List[List[Int]] = Nil): List[List[Int]] = {
val c = max - a - b
if(a > max/3) {
triplets
} else if(b < c) {
triplet(a, b+1, List(a, b, c) :: triplets)
} else {
triplet(a+1, a+2, triplets)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment