而vs每个循环

时间:2015-08-14 13:07:55

标签: arrays ruby loops

我正在转换M行和N列的二维数组,其中M是外部数组的长度,N是嵌套数组的长度(我在解决方案中考虑了不同的长度):

a = [[1, 2], [3, 4, 5], [6], [7, 8, 9], [10, 11, 12]]

each的工作解决方案是:

(0..(@columns-1)).each do |col|
  (0..(@rows-1)).each do |row|
    print @ar[row][col]
  end
  print "\n"
end

结果是:

136710
24-811
-5-912

作为验证的结果,我用'-'填充空白点以使内部数组具有相同的长度。

我尝试使用以下while循环来解决问题:

while @columns > 0
  while @rows > 0
    p @ar[(@rows - 1)][(@columns - 1)]
    @rows = @rows - 1
  end
  @columns = @columns - 1
end

结果是:

12
9
"-"
5
"-"

为什么each循环没有工作while循环?

1 个答案:

答案 0 :(得分:1)

主要问题是,在您第一次退出内部行循环后,@rows设置为0.由于@rows永远不会重置为其原始值,@rows > 0将进入下一栏后仍然是假的。试试这个:

original_rows = @rows
while @columns > 0
  while @rows > 0
    print @ar[(@rows - 1)][(@columns - 1)] # Also use `print` here, not `p`
    @rows = @rows - 1
  end
  print "\n" # You also forgot this
  @columns = @columns - 1
  @rows = original_rows # Move back to the first row
end

当然,在实际应用中,转置数组的最佳方法实际上就是:

@ar.transpose

但这对学习练习没有多大帮助。