Skip to content

Instantly share code, notes, and snippets.

@Viveron
Created September 12, 2023 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Viveron/adf2754285f64ac0d0bad8e9b367e04e to your computer and use it in GitHub Desktop.
Save Viveron/adf2754285f64ac0d0bad8e9b367e04e to your computer and use it in GitHub Desktop.
//необходимо реализовать функцию позволяющую делать сдвиг массива
//@param swift - любое целочисленное число
//@param arr - любой целочисленный массив
//func arrayShift(_ arr: [Int], swift: Int) -> [Int]
//пример 1
//arrayShift([1,2,3,4,5], shift: 1)
//result : [5,1,2,3,4]
//пример 2
//arrayShift([1,2,3,4,5], shift: 2)
//result : [4,5,1,2,3]
func arrayShift(_ input: [Int], shift: Int) -> [Int] {
guard !input.isEmpty, shift != 0 else {
return input
}
guard input.count != shift else {
return input
}
let isSuffix = shift > 0
var count = abs(shift)
if count > input.count {
count = count % input.count
}
var output = input
if isSuffix {
var suffix = output.suffix(count)
output.removeLast(count)
return suffix + output
} else {
var output = input
var prefix = output.prefix(count)
output.removeFirst(count)
return output + prefix
}
}
let r1 = arrayShift([1,2,3,4,5], shift: 1)
let r2 = arrayShift([1,2,3,4,5], shift: 2)
let r3 = arrayShift([1,2,3,4,5], shift: 11)
let r4 = arrayShift([], shift: 11)
let r5 = arrayShift([1,2,3,4,5], shift: 0)
let r6 = arrayShift([1,2,3,4,5], shift: -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment