Sonntag, 3. Juli 2011

Simple Problem, Simple Solution(s)

Borrowed from :
http://learnyouahaskell.com/starting-out#im-a-list-comprehension
Which right triangle that has integers for all sides and all sides equal to or smaller than 10 has a perimeter of 24? 


Haskell
[ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24]


Scala

for {c <- 1 to 10; b <- 1 to c; a <- 1 to b; if(a+b+c == 24 && (a*a) +(b*b) ==(c*c))} yield (a,b,c)



C#

var result= from c in Enumerable.Range(1, 10)
from b in Enumerable.Range(1, c)
from a in Enumerable.Range(1, b)
where a+b+c == 24 && (a*a) + (b*b) == (c*c)
select a+" "+b+" "+c;


More on comprehensions:
http://patternsinfp.wordpress.com/2012/01/19/comprehensions/
Haskell
[2 * a + b | a <-[1,2,3], b <- [4,5,6],  b `mod` a == 0]


Scala
for{a <- 1 to 3; b <- 4 to 6; if (b % a == 0)} yield(2 * a + b)

Keine Kommentare:

Kommentar veröffentlichen