2013-08-28 124 views
2

該類採用類型爲[String,List [String]]的Map,並輸出[String,String]的地圖 ,其中關鍵字是List的名稱,值爲二進制信件的表示。 每個數字對應於該字母是否出現在列表中。 1 - 看起來,0 - 它沒有出現。 例如名單:將此迭代解決方案轉換爲功能解決方案

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 

下面是一個迭代的解決方案:

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 

    } 


} 

我認爲這是一個相當混亂,但其最好的我能做到。什麼是更實用的方法來實現相同的結果?

回答

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)) 
} 

這樣的數據轉換幾乎總是可以實現一些系列map電話。