Advertisement
MiroJoseph

Delete occurrences of an element if it occurs more than n t

Apr 18th, 2020
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.60 KB | None | 0 0
  1. My:
  2. import scala.collection.mutable.ListBuffer
  3.  
  4. object EnoughIsEnough {
  5.   def deleteNth(elements: List[Int], maxOccurrences: Int): List[Int] = {
  6.     var l =new ListBuffer[Int].empty:++(elements)
  7.     l.reverse.foreach(x=>{
  8.       if(l.count(y=>y==x)>maxOccurrences)
  9.         l.remove(l.lastIndexOf(x))
  10.     })
  11.     l.toList
  12.   }
  13. }
  14.  
  15. Other:
  16. object EnoughIsEnough {
  17.  
  18.   def deleteNth(elements: List[Int], max: Int): List[Int] =
  19.     elements
  20.       .foldLeft(List[Int]()) {
  21.         case (xs, x) if xs.count(_ == x) < max => x :: xs
  22.         case (xs, _)                           => xs
  23.       }.reverse
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement