Last active
August 29, 2015 14:09
-
-
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
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 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) | |
} | |
} |
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
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 ofa
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.