Skip to content

Commit ce562ac

Browse files
authored
Create rotating-arrays-in-swift.swift
1 parent ea7fd89 commit ce562ac

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

source/rotating-arrays-in-swift.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Want to support my work 🤝? https://buymeacoffee.com/vandad
2+
3+
extension Array {
4+
private func timesToRotate(count: Int) -> Int? {
5+
assert(count > 0)
6+
assert(self.count > 1)
7+
let times = count % self.count
8+
return times > 0 ? times : nil
9+
}
10+
func rotatedLeft(count: Int) -> Self {
11+
guard let times = timesToRotate(count: count) else { return self }
12+
return Array(self[times...]) + Array(self[..<times])
13+
}
14+
func rotatedRight(count: Int) -> Self {
15+
guard let times = timesToRotate(count: count) else { return self }
16+
return Array(self.suffix(times)) + Array(self.prefix(self.count - times))
17+
}
18+
}
19+
20+
let arr = [1, 2, 3]
21+
22+
assert(arr.rotatedLeft(count: 1) == [2, 3, 1])
23+
assert(arr.rotatedLeft(count: 3) == [1, 2, 3])
24+
assert(arr.rotatedLeft(count: 4) == [2, 3, 1])
25+
assert(arr.rotatedLeft(count: 8) == [3, 1, 2])
26+
27+
assert(arr.rotatedRight(count: 2) == [2, 3, 1])
28+
assert(arr.rotatedRight(count: 1) == [3, 1, 2])
29+
assert(arr.rotatedRight(count: 5) == [2, 3, 1])

0 commit comments

Comments
 (0)