Skip to content

Instantly share code, notes, and snippets.

@tamizhgeek
Last active August 29, 2015 14:09
Show Gist options
  • Save tamizhgeek/d6244432b1035ffad928 to your computer and use it in GitHub Desktop.
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
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())
}
}
@brewkode
Copy link

Ashwanth - Nailed. Pattern matching can be deceptive. You need to be clear when to use it and when to use if-else. And, secondly help the Type checker by not giving Any :)
L#51, 54 cases can be converted to Case 0 => do_something and Case _ => do_something_else

@tamizhgeek
Copy link
Author

Incorporated the comment changes. But i have a lot of questions. Will come and bug either of you to get more clarity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment