Using this code I'm attempting to output an Int value that corresponds to string value in List :
val l = List("a" , "b" , "b" , "a");
var counter = 0;
var isAdded = new scala.collection.mutable.ListBuffer[String]();
val map = scala.collection.mutable.HashMap.empty[String,Int]
def getId(m : String) : Int = {
if(map.isDefinedAt(m)){
map.get(m).get
}
else {
map += m -> counter
counter = counter + 1
counter
}
}
(l.map(m => getId(m))).foreach(println)
1
2
1
0
is outputted when I'm expecting 1,2,2,1 , each Int is sequential and unique in how it maps to the element in List. If List contained ("a" , "b" , "b" , "a" , "r") then 1,2,2,1,3 should be generated.
I understand this is an imperative solution attempt but I'm attempting to try an imperative solution before converting to functional.
How to generate a unique List of sequential Int values that map to the values in the List ?