File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
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 ] )
You can’t perform that action at this time.
0 commit comments