通过切成两半但扩展元素来转换数组

时间:2017-03-30 09:17:43

标签: arrays ruby

我想转换现有数组以显示它。因此,我将数组切成两半,但将切割元素的内容添加到剩余元素中。

# source structure
s = [[1, 'blue'], 
     [2, 'red'], 
     [3, 'yellow'], 
     [4, 'green'], 
     [5, 'orange'], 
     [6, 'black']]

# result structure
format_array(s) 
# [[1, 'blue', 4, 'green'], 
#  [2, 'red', 5, 'orange'], 
#  [3, 'yellow', 6, 'black']]

你会如何实现它?

6 个答案:

答案 0 :(得分:4)

a = [[1, "blue"], [2, "red"], [3, "yellow"], [4, "green"], [5, "orange"], [6, "black"]]
first, last = a.first(a.size / 2), a.last(a.size / 2)
#=> [[[1, "blue"], [2, "red"], [3, "yellow"]], [[4, "green"], [5, "orange"], [6, "black"]]]
first.zip(last).map(&:flatten)
# [
#   [1, "blue", 4, "green"],
#   [2, "red", 5, "orange"],
#   [3, "yellow", 6, "black"]
# ]

答案 1 :(得分:3)

再多一个解决方案:

a.each_slice(a.size / 2).to_a.transpose.map(&:flatten)
#=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]

答案 2 :(得分:2)

第1步: 使用 each_slice 数组方法将数组划分为两个each_slice documentation

第2步:使用array.zip方法映射数组self with corresponding elementszip documentation

第3步:使用flatten展平数组。 Flatten documentation

s  => [[1, "blue"], [2, "red"], [3, "yellow"], [4, "green"], [5, "orange"], [6, "black"]]

s1,s2 = s.each_slice((s.length)/2).to_a

==> [[[1, "blue"], [2, "red"], [3, "yellow"]], [[4, "green"], [5, "orange"], [6, "black"]]]

s1.zip(s2).map(&:flatten)

=> [[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]

答案 3 :(得分:2)

s.each_slice((s.size + 1) / 2).reduce(&:zip).map(&:flatten)

答案 4 :(得分:1)

s = [[1, 'blue'], [2, 'red'], [3, 'yellow'], [4, 'green'], [5, 'orange'], [6, 'black']]

# Split into two sections
s1 = s[0...s.length/2]
s2 = s[s.length/2..-1]

# Compile
p s1.each_with_index.map { |x, i| x + s2[i] }
#[[1, "blue", 4, "green"], [2, "red", 5, "orange"], [3, "yellow", 6, "black"]]

答案 5 :(得分:1)

数学技巧 - ))

s.group_by {|a| a[0]%((s.length)/2) }.values.map {|e| e.flatten }
# [
#   [1, "blue", 4, "green"], 
#   [2, "red", 5, "orange"], 
#   [3, "yellow", 6, "black"]
# ]