I've seen many questions about Scala collections and could not decide. This question was the most useful until now.
I think the core of the question is twofold: 1) Which are the best collections for this use case? 2) Which are the recommended ways to use them?
Details:
I am implementing an algorithm that iterates over all elements in a collection searching for the one that matches a certain criterion. After the search, the next step is to search again with a new criterion, but without the chosen element among the possibilities. The idea is to create a sequence with all original elements ordered by the criterion (which changes at every new selection). The original sequence doesn't really need to be ordered, but there can be duplicates (the algorithm will only pick one at a time). Example with a small sequence of Ints (just to simplify):
object Foo extends App {
def f(already_selected: Seq[Int])(element: Int): Double =
// something more complex happens here,
// specially something take takes 'already_selected' into account
math.sqrt(element)
//call to the algorithm
val (result, ti) = Tempo.time(recur(Seq.fill(9900)(Random.nextInt), Seq()))
println("ti = " + ti)
//algorithm
def recur(collection: Seq[Int], already_selected: Seq[Int]): (Seq[Int], Seq[Int]) =
if (collection.isEmpty) (Seq(), already_selected)
else {
val selected = collection maxBy f(already_selected)
val rest = collection diff Seq(selected) //this part doesn't seem to be efficient
recur(rest, selected +: already_selected)
}
}
object Tempo {
def time[T](f: => T): (T, Double) = {
val s = System.currentTimeMillis
(f, (System.currentTimeMillis - s) / 1000d)
}
}