ONLY DO WHAT ONLY YOU CAN DO

こけたら立ちなはれ 立ったら歩きなはれ

Scala で Project Euler Problem 9

scala> (1 to 9)
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
 
scala> (1 to 9).
     | map(a => (a + 1 to 10))
res1: scala.collection.immutable.IndexedSeq[scala.collection.immutable.Range.Inclusive] = Vector(Range(2, 3, 4, 5, 6, 7, 8, 9, 10), Range(3, 4, 5, 6, 7, 8, 9, 10), Range(4, 5, 6, 7, 8, 9, 10), Range(5, 6, 7, 8, 9, 10), Range(6, 7, 8, 9, 10), Range(7, 8, 9, 10), Range(8, 9, 10), Range(9, 10), Range(10))
 
scala> (1 to 9).
     | map(a => (a + 1 to 10).map(b => (a, b)))
res2: scala.collection.immutable.IndexedSeq[scala.collection.immutable.IndexedSeq[(Int, Int)]] = Vector(Vector((1,2), (1,3), (1,4), (1,5), (1,6), (1,7), (1,8), (1,9), (1,10)), Vector((2,3), (2,4), (2,5), (2,6), (2,7), (2,8), (2,9), (2,10)), Vector((3,4), (3,5), (3,6), (3,7), (3,8), (3,9), (3,10)), Vector((4,5), (4,6), (4,7), (4,8), (4,9), (4,10)), Vector((5,6), (5,7), (5,8), (5,9), (5,10)), Vector((6
 
scala> (1 to 9).
     | flatMap(a => (a + 1 to 10).map(b => (a, b)))
res3: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,2), (1,3), (1,4), (1,5), (1,6), (1,7), (1,8), (1,9), (1,10), (2,3), (2,4), (2,5), (2,6), (2,7), (2,8), (2,9), (2,10), (3,4), (3,5), (3,6), (3,7), (3,8), (3,9), (3,10), (4,5), (4,6), (4,7), (4,8), (4,9), (4,10), (5,6), (5,7), (5,8), (5,9), (5,10), (6,7), (6,8), (6,9), (6,10), (7,8), (7,9), (7,10), (8,9), (8,10), (9,10))
 
scala> (1 to 9).
     | flatMap(a => (a + 1 to 10).map(b => (a, b))).
     | collect{case (a,b) if a % 3 == 0 || b % 3 == 0 => (a, b)}
res4: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((1,3), (1,6), (1,9), (2,3), (2,6), (2,9), (3,4), (3,5), (3,6), (3,7), (3,8), (3,9), (3,10), (4,6), (4,9), (5,6), (5,9), (6,7), (6,8), (6,9), (6,10), (7,9), (8,9), (9,10))
 
scala> (1 to 499).
     | flatMap(a => (a + 1 to 500).map(b => (a, b))).
     | collect{case (a,b) if 1000 * (a + b) - (a * b) == 500000 => (a, b, 1000 - (a + b))}
res5: scala.collection.immutable.IndexedSeq[(Int, Int, Int)] = Vector((200,375,425))
 
scala> (1 to 499).
     | flatMap(a => (a + 1 to 500).map(b => (a, b))).
     | filter(t => 1000 * (t._1 + t._2) - (t._1 * t._2) == 500000)
res6: scala.collection.immutable.IndexedSeq[(Int, Int)] = Vector((200,375))
 
scala> (1 to 499).
     | flatMap(a => (a + 1 to 500).map(b => (a, b))).
     | filter(t => 1000 * (t._1 + t._2) - (t._1 * t._2) == 500000).
     | flatMap(t => List(t._1, t._2, 1000 - (t._1 + t._2)))
res7: scala.collection.immutable.IndexedSeq[Int] = Vector(200, 375, 425)
 
scala> (1 to 499).
     | flatMap(a => (a + 1 to 500).map(b => (a, b))).
     | filter(t => 1000 * (t._1 + t._2) - (t._1 * t._2) == 500000).
     | flatMap(t => List(t._1, t._2, 1000 - (t._1 + t._2))).
     | reduceLeft(_*_)
res8: Int = 31875000