Can this be improved? Rot13 Encode & Decode

6 ビュー (過去 30 日間)
Jake Wright
Jake Wright 2019 年 10 月 17 日
編集済み: Rik 2019 年 10 月 21 日
Hello,
Im a new student studying computer science and we have recently started learning Matlab. (2-3 Weeks so still very novice!)
I was given a task of creating two scripts to both encode and decode the rot13 cypher. I believe I have completed them but just wanted to see if you guys can spot any
rookie mistakes or any improvements you would make? Thanks for any help!
Encode :
function [ciphermessage] = rot13_encode(plainmessage)
ciphermessage = plainmessage + 13;
for i=1:length(ciphermessage)
if(ciphermessage(i)>90)
ciphermessage(i) = ciphermessage(i) - 26;
end
end
ciphermessage = char(ciphermessage);
end
Decode:
function [ciphermessage] = rot13_encode(plainmessage)
ciphermessage = plainmessage - 13;
for i=1:length(ciphermessage)
if(ciphermessage(i) < 65)
ciphermessage(i) = ciphermessage(i) + 26;
end
end
ciphermessage = char(ciphermessage);
end

回答 (1 件)

Sid Singh
Sid Singh 2019 年 10 月 21 日
Hi, you should rename your decoding function, it is very misleading.
Instead of using the for loop, you can use logical indexing to make it more MATLAB like.
idx = ciphermessage>90;
ciphermessage(idx) = ciphermessage(idx) - 26;
Also your code doesn't work for lowercase ASCII. Maybe you can improve it to support this as well.

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by