Ruby -比较数组和交换索引



我有字符串数组和整数数组,它们表示字符串的索引和它们需要交换的顺序。我需要将索引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`
```

输入

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"]

相关内容

  • 没有找到相关文章

最新更新