Ruby:在散列中分配数组值

问题描述 投票:2回答:6

我想要以下哈希输出:

{ 0 => [0,1,2], 1 => [0,1,2], 2 => [0,1,2],
  3 => [3,4,5], 4 => [3,4,5], 5 => [3,4,5],
  6 => [6,7,8], 7 => [6,7,8], 8 => [6,7,8]
}

直觉上我可以硬编码这些值,但我很难弄清楚如何动态地将每个哈希键分配给适当的数组值。例如,可能创建一个9次循环?

{ 0 => (0..2).to_a, 1 => (0..2).to_a, 2 => (0..2).to_a,
  3 => (3..5).to_a, 4 => (3..5).to_a, 5 => (3..5).to_a, 
  6 => (6..8).to_a, 7 => (6..8).to_a, 8 => (6..8).to_a 
}

谢谢你的指导

arrays ruby hash
6个回答
2
投票

具有动态上限:

count, split = 9, 3
0.upto(count - 1).map do |i|
  [i, [*(i / split * split)...(i / split) * split + split]]
end.to_h

2
投票

使用模运算(%),您可以计算子数组的值:

(0..8).map { |i| [i, (i - i%3 .. i - i%3 + 2).to_a] }.to_h

# => {0=>[0, 1, 2], 1=>[0, 1, 2], 2=>[0, 1, 2], 3=>[3, 4, 5], 4=>[3, 4, 5], 5=>[3, 4, 5], 6=>[6, 7, 8], 7=>[6, 7, 8], 8=>[6, 7, 8]}


0
投票

也许是这样的:

[0..2, 3..5, 6..8].each.with_object({}) do |range, result|
  range.each do |ind|
    result[ind] = range.to_a
  end
end

0
投票
dummy_data = {}
(0..8).to_a.each_slice(3).map{ |m| m.each{|v| dummy_data[v] = m }}

它会生成预期的虚拟数据

dummy_data
 => {0=>[0, 1, 2], 1=>[0, 1, 2], 2=>[0, 1, 2], 3=>[3, 4, 5], 4=>[3, 4, 5], 5=>[3, 4, 5], 6=>[6, 7, 8], 7=>[6, 7, 8], 8=>[6, 7, 8]} 

0
投票
def make_da_hash(n)
  a = (0..n*n-1).to_a
  a.zip(a.each_slice(n).flat_map { |e| [e]*n }).to_h
end

make_da_hash(3)
  #=> {0=>[0, 1, 2], 1=>[0, 1, 2], 2=>[0, 1, 2],
  #    3=>[3, 4, 5], 4=>[3, 4, 5], 5=>[3, 4, 5],
  #    6=>[6, 7, 8], 7=>[6, 7, 8], 8=>[6, 7, 8]} 

make_da_hash(4)
  #=> {0=>[0, 1, 2, 3], 1=>[0, 1, 2, 3], 2=>[0, 1, 2, 3], 3=>[0, 1, 2, 3],
  #    4=>[4, 5, 6, 7], 5=>[4, 5, 6, 7], 6=>[4, 5, 6, 7], 7=>[4, 5, 6, 7],
  #    8=>[8, 9, 10, 11], 9=>[8, 9, 10, 11], 10=>[8, 9, 10, 11],
  #    11=>[8, 9, 10, 11], 12=>[12, 13, 14, 15], 13=>[12, 13, 14, 15],
  #    14=>[12, 13, 14, 15], 15=>[12, 13, 14, 15]} 

0
投票
{}.merge(*Array.new(3){|i| (0..8).group_by{|n| n / 3 * 3 + i}})  

输出:

{
  0=>[0, 1, 2],
  3=>[3, 4, 5],
  6=>[6, 7, 8],
  1=>[0, 1, 2],
  4=>[3, 4, 5],
  7=>[6, 7, 8],
  2=>[0, 1, 2],
  5=>[3, 4, 5],
  8=>[6, 7, 8]
}
© www.soinside.com 2019 - 2024. All rights reserved.