rubylearn-ruby-the-hard-way

Nested Loop: to be dynamic?


Ok i'm actually doing this exercise to tackle those nested loop questions. I would say this would be the hardest one for me. I tried my best to be more dynamic instead of static. Can anyone give me tips on how to solve this?

expected output:

1
1 2
1 2 4
1 2 4 8
1 2 4 8 16
1 2 4 8 16 32
1 2 4 8 16 32 64
1 2 4 8 16 32 64 128

this is my static code:

n = 1
for i in 1..8

       for c in 1..n
               case i
                     when 1
                        print "1"
                     when 2
                        print "1 2"
                     when 3
                        print "1 2 4"
                     when 4
                        print "1 2 4 8"
                     when 5
                        print "1 2 4 8 16"
                     when 6
                        print "1 2 4 8 16 32"
                     when 7
                        print "1 2 4 8 16 32 64"
                     when 8
                        print "1 2 4 8 16 32 64 128"
               end
                  print "\n"
       end
end

I'm not looking for answer. But i would appreciate that you can guide me.


Solution

  • for x in 0..7
      for y in 0..x
        op = 2**y
        print op, " "
      end
      puts ""
    end
    

    Prints

    1 
    1 2 
    1 2 4 
    1 2 4 8 
    1 2 4 8 16 
    1 2 4 8 16 32 
    1 2 4 8 16 32 64 
    1 2 4 8 16 32 64 128