1

我正在研究单字母密码,我必须通过用任何其他字母代替它来加密消息。

fun encrypt(message:String){
//Assume message as ABCD
var encrypt:String = ""

val alphabets = ('A'..'Z').toMutableList() //['A','B','C','D',....]

var shuffAlp = alphabets.shuffled() // Assume shuffled op as ['D','L','N','J',....]

var pair = alphabets.zip(shuffAlp)
println(pair)   // Assume pair as [(A, D), (B, L), (C, N), (D, J), ...] acc to shuffled op

for(m in message){
    for (p in pair){
        if(p.first == m)
            encrypt+=p.second
        }
    }
println(encrypt) //DLNJ according to given pair
}

如您所见,我使用了两个 for 循环来生成我的加密字符串。我想知道是否有一个等效的 Lambda 函数或扩展会丢弃两个循环?

4

1 回答 1

4

压缩后,使用toMap这样您就可以轻松查找加密值而无需循环。

您正在使用vars ,其中您的变量可以是常量vals,并且MutableList作为不必要的中间步骤。

// Assumes message contains only capital letters
fun encrypt (message: String): String {
    val alphabet = 'A'..'Z'
    val cipher = alphabet.zip(alphabet.shuffled()).toMap()
    return message.map { cipher[it] }.joinToString("")
}

但是,如果您想要稍后可以解密的消息,则需要单独的函数,以便您可以存储密码并重复使用它。像这样的东西:

fun createCipher(): Map<Char, Char> {
    val alphabet = 'A'..'Z'
    return alphabet.zip(alphabet.shuffled()).toMap()
}

fun encrypt(message: String, cipher: Map<Char, Char>): String {
    return message.map { cipher[it] }.joinToString("")
}

fun decrypt(encrpytedMessage: String, cipher: Map<Char, Char>): String {
    val invertedCipher = cipher.entries.associate { it.value to it.key }
    return encrpytedMessage.map { invertedCipher [it] }.joinToString("")
}
于 2020-08-09T15:46:44.210 回答