added assignment 4 ex 3
This commit is contained in:
		
							
								
								
									
										64
									
								
								src/Assignment4/Ex3_Lists.sc
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										64
									
								
								src/Assignment4/Ex3_Lists.sc
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,64 @@ | ||||
| import scala.annotation.tailrec | ||||
|  | ||||
|  | ||||
| // Complexity: O(n) | ||||
| @tailrec | ||||
| def last[T](list: List[T]): T = { | ||||
|   if (list.isEmpty) throw new NoSuchElementException() | ||||
|   if (list.tail.isEmpty) list.head | ||||
|   else last(list.tail) | ||||
| } | ||||
|  | ||||
| def init[T](list: List[T]): List[T] = { | ||||
|   if (list.isEmpty) list | ||||
|   else if (list.tail.isEmpty) Nil | ||||
|   else list.head::init(list.tail) | ||||
| } | ||||
|  | ||||
| // Complexity: O(n) | ||||
| def concat[T](l1: List[T], l2: List[T]): List[T] = { | ||||
|   if (l1.isEmpty) l2 | ||||
|   else l1.head::concat(l1.tail, l2) | ||||
| } | ||||
|  | ||||
| // Complexity: O(n²) | ||||
| def reverse[T](list: List[T]): List[T] = { | ||||
|   if (list.isEmpty) Nil | ||||
|   else last(list)::reverse(init(list)) | ||||
| } | ||||
|  | ||||
| // Better -> O(n) | ||||
| /* | ||||
| def reverse[T](list: List[T], res: List[T] = Nil): List[T] = { | ||||
|   if (list.isEmpty) res | ||||
|   else reverse(list.tail, list.head::res) | ||||
| } | ||||
| */ | ||||
|  | ||||
| def take[T](list: List[T], n: Int): List[T] = { | ||||
|   if (list.isEmpty || n <= 0) Nil | ||||
|   else list.head::take(list.tail, n - 1) | ||||
| } | ||||
|  | ||||
| @tailrec | ||||
| def drop[T](list: List[T], n: Int): List[T] = { | ||||
|   if (list.isEmpty || n <= 0) list | ||||
|   else drop(list.tail, n - 1) | ||||
| } | ||||
|  | ||||
| @tailrec | ||||
| def apply[T](list: List[T], n: Int): T = { | ||||
|   if (list.isEmpty) throw new NoSuchElementException() | ||||
|   else if (n == 0) list.head | ||||
|   else apply(list.tail, n - 1) | ||||
| } | ||||
|  | ||||
|  | ||||
| assert(last(List(1,2,3)) == 3) | ||||
| assert(init(List(1,2,3)) == List(1,2)) | ||||
| assert(concat(List(1,2,3), List(4,5,6)) == List(1,2,3,4,5,6)) | ||||
| assert(reverse(List(1,2,3)) == List(3,2,1)) | ||||
| assert(take(List(1,2,3), 2) == List(1,2)) | ||||
| assert(drop(List(1,2,3), 2) == List(3)) | ||||
| assert(drop(List(1,2,3), 4) == Nil) | ||||
| assert(apply(List(1,2,3), 2) == 3) | ||||
		Reference in New Issue
	
	Block a user