Last active
August 29, 2015 14:09
-
-
Save tamizhgeek/d6244432b1035ffad928 to your computer and use it in GitHub Desktop.
Bootcamp week-1 list related problems. Test cases are here : https://gist.github.com/tamizhgeek/6e09fbb4d6e448bea213
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package assignments | |
object ListUtils { | |
def findLast(list : List[Int]) :Int = { | |
list match { | |
case a :: Nil => a | |
case a :: b => findLast(b) | |
} | |
} | |
def lenCustom(list: List[Int]) : Int = { | |
list match { | |
case (Nil) => 0 | |
case (a :: Nil) => 1 | |
case (a :: b) => 1 + lenCustom(b) | |
} | |
} | |
def penultimate(list: List[Int]) : Int = { | |
list match { | |
case (a :: b :: Nil) => a | |
case (a :: b) => penultimate(b) | |
} | |
} | |
def reverse(list: List[Int]) : List[Int] = { | |
def collect(list: List[Int], newList : List[Int]) : List[Int] = { | |
list match { | |
case (Nil) => newList | |
case a :: b => collect(b, a :: newList) | |
} | |
} | |
collect(list, List()) | |
} | |
def removeDuplicates(list : List[Int]) : List[Int] = { | |
list match { | |
case Nil => Nil | |
case a :: Nil => a :: Nil | |
case (a1 :: a2 :: b) => { | |
if(a1 == a2) | |
removeDuplicates(a1 :: b) | |
else | |
a1 :: removeDuplicates( a2 :: b) | |
} | |
} | |
} | |
def drop(interval : Int, list : List[Int]) : List[Int] = { | |
def collect(currentIdx : Int, newList : List[Int]) : List[Int] = { | |
if(lenCustom(list) == currentIdx) return newList | |
if(((currentIdx + 1) % interval) == 0) collect(currentIdx + 1, newList) | |
else collect(currentIdx + 1, newList :+ list.apply(currentIdx)) | |
} | |
collect(0, List()) | |
} | |
def slice(start : Int, end : Int, list : List[Int]) : List[Int] = { | |
def collect(currentIdx : Int, newList : List[Int]) : List[Int] = { | |
currentIdx match { | |
case a if(a < start) => collect(a + 1, newList) | |
case a if(a >= start && a < end) => collect(a + 1, newList :+ list.apply(a)) | |
case a => newList | |
} | |
} | |
collect(0, List()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incorporated the comment changes. But i have a lot of questions. Will come and bug either of you to get more clarity.