Skip to content

Instantly share code, notes, and snippets.

@tamizhgeek
Last active August 29, 2015 14:09
Show Gist options
  • Save tamizhgeek/050e7c77642f1c710e81 to your computer and use it in GitHub Desktop.
Save tamizhgeek/050e7c77642f1c710e81 to your computer and use it in GitHub Desktop.
Bootcamp week 1 problems, not related to lists. Test cases are here : https://gist.github.com/tamizhgeek/60b1a4ece4ecbb79a1e7
package assignments
object MiscUtils {
def listPrimes(start : Int, end : Int) : List[Int] = {
def collect(currentIdx : Int, newList : List[Int]) : List[Int] = {
currentIdx match {
case a if(a == 2 || a == 3 || (a % 2 != 0 && a % 3 != 0)) => collect(a + 1, newList :+ a)
case a if(a >= end) => newList
case a => collect(a + 1, newList)
}
}
collect(start, List())
}
def sumOfMultiples(end : Int) : Int = {
def collect(currentIdx : Int, acc : Int) : Int = {
currentIdx match {
case a if(a % 3 == 0 || a % 5 == 0) => collect(a + 1, acc + a)
case a if (a >= end) => acc
case a => collect(a + 1, acc)
}
}
collect(0, 0)
}
}
@ashwanthkumar
Copy link

Line 8-9 - Seems like they're doing the same thing. Can we merge the 2 lines?
Line 14 - Shouldn't it be collect(start, List()) ?
General observation - Though it means the same thing, we're using currentIdx instead of a inside all pattern matching clauses. You should stick to a convention (I personally prefer the local scope variable than the global one, because for unusally large functions with pattern matching, it is very difficult to keep track where the variable is coming from) unless you're decomposing the input parameter and you want the original value. Eg.

    list match {
      case a :: Nil => a
      case a :: b => doSomethingWithOriginal(list) // since list is decomposed to a, b
    }

@tamizhgeek
Copy link
Author

Line 8-9 - Combined to a single step

Line 14 - Yeah. My bad. Changed it now.

General Observation - Agreed. Using local variables makes more sense.

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