-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotate.scala
26 lines (23 loc) · 907 Bytes
/
Rotate.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Created by yhf on 15/6/10.
*/
/**
* P19
* Rotate a list N places to the left.
*
* Examples:
* scala> rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
* res0: List[Symbol] = List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'a, 'b, 'c)
* scala> rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
* res1: List[Symbol] = List('j, 'k, 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i)
*/
object Rotate {
def rotate[A](n: Int, ls: List[A]): List[A] = {
if (n >= 0) ls.drop(n % ls.length) ::: ls.take(n % ls.length)
else ls.takeRight(- (n % ls.length)) ::: ls.dropRight(- (n % ls.length))
}
def main(args: Array[String]) {
assert(rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)) == List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'a, 'b, 'c))
assert(rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k)) == List('j, 'k, 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i))
}
}