我有一个数组如下
#bad
tourney = [
[
[["Armando", "P"], ["Dave", "S"]],
[["Richard", "R"], ["Michael", "S"]]
],
[
[["Allen", "S"], ["Omer", "P"]],
[["David E.", "R"], ["Richard X.", "P"]]
]
]
我必须实施一种递归锦标赛方法,让每个竞争对手彼此对抗。只要它的2 ^ n,这场比赛必须增加到任何数字。是否有任何数组方法将此数组分成两个级别,如下面的数组?
#good
tourney = [
["Armando", "P"], ["Dave", "S"],
["Richard", "R"], ["Michael", "S"],
["Allen", "S"], ["Omer", "P"],
["David E.", "R"], ["Richard X.", "P"]
]
有了这个,我可以使用each_slice(2)
让对手相互对抗。
以下是我能够提出来的。
def split(array)
return array.flatten(1)
end
def depth_array(a)
return 0 unless a.is_a?(Array)
return 1+depth_array(a[0])
end
def format_array(array)
good = array
while depth_array(good) > 2
good = split(good)
end
end
tourney = [[[["Armando", "P"], ["Dave", "S"]],
[["Richard", "R"], ["Michael", "S"]]],
[[["Allen", "S"], ["Omer", "P"]],
[["David E.", "R"], ["Richard X.", "P"]]]]
tourney2 = [[["Armando", "P"], ["Dave", "S"]],
[["Allen", "S"], ["Omer", "P"]]]
tourney3 = [["Omer", "P"], ["Allen", "S"]]
tourney4 = [[[[["Armando", "P"], ["Armando", "P"]], [["Armando", "P"], ["Armando", "P"]]],
[[["Allen", "S"], ["Allen", "S"]], [["Allen", "S"], ["Allen", "S"]]]],
[[[["Dave", "S"], ["Dave", "S"]], [["Dave", "S"], ["Dave", "S"]]],
[[["David E.", "R"], ["David E.", "R"]], [["David E.", "R"], ["David E.", "R"]]]]]
format_array(tourney4)
答案 0 :(得分:2)
tourney.flatten(2)
将坏数组转换为好数组。
答案 1 :(得分:0)
这样的事情怎么样:
tourney = [[[["Armando", "P"], ["Dave", "S"]],
[["Richard", "R"], ["Michael", "S"]]],
[[["Allen", "S"], ["Omer", "P"]],
[["David E.", "R"], ["Richard X.", "P"]]]]
good = [].tap do |arr|
tourney.flatten.each_slice(2) do |pr|
arr << pr
end
end
puts good.inspect
# output
[["Armando", "P"], ["Dave", "S"], ["Richard", "R"], ["Michael", "S"], ["Allen", "S"], ["Omer", "P"], ["David E.", "R"], ["Richard X.", "P"]]