From: Robert Klemme Date: 2011-09-05T17:30:18+09:00 Subject: Re: Beginner needing help - Writing right-angle triangle program On Sun, Sep 4, 2011 at 6:43 AM, Josh Cheek wrote: > On Sat, Sep 3, 2011 at 11:23 PM, Kane Williams wrote: > >> Thanks for the reply! >> >> I wanted to get something out of the way first, some other guy made a >> thread exactly the same as my one and it has generated 6 replys somehow. >> It is located here http://www.ruby-forum.com/topic/2497160#new although >> you can probably just see it for yourself on the frontpage. >> >> We are in no way connected, in fact I don't really know any other >> programmers :O. So I would assume this is a glitch in the system. I hope >> there is some way to merge these two threads together. >> >> Now to reply to the questions: >> >> > Is this no good? >> > [7, 7.058823529, 9.941176471] >> > >> > or this? >> > [6.5, 7.542857143, 9.957142857] >> > >> > >> > Are you requiring only integers? >> > Can you show some code? >> >> Yea for simplicity's sake I just want full integers, although I don't >> really mind either way. >> >> Here is the Haskell code: >> ghci> let rightTriangles' = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- >> [1..b], a^2 + b^2 == c^2, a+b+c == 24] >> ghci> rightTriangles' >> [(6,8,10)] >> >> Which was found at the bottom of this tutorial: >> http://learnyouahaskell.com/starting-out#tuples >> >> And I don't have any ruby code, that's why I'm posting here! :3 Just >> wondering how I would start about to make a program which uses >> Pythagoras Theorem. >> >> -- >> Posted via http://www.ruby-forum.com/. >> >> > A direct translation of that would look like this: > > def right_triangles >  results = [] >  (1..10).each do |c| >    (1..c).each do |b| >      (1..b).each do |a| >        results << [a, b, c] if a+b+c == 24 && a**2 + b**2 == c**2 >      end >    end >  end >  results > end > > right_triangles # => [[6, 8, 10]] I'd rather stick with a more traditional approach for c in 1 .. perimeter / 2 cq = c * c for b in 1 ... c a = perimeter - c - b p [a, b, c] if a * a + b * b == cq end end Note: the third side can be calculated from the first two sides so iterating is not necessary for that. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/