按索引移动数组中的元素 [英] Shift elements in array by index
问题描述
c $ c> [2,3,4,5,1] var array = [1,2,3,4,5] $ c $我可以写一个扩展到
: Array
,所以我可以修改数组来实现这个输出:<$ c
变异func shiftRight (){
append(removeFirst())
}
方式来实现这样一个功能,可以将数组按任何索引,正数或负数进行移位。我可以用 if-else
子句的命令风格实现这个功能,但是我正在寻找的是功能实现。
<该算法很简单:
- 将数组拆分为两个索引:
- 数组到第二行的结尾
- 数组到第二行的结尾
有没有什么方法可以用函数样式实现它?
我已经完成的代码:
扩展数组{
mutating func shift(var amount:Int){
guard -count ... count〜= amount else {return}
如果金额< 0 {amount + = count}
self = Array(self [amount ..< count] + self [0 ..< amount])
}
}
您可以使用范围下标并连接结果。这会给你你正在寻找的东西,名字类似于标准库:
扩展数组{
func shiftRight(var amount:Int = 1) - > [元素] {
assert(-count ... count〜= amount,移位量越界)
如果数量< 0 {amount + = count} // this this is> = 0
return Array(self [amount ..< count] + self [0 ..< amount])
}
mutating func shiftRightInPlace(amount:Int = 1){
self = shiftRight(amount)
}
}
Array(1。 ..10).shiftRight()
// [2,3,4,5,6,7,8,9,10,1]
Array(1 ... 10).shiftRight( 7)
// [8,9,10,1,2,3,4,5,6,7]
您可以从返回
。 Array(后缀(count - amount)+前缀(amount))
而不是下标, shiftRight()
Given array of n elements, i.e.
var array = [1, 2, 3, 4, 5]
I can write an extension to the Array
so I can modify array to achieve this output: [2, 3, 4, 5, 1]
:
mutating func shiftRight() {
append(removeFirst())
}
Is there a way to implement such a function that would shift array by any index, positive or negative. I can implement this function in imperative style with if-else
clauses, but what I am looking for is functional implementation.
The algorithm is simple:
- Split array into two by the index provided
- append first array to the end of the second
Is there any way to implement it in functional style?
The code I've finished with:
extension Array {
mutating func shift(var amount: Int) {
guard -count...count ~= amount else { return }
if amount < 0 { amount += count }
self = Array(self[amount ..< count] + self[0 ..< amount])
}
}
You can use ranged subscripting and concatenate the results. This will give you what you're looking for, with names similar to the standard library:
extension Array {
func shiftRight(var amount: Int = 1) -> [Element] {
assert(-count...count ~= amount, "Shift amount out of bounds")
if amount < 0 { amount += count } // this needs to be >= 0
return Array(self[amount ..< count] + self[0 ..< amount])
}
mutating func shiftRightInPlace(amount: Int = 1) {
self = shiftRight(amount)
}
}
Array(1...10).shiftRight()
// [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
Array(1...10).shiftRight(7)
// [8, 9, 10, 1, 2, 3, 4, 5, 6, 7]
Instead of subscripting, you could also return Array(suffix(count - amount) + prefix(amount))
from shiftRight()
.
这篇关于按索引移动数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!