Created
March 7, 2016 22:21
-
-
Save JRuumis/ef7f6ae7800b985e0a66 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Created by janisrumnieks on 07/03/2016. | |
| * Hackerrank -> Functional Programming -> Recursion -> Filter Elements (10) | |
| * https://www.hackerrank.com/challenges/filter-elements | |
| */ | |
| object FilterElements /* rename this to Solution for Hackerrank */ extends App { | |
| // helper functions | |
| def countElementsR(occurrences: Int, list: List[Int]):List[Int] = list match { | |
| case i::rest => if (rest.count(_ == i) >= occurrences-1) | |
| i :: countElementsR(occurrences, rest.filter( _ != i)) | |
| else | |
| countElementsR(occurrences, rest.filter( _ != i)) | |
| case Nil => Nil | |
| } | |
| // two functions instead of a one - looks like a fail to me... | |
| def countElements (occurrences: Int, list: List[Int]): List[Int] = { | |
| val result = countElementsR(occurrences, list) | |
| if (result == Nil) List(-1) else result | |
| } | |
| // MAIN | |
| val testCases = io.StdIn.readInt() | |
| Range(0,testCases) | |
| .map { _ => ( io.StdIn.readLine().split(' ')(1).toInt , io.StdIn.readLine().split(' ').toList.map(_.toInt) ) } | |
| .map { case (occurrences, list) => countElements(occurrences, list) } | |
| .map { l => println( l.mkString(" ") ) } | |
| } | |
Import io.StdIn.readLine or at least io.StdIn.
IMHO you can share the countElementsR(occurrences, rest.filter( _ != i)) somehow instead of copy-pasting it.
If you hate the two functions, you could also move the if (result == Nil) List(-1) else result part below into the .map portion, as really it is part of output formatting.
I dislike the formatting at places, like lack of spaces around - in occurrences-1, how lines 10-13 are formatted.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could use Specs2 https://etorreborre.github.io/specs2/ or ScalaTest http://www.scalatest.org/ (and even ScalaCheck https://www.scalacheck.org/) for tests. They are all really nice.