Ruby - 比较数组和交换索引
Posted
技术标签:
【中文标题】Ruby - 比较数组和交换索引【英文标题】:Ruby - Compare Arrays and Swap Indexes 【发布时间】:2021-12-10 08:43:29 【问题描述】:我有字符串数组和整数数组,它们表示字符串的索引以及它们需要交换的顺序。我需要将索引 X 与以下索引交换,并对下一对数字执行相同操作。
我认为必须有一种方法可以用数字替换字符串的索引并相应地交换字符串位置。
例如:
```
Array = ["A", "B", "C", "D", "E", "F"]
SwapIndexes = [4, 2, 0, 3, 1, 5]
`#=>can also be understood as [4<to>2, 0<to>3, 1<to>5]`
```
输出应该是:
```
NewArray = ["D", "F", "E", "A", "C", "B"]
`#=>Indexes have beem swaped according to each pair of numbers in SwapIndexes`
```
【问题讨论】:
【参考方案1】:输入
Array = ["A", "B", "C", "D", "E", "F"]
SwapIndexes = [4, 2, 0, 3, 1, 5]
代码
SwapIndexes.each_slice(2) do |first, second|
Array[first], Array[second] = Array[second], Array[first]
end
p Array
输出
["D", "F", "E", "A", "C", "B"]
【讨论】:
以上是关于Ruby - 比较数组和交换索引的主要内容,如果未能解决你的问题,请参考以下文章