Skip to content

Instantly share code, notes, and snippets.

@JRuumis
Created March 8, 2016 23:20
Show Gist options
  • Select an option

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

Select an option

Save JRuumis/bf16657ccc65271866d2 to your computer and use it in GitHub Desktop.
success!
object FilterElements4 /* rename this to Solution for Hackerrank */ extends App {
// helper functions
def occurringElements(occur: Int, list: List[Int]):Set[Int] = {
list.groupBy(identity).mapValues( _.size ).filter{ case(key,value) => value >= occur }.keys.toSet
}
def filterListByOccurrences(list: List[Int], occurringElements: Set[Int]): List[Int] = {
if (list == Nil || occurringElements.isEmpty) Nil
else {
val (l :: rest) = list
if ( occurringElements contains l ) l :: filterListByOccurrences( rest, occurringElements - l )
else filterListByOccurrences( rest, occurringElements )
}
}
// 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) => ( list, occurringElements(occurrences, list) ) }
.map { case (list, occurringElements) => filterListByOccurrences(list, occurringElements)}
.map { l => if (l == Nil) List(-1) else l }
.map { l => println( l.mkString(" ") ) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment