Guest User

Untitled

a guest
Aug 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.61 KB | None | 0 0
  1. Scala: what is the most appropriate data structure for sorted subsets?
  2. val a = Vector( 9,2,6,1,7,5,2,6,9 ) // just an example
  3. val f : (Int)=>Double = (n)=>n // evaluation function
  4. val b = a.sortBy( f ).take( N ) // sort, then clip
  5.  
  6. def firstK[A](xs: Seq[A], k: Int)(implicit ord: Ordering[A]) = {
  7. val q = new scala.collection.mutable.PriorityQueue[A]()(ord.reverse)
  8. val (before, after) = xs.splitAt(k)
  9. q ++= before
  10. after.foreach(x => q += ord.max(x, q.dequeue))
  11. q.dequeueAll
  12. }
  13.  
  14. scala> firstK(Vector(9, 2, 6, 1, 7, 5, 2, 6, 9), 4)
  15. res14: scala.collection.mutable.Buffer[Int] = ArrayBuffer(6, 7, 9, 9)
Add Comment
Please, Sign In to add comment