blue-sky blue-sky - 1 month ago 21
Scala Question

Sorting list according to previous order

In code below the

List
ordering of
val originalOrdering
should be re-created after removing element(s) from the
List
.

If
val random3ElementStringList
takes value
List(3, 4, 1)
then List should be re-ordered to
List(1 , 3 , 4)

The original list
val originalOrdering
with values
1,2,3,4
does not suggest the values that can be contained in the
List
. The list can contain characters other than numeric.

import scala.collection.immutable._

object sort extends App {

val originalOrdering : List[String] = List("1" , "2" , "3" , "4");

var random3ElementStringList : List[String] = util.Random.shuffle(originalOrdering).take(3)

val stringPositions : Map[String , Int] = originalOrdering.zipWithIndex.toMap

println(random3ElementStringList)

println(stringPositions);

val fl = random3ElementStringList.foldLeft("")((a , b) => (stringPositions.get(b)+","))

println(fl)

}


The output of this code is :

List(2, 3, 4)
Map(1 -> 0, 2 -> 1, 3 -> 2, 4 -> 3)
Some(3),


But
fl
should contain the sentences in sorted order where the sort is determined by the original order in
stringPositions


Update :

import scala.collection.immutable._

object sort extends App {

def reOrder(originalList : List[String] , originalListSubset : List[String]) = {

val stringPositions : Map[String , Int] = originalList.zipWithIndex.toMap
val fl : List[(String , Int)] = originalListSubset.map(m => (m , stringPositions.get(m).get))

fl.sortBy(s => s._2).map(m => m._1)
}

val originalList : List[String] = List("a" , "b" , "c" , "f");
var random3ElementStringList : List[String] = util.Random.shuffle(originalList).take(3)

println(random3ElementStringList)
println(reOrder(originalList , random3ElementStringList))

random3ElementStringList = util.Random.shuffle(originalList).take(2)

println(random3ElementStringList)
println(reOrder(originalList , random3ElementStringList))
}

Answer

You just forgot to use a in the folding function. It's the "accumulator" of the folding. You can fix it like this:

val fl = random3ElementStringList.foldLeft("") { (acc, index) =>
  acc +","+ stringPositions.get(index)
}

I changed the arguments names to make it more clear. Here's output:

List(3, 4, 2)
Map(1 -> 0, 2 -> 1, 3 -> 2, 4 -> 3)
,Some(2),Some(3),Some(1)

You can get rid of that comma in the beginning, but I would suggest you a simpler solution without foldLeft:

val fl = random3ElementStringList.map(stringPositions.get).mkString(",")

You can just map over those random indexes and get the elements, then make a string with a given separator. The output is Some(2),Some(3),Some(1).