如何使用for循环制作floyd三角形?

时间:2015-05-15 06:51:18

标签: ruby loops nested-loops

我需要输出Floyd三角形,如:

1
0 1
1 0 1
0 1 0 1

我试过了。我没有完全理解。任何人都可以解释这个逻辑吗?

这是我尝试过的代码:

k = 0
for i in 1..5 
  for j in 1..5 
    if (i%2)==0; 
      k = (j%2==0) ? 1:0; 
    else; 
      k = (j%2==0) ? 0:1; 
      puts k,''; 
    end
  end
  puts
end

5 个答案:

答案 0 :(得分:0)

您可以尝试使用以下输出代码:

k = 0
for i in 1..4
  for j in 1..i  // inner loop code runs i times for each outer loop iteration
    if (i%2)==0; 
       k = (j%2==0) ? 1:0; 
    else; 
       k = (j%2==0) ? 0:1; 
    end
    print k,' '; 
   end
   puts
end

Click Here查看输出。

您还可以通过this link.

了解for循环

答案 1 :(得分:0)

好的以下应该有效,但我希望它具有可读性。如果您需要更多解释或有特定问题,请告诉我

if

答案 2 :(得分:0)

这里的主要问题是为了获得"三角形"输出的形状,你需要你的内部循环从1增加到i而不是1到5。

k = 0
for i in 1..5 
  for j in 1..i
    if (i%2)==0
      k = j + 1
    else
      k = j
    end
    print "#{k%2} "
  end
  puts
end

答案 3 :(得分:0)

这是一条单行方法:

5.times {|line| puts (line + 1).times.with_object(""){|num, str| (num + line).even? ? (str << " 1 ") : (str << " 0 ") } }

使其更清晰:

lines = 5
lines.times do |line|
  str = ""
  line = line + 1 # 5.times runs from 0 to 4 and we need 1 to 5
  line.times do |num|
    # the condition is a bit different because I changes the code a bit
    if (line + num).even?
      str << " 0 "
    else
      str << " 1 "
    end
  end
  puts str
end

答案 4 :(得分:0)

首选的红宝石方式:

layers = 4  # Change to as many layers as you want
layers.times do |i|  # i starts from 0
  (i + 1).times do |j|  # j also starts from 0
    print (i + j + 1) & 1, ' '
  end
  puts
end

for方式:

layers = 4
for i in 0...layers
  for j in 0...(i + 1)
    print (i + j + 1) & 1, ' '
  end
  puts
end