Suresh
Suresh

Reputation: 39

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.

Upvotes: 3

Views: 118

Answers (2)

Karan Shah
Karan Shah

Reputation: 1324

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 

Upvotes: 3

peter
peter

Reputation: 42182

You need to store the result of every step and add the new step.

Ruby doesn't work much with for's, there are better methods such as the .upto method I use here. The inject provides the result variable out at which you can add the step calculation. The " #{2**i} " is the calculation interpolated as a string with a space after.

(0.upto 8).inject("") do |out, i|
  puts out
  out << "#{2**i} "
end

Which gives

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 

Upvotes: 1

Related Questions