Andre Queen Andre Queen - 19 days ago 20
Scala Question

Finding values greater than * in a map list

My current system is a mapped String,List[Int], the String being a key value, "Sk1", "Sk2" etc, and the int is a list of numbers from 0-9.

Here is my current method to find all of the lists, how do I edit this to find only all of the "Sk*"s greater than the selected "SK*". The value of the list is the last element of the tail, which I already have a function to find. It is the handleFive option menu. To clarify, I need to find the last element (already have that function) then display only stocks greater than the selected stock.

Handler for the menu options

def handleFive(): Boolean = {
mnuShowSingleDataStock(currentStockLevel)
true
}

def handleSeven(): Boolean = {
mnuShowPointsForStock(allStockLevel)
true
}


Functions that invoke and interact with the user

// Returns a single result, not a list
def mnuShowSingleDataStock(f: (String) => (String,Int)) = {
print("Stock > ")
val data = f(readLine)
println(s"${data._1}: ${data._2}")
}

//Returns a list value
def mnuShowPointsForStock(f: (String) => (String,List[Int])) = {
print("Stock > ")
val data = f(readLine)
println(s"${data._1}: ${data._2}")
}


Not sure how to edit this, currently it shows ALL of the values in the list, I only want to return values greater than the selected value

//Show last element in the list, most current
def currentStockLevel (stock: String): (String, Int) = {
(stock, mapdata.get (stock).map(findLast(_)).getOrElse(0))
}

//Unsure how to change this to only return values greater than the selected one, not everything
def currentStockLevel (stock: String): (String, List[Int]) = {
(stock, mapdata.get (stock).map(findLast(_)).getOrElse(0))
}


My current mapped list - THIS IS MAPDATA

SK1, 9, 7, 2, 0, 7, 3, 7, 9, 1, 2, 8, 1, 9, 6, 5, 3, 2, 2, 7, 2, 8, 5, 4, 5, 1, 6, 5, 2, 4, 1
SK2, 0, 7, 6, 3, 3, 3, 1, 6, 9, 2, 9, 7, 8, 7, 3, 6, 3, 5, 5, 2, 9, 7, 3, 4, 6, 3, 4, 3, 4, 1
SK4, 2, 9, 5, 7, 0, 8, 6, 6, 7, 9, 0, 1, 3, 1, 6, 0, 0, 1, 3, 8, 5, 4, 0, 9, 7, 1, 4, 5, 2, 8
SK5, 2, 6, 8, 0, 3, 5, 5, 2, 5, 9, 4, 5, 3, 5, 7, 8, 8, 2, 5, 9, 3, 8, 6, 7, 8, 7, 4, 1, 2, 3
SK6, 2, 7, 5, 9, 1, 9, 8, 4, 1, 7, 3, 7, 0, 8, 4, 5, 9, 2, 4, 4, 8, 7, 9, 2, 2, 7, 9, 1, 6, 9
SK7, 6, 9, 5, 0, 0, 0, 0, 5, 8, 3, 8, 7, 1, 9, 6, 1, 5, 3, 4, 7, 9, 5, 5, 9, 1, 4, 4, 0, 2, 0
SK8, 2, 8, 8, 3, 1, 1, 0, 8, 5, 9, 0, 3, 1, 6, 8, 7, 9, 6, 7, 7, 0, 9, 5, 2, 5, 0, 2, 1, 8, 6
SK9, 7, 1, 8, 8, 4, 4, 2, 2, 7, 4, 0, 6, 9, 5, 5, 4, 9, 1, 8, 6, 3, 4, 8, 2, 7, 9, 7, 2, 6, 6

Answer

If the key strings are things like "SK9" and "SK10" then you have to cut the digits out, convert to Int, and compare/filter them, but if your keys are kept in a completely consistent format: "SK001", "SK002" ... "SK009", "SK010" ... "SK099", "SK100", etc., then you use simple string comparisons to filter for just what you want.

mapdata.filterKeys(_ >= stock).values  // an Iterable[List[Int]]
Comments