【问题标题】:Array.push doesn't work for two dimentional arrayArray.push 不适用于二维数组
【发布时间】:2013-12-12 17:54:02
【问题描述】:

我正在尝试向 ruby​​ 中的二维数组添加更多元素,但 .push 方法不起作用。在截图中,我打印出了所有元素,最后一行是数组。

代码如下:

def solution(a)
  x = 0
  y = 1
  coordinates = [[0, 0]]
  a.each_with_index do |i, index|
    next_coordinate = coordinates[coordinates.length-1]
    case (index%4)
    when 0
      next_coordinate[y] += i
    when 1
      next_coordinate[x] += i
    when 2
      next_coordinate[y] -= i
    else
      next_coordinate[x] -= i
    end
    puts next_coordinate.to_s
    coordinates.push(next_coordinate)
  end
  return coordinates.to_s
end

a = [1, 3, 2, 5, 4, 4, 6, 3, 2]
puts solution(a)

【问题讨论】:

  • 预期输出是什么?
  • [[0, 0], [0, 1], [3, 1], [3, -1], [-2, -1], [-2, 3], [ 2, 3], [2, -3], [-1, -3], [-1, -1]]
  • 请考虑将您的结果作为文本而不是屏幕截图添加到问题中。屏幕截图不能剪切和粘贴,而且更难阅读。您的预期输出也应该包含在问题本身中。

标签: ruby arrays push


【解决方案1】:

代码多次使用同一个数组对象。

代码执行如下操作:

a = [[1]]
a.push(a[-1])
a
# => [[1], [1]]
a[-1][0] += 1
a
# => [[2], [2]]

简单的解决方法是使用clone 方法复制对象。

next_coordinate = coordinates[coordinates.length-1].clone

【讨论】:

    【解决方案2】:
    def solution(a)
      a.each_with_index.inject([[0, 0]]) do |c, (i,index)|
        c.push( c.last.clone.tap do |nc| 
            xy=1-index%2
            sign=(1-2*((index/2)%2)))
            nc[xy] += i * sign 
         end
        )
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 2021-07-15
      • 2022-06-15
      • 2021-11-21
      • 2021-09-30
      • 2023-04-06
      相关资源
      最近更新 更多