首页 > 解决方案 > 交换数组中的元素而不创建新数组

问题描述

我被要求提供一种返回 arr 的方法,如果 element == 5 被推到数组的末尾,如果它不是 5 被推到 arr 的开头,则必须在不创建新数组的情况下执行此操作,请您帮忙我通过迭代 .each 和另一个不使用 .each 来解决这个问题 使用 ruby

请红宝石

结尾

puts put_num5_last([5,3,5,2,5,1,4])

标签: arraysruby

解决方案


您可以从数组中找出五个,并将它们连接到最后。

numbs = [5, 3, 5, 2, 5, 1, 4]
fives = numbs.select { |numb| numb == 5 }
numbs.delete(5)
numbs.concat(fives)

numbs #=> [3, 2, 1, 4, 5, 5, 5]

这不是最有效的解决方案,因为两者都select遍历delete整个数组。但这是最易读的。更高效但可读性更低的是:

numbs = [5, 3, 5, 2, 5, 1, 4]

# reverse loop to prevent shifting of elements that are not yet iterated
numbs.each_index.reverse_each do |index|
  next unless numbs[index] == 5
  numbs << numbs.delete_at(index)
end

numbs #=> [3, 2, 1, 4, 5, 5, 5] 

以上仅在数组上循环一次,从数组中删除值并将其附加到末尾。


推荐阅读