Skip to main content
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
edited tags
Link
Jamal
  • 34.9k
  • 13
  • 133
  • 237
Source Link
Kevin Meredith
  • 3.2k
  • 28
  • 51

Find Pythagorean Triple with Perimeter == 24

Learn You a Haskell gives this exercise:

Here's a problem that combines tuples and list comprehensions: which right triangle that has integers for all sides and all sides equal to or smaller than 10 has a perimeter of 24? First, let's try generating all triangles with sides equal to or smaller than 10:

Here's my solution in Scala. Note that I'm ignoring the right triangle part.

val a = List.range(1,11)
val b = List.range(1,11)
val c = List.range(1,11)

def sumsEqualsTo24(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] = 
                           if(x + y + z == 24) Some( (x,y,z) ) else None

def pythagTriple(x: Int, y: Int, z: Int): Option[(Int, Int, Int)] = { 
                             if( Math.pow(x, 2) + Math.pow(y, 2) == Math.pow(z, 2) )
                                  Some( (x,y,z) ) 
                             else None
}

Using flatMap

val xs: List[(Int, Int, Int)] = a.flatMap(x => 
                                 b.flatMap(y => 
                                  c.flatMap(z => sumsEqualsTo24(x, y, z) ) ) )                                   

val ys: List[(Int, Int, Int)] = xs.flatMap{a => pythagTriple(a._1, a._2, a._3)}

Using for-comprehension

for {
  a <- List.range(1, 11)
  b <- List.range(1, 11)
  c <- List.range(1, 11) 
  xs <- sumsEqualsTo24(a,b,c)
  _ <- pythagTriplebar(xs._1, xs._2, xs._3)
} yield (a,b,c)

Could you please critique my code?