当位置超出范围时,如何从数组中选择值

How to select a value from an array when the location is out of bounds?

本文关键字:数组 选择 位置 范围      更新时间:2023-09-26

我正在尝试使用特定的方法加密一些明文。给定密钥[4,5,6,7]和明文"这是一些明文"第一个字母是T密钥中的第一个数字是4,因此T通过向前移动4而变为X(T,U,V,W,X)下一个字母是H密钥是5,因此H变为M{H,I,J,K,L,M}

当密钥到达末尾时,只需从头开始,一直加密到结束。我有一个Python的基本大纲:

#key = [4,5,12,6,7,11,8,9,1,2,3,10]
key = [4,5,6,7]
letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
plaintext = "IfyouarereadingthisthenthisplanetmayhavehopeafterallYouhavethepowerand"
plaintext = plaintext.upper()
keySpot = 0
count = 0;
keyCount = 0
letterLocation = 0
tempLetter = ""
i = 0
while(count < len(plaintext)):
    tempLetter = plaintext[count]
    for i in range(0, len(letters)):
        if(tempLetter == letters[i]):
            letterLocation = i
        i = i + 1
    if(keyCount > 4):
    keyCount = 0
letterLocation = letterLocation + key[keyCount]
keyCount = keyCount + 1
if(letterLocation > 27):
    #need some logic here so it wont go out of bounds
print letters[letterLocation]
count = count + 1

我的主要问题是,如果letterLocation在前进并超过Z时太大,该怎么办。当它到达Z时,我需要它从A开始,一直走到完成。例如,如果明文字母是Y,密钥是5,则Y将变为D{Y,Z,A,B,C,D}

我该怎么做?它可以是Java、C、C++、JavaScript或Python中任何最简单的版本。如果你能想出一个更好的方法,我会采纳的。

好吧,这很容易,只需使用模:

letterLocation = (letterLocation + key[keyCount]) % 26