如何将值推入多维数组(RUBY)

时间:2014-12-15 17:19:26

标签: ruby arrays

我希望将值1推入随机索引点的所有0的数组中。 数组的格式是10×10的0被排列成方形表。我想为此生成一个随机输入点,并将该值更改为1。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法: -

# First create an array of array
array = Array.new(10) { Array.new(10) { 0 } }

# method to get the random index.
def random_index(start_point = 0, end_point)
  (start_point..end_point).to_a.sample
end

# First find out the any random inner array
inner_array = array[random_index(0, array.size-1)]
# Then get the any random index from the inner array and update the value.
inner_array[random_index(0, array.size-1)] = 1
array
# => [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

回答OP's comment: -

def get_index_of_item_from_inner_array(array, item)
  first_inner_array_contains_item = array.find { |in_ary| in_ary.include? item }
  (0..first_inner_array_contains_item.size - 1).find { |ind| first_inner_array_contains_item[ind] == item }
end

get_index_of_item_from_inner_array(array, 1) # => 2

答案 1 :(得分:0)

一种方式:

arr = Array.new(10) { Array.new(10) { 0 } }

row, col = rand(100).divmod(10)
arr[row][col] = 1

row #=> 7
col #=> 6
arr
  #=> [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  #    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]