arrays - 交换数组中的元素而不创建新数组
问题描述
我被要求提供一种返回 arr 的方法,如果 element == 5 被推到数组的末尾,如果它不是 5 被推到 arr 的开头,则必须在不创建新数组的情况下执行此操作,请您帮忙我通过迭代 .each 和另一个不使用 .each 来解决这个问题 使用 ruby
请红宝石
结尾
puts put_num5_last([5,3,5,2,5,1,4])
解决方案
您可以从数组中找出五个,并将它们连接到最后。
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]
以上仅在数组上循环一次,从数组中删除值并将其附加到末尾。
推荐阅读
- json - kotlinx JSON.stringify 忽略空值
- ios - 在 Xcode 中添加自定义云容器 id 的位置(不使用开发者帐户)
- php - 将按钮旁边的徽标移动到 Wordpress 网站的移动视图中?
- python - 当数据框中的 None 和 NaN 值时与 fillna() 混淆
- wpf - 在背景wpf中居中图像
- php - 获取指定数量的列
- maven - 通过 maven 快照部署代码
- mysql - 在一个函数中定义的全局变量不会在另一个函数中保留定义
- reactjs - React Select Createable 中的持久值
- node.js - 在 GKE 上部署 Express API 时出错