I worked on a code for caesar cypher problem it should work correctly but it does not

2 views (last 30 days)
The function gives wrong outputs in some test cases.
function coded=new_caesar(ch_v,shift);
x=double(ch_v);
for jj=1:length(x)
if (x(jj)>=48) && (x(jj)<=57)
y=char(x(jj));
z=str2num(y);
x(jj)=z+shift;
else
x(jj)=x(jj)+shift;
end
end
for ii=1:length(x)
if (x(ii)>=0) && (x(ii)<=9)
x(ii)=num2str(x(ii));
elseif x(ii)<32
x(ii)=char(126);
elseif x(ii)>126
x(ii)=char(32);
end
end
coded=char(x);

Answers (1)

Tejas
Tejas on 25 Sep 2024
Edited: Tejas on 25 Sep 2024
Hello Amany,
The reason the above code produces incorrect results on certain test cases is due to the lack of wrap-around when a character's ASCII value is shifted by an integer. Here is a simple example for better understanding:
  • The digit '0' has an ASCII value of 48. When shifted by 3 positions, it becomes ASCII 51, representing digit '3', which works as expected.
  • However, when the digit '8', with an ASCII value of 56, is shifted by 3 positions, it becomes ASCII 59, which does not correspond to the digit '1'. Instead, the ASCII value should wrap-around to 49, representing digit '1'.
The wrap-around can be achieved using the 'mod' function. Refer to this documentation for more information on it:
Here are some example code snippets to wrap-around ASCII values:
  • For digits 0 to 9:
if (x(jj) >= 48) && (x(jj) <= 57)
x(jj) = mod(x(jj) - 48 + shift, 10) + 48;
end
  • For lowercase alphabets a to z:
if (x(jj) >= 97) && (x(jj) <= 122)
x(jj) = mod(x(jj) - 97 + shift, 26) + 97;
end

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!