scala - Transform this iterative solution to functional solution -
this class takes map of type [string , list[string]] , outputs map of [string, string] key name of list , values binary representation of letters. each digit corresponds if letter appears in list or not. 1 - appears, 0 - not appear. example list :
1 = 1,1,0,0 2 = 1,1,1,0 3 = 1,1,0,1 4 = 1,1,0,0 returns 4-->1100 1-->1100 2-->1110 3-->1101
below iterative solution :
object binaryrep { var userdetails : scala.collection.immutable.hashmap[string, list[string]] = new scala.collection.immutable.hashmap[string, list[string]] var letterstocheck = list("a" , "b" , "c" ,"d") def main(args: array[string]) { userdetails += "1" -> list("a" , "b") userdetails += "2" -> list("a" , "b" , "c") userdetails += "3" -> list("a" , "b" , "d") userdetails += "4" -> list("a" , "b") val binrep = getbinaryrepresentation getbinaryrepresentation foreach ( (t2) => println (t2._1 + "-->" + t2._2)) } def getbinaryrepresentation = { var mapvalues = new scala.collection.immutable.hashmap[string, string] var binaryrep = ""; (usd <- userdetails) { (letter <- letterstocheck) { if (usd._2.contains(letter)) { binaryrep += "1" } else { binaryrep += "0"; } } mapvalues += usd._1 -> binaryrep binaryrep = ""; } mapvalues } }
i think quite messy best do. more functional approach accomplish same result ?
import scala.collection.immutable.hashmap object binaryrep { val userdetails = hashmap("1" -> "ab", "2" -> "abc", "3" -> "abd", "4" -> "ab") val letterstocheck = "abcd" def getbinaryrepresentation = userdetails.mapvalues(string => letterstocheck.map(letter => if (string.contains(letter)) '1' else '0')) getbinaryrepresentation foreach ( (t2) => println (t2._1 + "-->" + t2._2)) }
data transformation can implement series of map
calls.
Comments
Post a Comment