2

This class takes a Map of type [String , List[String]] and outputs a Map of [String, String] where the key is the name of the List and the values is binary representation of the letters. Each digit corresponds to if the letter appears in the List or not. 1 - it appears, 0 - it does not appear. For example this 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 is an 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 = "";

    for (usd <- userDetails) {
      for (letter <- lettersToCheck) {
        if (usd._2.contains(letter)) {
          binaryRep += "1"
        } else {
          binaryRep += "0";
        }
      }
      mapvalues += usd._1 -> binaryRep
      binaryRep = "";
    }
    mapvalues

  }


}

I think this is a quite messy but its the best I could do. What is more functional approach to accomplish same result ?

1 Answer 1

2
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 like this can almost always be implement as some series of map calls.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.