從網路課程 程式必修課!離散數學與演算法 來淺嚐一下沒機會在課堂上所學的離散數學與演算法。或許對撰寫程式的效能提昇會有些幫助。
課程相關資訊
[連結]:https://hiskio.com/courses/1196/lectures/133839
本篇範圍:Chapter 9
請注意:本系列文章為個人對應課程的消化吸收後,所整理出來的內容。換言之,並不一定會包含全部的課程內容,也有可能會添加其他資源來說明。
內容
凱薩密碼 Caesar Cipher Coding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function CaesarCipher(str, key, isEncrypt = true) { let result = '' for(let i=0; i<str.length; i++){ if (str[i] === ' ') { result += ' ' continue } let charCode = str.charCodeAt(i) - 65 let cipherIndex = isEncrypt ? (charCode + key) % 26 : (charCode - key) % 26 if(cipherIndex < 0) cipherIndex += 26; result += String.fromCharCode(cipherIndex + 65) } return result } console.log(CaesarCipher('HELLO WORLD', 3)) // KHOOR ZRUOG console.log(CaesarCipher('KHOOR ZRUOG', 3, false)) // HELLO WORLD |