Skip to content

Instantly share code, notes, and snippets.

@JRuumis
Created March 7, 2016 22:21
Show Gist options
  • Select an option

  • Save JRuumis/ef7f6ae7800b985e0a66 to your computer and use it in GitHub Desktop.

Select an option

Save JRuumis/ef7f6ae7800b985e0a66 to your computer and use it in GitHub Desktop.
/**
* 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(" ") ) }
}
@jurisk
Copy link
Copy Markdown

jurisk commented Mar 8, 2016

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.

@jurisk
Copy link
Copy Markdown

jurisk commented Mar 8, 2016

Import io.StdIn.readLine or at least io.StdIn.

@jurisk
Copy link
Copy Markdown

jurisk commented Mar 8, 2016

IMHO you can share the countElementsR(occurrences, rest.filter( _ != i)) somehow instead of copy-pasting it.

@jurisk
Copy link
Copy Markdown

jurisk commented Mar 8, 2016

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.

@jurisk
Copy link
Copy Markdown

jurisk commented Mar 8, 2016

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