Created
March 9, 2016 05:44
-
-
Save jurisk/774ef94850c0757302d2 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
| /** https://www.hackerrank.com/challenges/filter-elements */ | |
| object Solution extends App { | |
| def filterElements(list: List[Int], times: Int, processed: Set[Int] = Set.empty): List[Int] = { | |
| if (list.isEmpty) Nil | |
| else { | |
| val elem = list.head | |
| val x = if (processed.contains(elem)) { | |
| Nil // already seen | |
| } else { | |
| if (list.count(_ == elem) >= times) List(elem) // right count | |
| else Nil // wrong count | |
| } | |
| x ::: filterElements(list.tail, times, processed + elem) | |
| } | |
| } | |
| val in = io.StdIn | |
| val testCases = in.readInt() | |
| Range(0, testCases) | |
| .map { _ => ( in.readLine().split(' ')(1).toInt, in.readLine().split(' ').map(_.toInt).toList ) } | |
| .map { case (occurrences, list) => filterElements(list, occurrences) } | |
| .map { l => if (l.isEmpty) "-1" else l.mkString(" ") } | |
| .foreach(println) | |
| } |
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
| import org.scalatest.{FlatSpec, Matchers} | |
| class SolutionSpec extends FlatSpec with Matchers { | |
| it should "pass test case 1" in { | |
| Solution.filterElements(List(4, 5, 2, 5, 4, 3, 1, 3, 4), 2) shouldEqual List(4, 5, 3) | |
| } | |
| it should "pass test case 2" in { | |
| Solution.filterElements(List(4, 5, 2, 5, 4, 3, 1, 3, 4), 4) shouldEqual Nil | |
| } | |
| it should "pass test case 3" in { | |
| Solution.filterElements(List(5, 4, 3, 2, 1, 1, 2, 3, 4, 5), 2) shouldEqual List(5, 4, 3, 2, 1) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment