caesar cyphor encryption problem .
Infos
This question is locked. Rouvrir pour modifier ou répondre.
Afficher commentaires plus anciens
Caesar's cypher is the simplest encryption algorithm. It adds a fixed value to the ASCII (unicode) value of each character of a text. In other words, it shifts the characters. Decrypting a text is simply shifting it back by the same amount, that is, it substract the same value from the characters. Write a function called caesar that accepts two arguments: the first is the character vector to be encrypted, while the second is the shift amount. The function returns the output argument coded, the encrypted text. The function needs to work with all the visible ASCII characters from space to ~. The ASCII codes of these are 32 through 126. If the shifted code goes outside of this range, it should wrap around. For example, if we shift ~ by 1, the result should be space. If we shift space by -1, the result should be ~.
for the first part of the code...this works
function coded=caesar(A,n)
char_set=char(32):char(126)
coded=char(A+n);
end
But if i want to maintain the range between 32 and 126 ....and also wrap around the same values as asked in later half of question , it doesnt work
function coded=caesar(A,n)
char_set=char(32):char(126)
while A <=char_set
coded=char(A+n);
end
end
please help me with the concerned code buiding ....( expect a simple approach , since iam a begineer)
test for these outputs
caesar('ABCD',1)
ans =
'BCDE'
caesar('xyz ~',1)
ans =
'yz{! '
caesar('xyz ~',-1)
ans =
'wxy~}' %these are correct answers to the code
16 commentaires
Mounic Kumar
le 20 Juin 2019
we will even get by using loops, but it is quite messy and challenging
function coded= caesar(A,n)
k=length(A);
b=double(A);
c(1,k)=0;
for i=1:k
if b(1,i)+n >126
m=126-b(1,i);
exc=n-m;
while exc>95
exc=exc-95;
end
c(1,i)=31+exc;
elseif b(1,i)+n<32
d=b(1,i)-32;
less=n+d;
while less<-95
less=less+95;
end
c(1,i)=127+less;
else
c(1,i)=b(1,i)+n;
end
end
coded=char(c);
try it, you will get output.....
but it is quite messy and challenging
As I explained in my answer, it's trivially done using mod or rem. You only need 1 line of code, and not a very long line at that. (a subtraction by an integer, a mod, an addition by the same integer).
Mounic Kumar
le 25 Juin 2019
I tried your 1 line of code idea, but I didn't get the correct result. So, why don't you explain a little longer...?
Guillaume
le 25 Juin 2019
Look at the examples in my answer. And above I've given you the exact steps required
As I said I don't give solution to homework problems as figuring out the solution is the whole point of the homework.
>> caesar = @(message, shift) xxxx(xxx(message x shift x yy, zz) x yy)
caesar =
function_handle with value:
@(message,shift)xxxx(xxx(messagexshiftxyy,zz)xyy)
>> caesar('~', 1)
ans =
' '
>> caesar(' ', -1)
ans =
'~'
>> caesar('The quick brown fox + 12345', 2)
ans =
'Ymj%vznhp%gwt|s%kt}%0%6789:'
I've masked the actual functions and numbers used, but as you can see a one line of code is all that is needed.
Guillaume
le 30 Juin 2019
As I've explained above and below, the whole thing can be done in just one line with mod or rem , with no loop needed. You could indeed try to implement mod or rem yourself as you've tried to do but why bother?
Your code is wrong. In most cases you forget to add n. Some cases are also covered by other more generic ones.
sadek kouz
le 17 Mar 2020
Modifié(e) : sadek kouz
le 17 Mar 2020
this is how I solved it
function coded = caesar(lettre, n)
N = n - 95 * fix(n/95);
a=double(lettre+N);
for i=1:length(a);
if a(i)>126
a(i)=a(i)-126+31;
elseif a(i)<32
a(i)=a(i)+126-31;
end
end
coded=char(a);
end
Aravind Meyappan
le 10 Avr 2020
HI Sadek
I had the exact same solution except for the 2nd line , where N is assigned a value, and i am getting error in my code for certain values. whats the significance of the 2nd line code?
thanks in advance
Walter Roberson
le 10 Avr 2020
That second line does the same computation that would be done for
N = mod(N, 95);
Aravind Meyappan
le 10 Avr 2020
but why is that necessary? the mod function?
can't we just add the input number "n" to the input string directly?
Walter Roberson
le 10 Avr 2020
What happens if the user enters n = 1234 ?
If you look through the various implementations people have posted here, you will see that some of them use a loop to keep subtracting or adding until the value is within range. The particular code you are looking at now instead uses a calculation equivalent to mod() to get the value into a range such that only a single addition or subtraction is needed to get back into range (provided, that is, that the input was ASCII and not, for example, 'ŭ' (character 365)
Saisunder Chaganty
le 27 Avr 2020
function y = caesar2(ch, key)
v = ' ' : '~';
[~, loc] = ismember(ch, v);
v2 = circshift(v, -key);
y = v2(loc);
end
Walter Roberson
le 29 Avr 2020
Interesting. But what should happen if one of the original characters was not in the range space to ~ ? For example newline characters are not in that range.
vamsi
le 20 Mai 2020
I tried this way.
function coded = caesar(cv, sh)
cv=cv+mod(sh, 95);
coded=char(cv-(cv>126).*95+(cv<32).*95);
end
SONU NIGAM
le 29 Mai 2020
function coded = caesar(char_vec,shift_amount)
char_value = char_vec+shift_amount;
for ii = 1:length(char_value)
if char_value>126
coded = char(char_value-95);
elseif char_value<32
coded = char(char_value+95);
else
coded = char(char_value);
end
end
end
I got correct output but in the assignment when i run this program it shows error...What fault i did i m unable to notice,if anyone can explain me then plz help me.
Danial Ahmad
le 28 Sep 2020
the problem is that e.g if the value of char_vec is 120 i.e x and the shift_amount is let's say 100 then char_value will be 220 and when you subtract 95 form that you dont get the desired result
Rik
le 28 Sep 2020
@Danial, which code are you talking about? Sonu already mentioned their code doesn't work.
Réponse acceptée
Plus de réponses (41)
function coded= caesar(string,shift)
value=string+shift;
for i=1:length(value)
while value(i)<32
value(i)=value(i)+95;
end
while value(i)>126
value(i)=value(i)-95;
end
end
coded=char(value);
15 commentaires
Arpit Srivastav
le 15 Mai 2020
Bro If this works I gotta say, You did it beautifully!
Kim Ngo
le 26 Mai 2020
I did something similar to this and it worked; I just used sprintf to concatenate individual chars inside the for loop
Toufik Zisan
le 22 Juin 2020
This is just the perfect code. Excellent job dear.
Raghav Jha
le 22 Juin 2020
thank you bro , i struggled for this problem and i tried many different method but none of them suceeded.
Abhishek Choudhury
le 18 Juil 2020
beautiful
Travis Ha
le 28 Juil 2020
I have a question. I did value (1:length(value)) in everything instead of i and didn't use the for loop. This ended up not working because for some reason the function completely skipped over the while loop with value(i)>126. Can someone please explain to me why it did this?
Walter Roberson
le 28 Juil 2020
Travis Ha:
In MATLAB, when you use if or while then the body of the statement is done only if all the items being tested are non-zero. For example,
if [1 5] > 3
the [1 5] > 3 becomes [false true] and when that is tested, the first element is zero (false is zero in MATLAB) and so it is not the case that all of the elements being tested are non-zero. So MATLAB would consider if [1 5] > 3 to be false and not do the statement.
The same thing happens for while
So when some of your values are > 126 but not all of them are, then MATLAB would not execute the body of the loop.
You can change this by using
while any(value(i)>126)
but be careful because it would proceed on to subtract 95 from all of the items in value(i)
Vectorizing is a good thing more often than not, but when you vectorize you need to be very careful with if and while . You should read about logical indexing
Travis Ha
le 29 Juil 2020
After editing my code, all of the tests were passed. Thanks for the help!
Santhosh Kumar
le 11 Déc 2020
why are we using + or - 95 in the code?
"The ASCII codes of these are 32 through 126"
length(32:126)
so each time you run off one end of the list of ASCII codes, to wrap around once, you need to adjust your counter by 95.
Jobin Geevarghese Thampi
le 16 Fév 2021
@Walter Roberson WHY ARE WE DOING + OR-95 WHAT IS ITS USE?
Suppose the input were
char(126)
and you were asked to shift it forward by 2 positions. What is the expected output? We read the problem requirements:
function needs to work with all the visible ASCII characters from space to ~. The ASCII codes of these are 32 through 126. If the shifted code goes outside of this range, it should wrap around
Wrap around in that forward direction means that the character after char(126) should be char(32) then char(33), then char(34) and so on. Thus if we started with ~ (char 126) and shifted forward two, we need to end up with char(33)
char(34)
which is
original = 126
shift = 2
target = 33
amount_to_go_back = original + shift - target
which also happens to be
length(32:126)
Jobin Geevarghese Thampi
le 21 Mar 2022
what does value=M+N means?
Jobin Geevarghese Thampi
le 21 Mar 2022
and for caesar('ABCD',3)
for=1:length(value) means 1:4 right?
Walter Roberson
le 21 Mar 2022
Wilver Sánchez
le 7 Fév 2020
function coded = caesar(text,amound)
n=amound - 95 * fix(amound/95);
v=double(text)+n;
v(v<32)=126-(31-v(v<32));
v(v>126)=32+(-127+v(v>126));
coded=char(v);
end
2 commentaires
Wilver Sánchez
le 7 Fév 2020
I've wrote this code it solves de problem in a different way that the ones I've seen in the previous answers, I hope it can help someone.
Raffael Leobino
le 26 Mar 2022
genius move
Pavel Radko
le 11 Août 2020
Modifié(e) : Pavel Radko
le 13 Août 2020
Thanks to a person who told about circshift function. I've been tried several hours to solve this task without that function.
So finaly I've passed all tests. And final code is much shorter and elegant as I have at today's morning ))
It has only 4 lines including the "end".
The main idea is to shift character table, but not the symbols of input.
% Write a function "caesar" that uses as input "array" - array
% of ASCII table characters, and "shift" - the value (integer) of shifting the "array" elements
% via ASCII table (from 32nd to 126th)
function coded = caesar (array,shift)
shifted_array=circshift(char(32:126),-shift);
% we shift (roll) ASCII characters from 32 to 126 on the "shift" amount
% note that we use "-shift", because we shift the character table but not
% the characters in our "array"
% as output we get all ASCII characters from 32 to 126 but shifted (rolled)
coded = shifted_array(double(array)-31)
% double(array) - gets array of numbers that correspond to ASCII character
% table
% (double(array)-31) - this outs array of numbers with caracter indices
% shifted by -31
% "-31" because we use "shifted_array" that hasnt ASCII characters from 1 to 31
% shifted_array() - uses array of numbers in parentheses as shifted table
% indices and outputs corresponding characters from it
end
8 commentaires
Rik
le 11 Août 2020
Well done, you actually try to educate future readers instead of treating this forum as a homework submission system. Have an upvote from me for your well-commented function and code.
There are only two things that would improve this function: documentation (a one-line description of the function, followed by an explanation of the input and output) and input validation.
Sayand Sathish
le 7 Oct 2020
By far the best solution on this page
THIERNO AMADOU MOUCTAR BALDE
le 29 Déc 2020
Thanks sir, that's the best code and the shortest
JPS
le 9 Jan 2021
thanks man!
Qaiser khan Bozdar
le 10 Jan 2021
Nice solution I got it.
Sai Krishna Praneeth Duggirala
le 4 Mai 2021
what is the need of using double ??
Nikhil Sharma
le 18 Juil 2021
function coded = caesar(x,y)
b= double(x)
m = mod(y, 95)
c= b+m
if c>126
c= c-95;
elseif c<32
c = c+95;
end
coded=char(c)
end
Walter Roberson
le 18 Juil 2021
That code can fail if x is a vector, which is the expected case. Consider for example
caeser( char(124:126), 1)
double(char(124:126)) would be [124, 125, 126]. Add 1 to that to get c = [125, 126, 127]. Now you test
if c>126
but c is a vector, and the [125 126] part is not greater than 126, so the if will fail because the test will produce [false,false,true] and if needs the values to be all non-zero for the test to succeed.
Guillaume
le 12 Juin 2019
>> mod(0:51, 26)
ans =
Columns 1 through 21
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Columns 22 through 42
21 22 23 24 25 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Columns 43 through 52
16 17 18 19 20 21 22 23 24 25
You can see that values 26, 27, ... go back to 0, 1, ...
Add/subtract some offsets to do the same for values in the range 32:126
5 commentaires
mayank ghugretkar
le 12 Juin 2019
Guillaume
le 12 Juin 2019
I'm sorry but I don't give solutions to homework. That would be a disservice to you as going through the process of finding the solution is how you learn to solve problems.
If you have a vector of numbers taken from the set 0:25, e.g.
v = [0 5 10 13 20];
And add 15 to each number
>> v = v + 15
v =
15 20 25 28 35
To force the result to wrap around back to your initial range (0:25), you'd use mod:
>> mod(v, 25)
ans =
15 20 0 3 10
Apply the same to your range (after shifting it so that it starts to 0 and shifting it back afterward).
Loops are not needed for this.
JPS
le 9 Jan 2021
mod is great when moving forward sir... what about a negative shift...?
mod() works for negative shifts too
S = 'xyla'
shift = 5
char('a' + mod(S - 'a' + shift,26))
char('a' + mod(S - 'a' - shift,26))
Manuel Rodríguez Flores
le 4 Août 2021
Hello, I've tried this but some of the values in my vector stop appearing or changed to another row when the output is given. I would really appreciate any advice. The code is:
function coded = caesar(v,m)
v = double(v);
v = v + m;
for r = 1:size(v,2) %I tried this to solve the characters dissapearing
v(1,r) = mod(v(1,r),95);
end
coded = char(v);
end
Zeyuan Cao
le 7 Fév 2020
I came up with an approach which uses logical indexing instead of if statement
function coded=caesar(str,n)
str1=double(str);
m=n-95*floor(n/95);
codedstr1=str1+m;
codedstr1(codedstr1>=127)=codedstr1(codedstr1>=127)-127+32;
coded=char(codedstr1);
end

1 commentaire
Dude this only half the solution you missed " message + n < 32 " condition
function coded = caesar(message , n)
msg = double(message);
m = mod(n, 95);
coded_msg = msg + m;
coded_msg(coded_msg > 126) = coded_msg(coded_msg > 126) - 127 + 32;
coded_msg(coded_msg < 32) = coded_msg(coded_msg < 32) + 127 -32;
coded =char(coded_msg);
end
function coded = caesar(message , n)
msg = double(message);
m = mod(n, 95); % this contricts the key within the range
coded_msg = msg + m;
coded_msg(coded_msg > 126) = coded_msg(coded_msg > 126) - 95;
coded_msg(coded_msg < 32) = coded_msg(coded_msg < 32) + 95;
coded =char(coded_msg);
end
4 commentaires
Capulus_love
le 12 Août 2020
thanks. i miss the sentence
m = mod(n, 95); % this contricts the key within the range
now i pass this question! :)
ANDIE MEDDAUGH
le 22 Juil 2021
Why 95?
Read the problem description:
"The function needs to work with all the visible ASCII characters from space to ~. The ASCII codes of these are 32 through 126"
Now calculate:
length(32:126)
Suleman
le 25 Fév 2023
% this contricts the key within the range
you mean constrict ?
very good solution
Cyrus David Pastelero
le 8 Juil 2020
Modifié(e) : Cyrus David Pastelero
le 8 Juil 2020
%This is my aproach to the problem.
function coded = caesar(arr, num)
size = strlength(arr);
coded = arr+num
for i = 1:size
while coded(i)> 126
coded(i) = coded(i) - 95;
end
while coded(i) < 32
coded(i) = coded(i) + 95;
end
end
coded = char(coded);
end
1 commentaire
Santhosh Kumar
le 11 Déc 2020
why are we using + or - 95 in the code ?
CCF2017 MIT
le 2 Juil 2019
Modifié(e) : CCF2017 MIT
le 2 Juil 2019
This problem is asking you to shift the character variable by a given element n
the word wrap means that if the ASCII code of your character exceeds 32 or 126 you need to circle back again .
For example
if ASCII code is 97 and n (shift variable) is 45 so your ASCII code is 142 which exceeds 126. So you need to subtract 126 from 142
142-126, and add the net result to 31.
you need'nt do all that..... use the function called circshift
so i defined a character array from 32 to 126 which is the required ascii range
ch=char(32:126)
these are the characters.
ch =
' !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
and when i use the circshift command
ch_shift_pos=circshift(ch,2)
ch_shift_pos =
'}~ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|'
ch_shift_neg=circshift(ch,-2)
ch_shift_neg=
'"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !'
Notice how the characters have shifted by 2 positions without you having to manually keep it within its range.
now if i want to find a character and its corresponding encrypted/shifted value i simply transfer the index since both ch and ch_shift are of the same size
so for example: if i want to find the encryption character of a , i first find the index of a in the 'ch' array and store it in a variable called x
x=strfind(ch,'a')
x =
66
and then i use that index to find the encryption in the shifted array
ch_shift_pos(x)
ans =
'_'
ch_shift_neg(x)
ans =
'c'
There! thats your answer. As simple as that. But i had to rack my brains for it. :P
3 commentaires
That's certainly one way of doing it, and it's not overly complicated.
Note that you don't need strfind and using strfind would force you to loop over the individual characters of the message to encrypt. Using the 2nd output of ismember would allow you to look up the position of all the message characters at once, so overall you'd need just 3 lines of code for your encryption function.
Still not as efficient as using mod but not bad.
CCF2017 MIT
le 2 Juil 2019
Modifié(e) : CCF2017 MIT
le 2 Juil 2019
i dont want to be arguing about what is efficient and what is not, and which one is complicated. what i certainly dont agree with is having an answer and not explaning properly. literally everyone in the comments section is asking for the meaning of your answer, yet you dont want to ellaborate further.
i am a beginner in matlab programming and so are many others, you must understand that not everyone has access to the best resources and not everyone has the knowledge or the skill that you have acquired . Hence you must try and be a little more specific and not take it for granted that someone knows. because it can be easy for you, and it can be complicated for others.
Guillaume
le 2 Juil 2019
I have explained how to do it in various comments here. I'm not sure how I can explain it more without giving the solution away.
In one comment, I wrote that all that is needed is: "a subtraction by an integer, a mod, an addition by the same integer" (and a conversion to char afterwards).
You have a message with a set of numbers (characters) between two values a and b. Shift that set of numbers so that it is between 0 and b-a. Add your caesar shift. This may underflow 0 or overflow b-a. Apply mod so that it wraps back between 0 and b-a. Reverse your original shift so that the numbers are once agian between a and b.
Rahul Gulia
le 22 Juil 2019
Modifié(e) : Guillaume
le 22 Juil 2019
function coded = caesar(str,n)
num1 = double(str); %Converting string to double to make the defined shifts
for i = 1 : length(num1)
if num1(i) + n > 126 % If ASCII value goes beyond 126
m = num1(i)-126+n;
p = 31+m;
num1(i) = p;
elseif num1(i)+n < 32 % If ASCII value goes below 32
m = 32 - num1(i) + n;
p = 126 - m;
num1(i) = p;
else m = num1(i) + n; % In a normal condition
num1(i) = m;
end
code(i) = num1(i);
end
coded = char(code);
I have written this code. Can anyone please expain as what is wrong in here? I know i have made a mistake. But i am not able to figure it out.
Thanks in advance.
5 commentaires
Mukti Awad
le 16 Août 2019
function coded = caesar(str,n)
num1 = double(str); %Converting string to double to make the defined shifts
for i = 1 : length(num1)
if num1(i) + n > 126 % If ASCII value goes beyond 126
m = num1(i)-126+n;
p = 31+m;
num1(i) = p;
elseif num1(i)+n < 32 % If ASCII value goes below 32
m = 32 - num1(i) + n;
p = 126 - m;
num1(i) = p;
else m = num1(i) + n; % In a normal condition
num1(i) = m;
end
code(i) = num1(i);
end
coded = char(code);
I am getting this error
Assessment: 0 of 2 Tests Passed
Submit More Info
- Assessment result: incorrectA few simple casesVariable coded has an incorrect value. caesar(' !"#$&()*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~',243) returned an incorrect value...
- Assessment result: incorrectRandom shiftsVariable coded has an incorrect value. caesar('MATLAB is fun!',105) returned an incorrect value...
Kunjkumar Thummar
le 30 Avr 2020
Can you please explain beypnd 126 case and below 32 case?
Robert Wadra
le 12 Juil 2020
Same error I am getting
Walter Roberson
le 12 Juil 2020
Suppose n = 1000 and the character vector is 'a' (which is 97 decimal). num1 would become 97. num1(1)+1000 > 126, so m = 97-126+1000 would be m=971. Then p=31+971 gives p = 1002 . This is not the desired result.
The code needs to adjust num1+n to be between 32 and 126 (inclusive)
shreyansh pitroda
le 30 Mar 2020
%% Function encode the code by shifting it by amount user as specified
function [coded]= caesar(code , shift) %% TAKES TWO VALUE CODE AND AMOUNT OF SHIFT
A = double(code);
x = 1;
z = length(A);
z = z+ 1;
shift = shift - 95*(fix(shift/95));
code(1:end) = code(1:end) + shift;
while x ~= z %%used the while loop to provide count
if code(1,x)< 32 %%if the value is below 32
A(1,x) = A(1,x) - 32;
A(1,x) = A(1,x) + shift;
A(1,x) = A(1,x) + 127;
elseif (code(1,x)>32)&&(code(1,x)<127) %% if value is between 32 and 127
A(1,x) = A(1,x) + shift;
else %% if the value is greater than 127
A(1,x) = A(1,x) - 127;
A(1,x) = A(1,x) + shift;
A(1,x) = A(1,x) + 32;
end
x= x + 1;
end
coded = char(A); %% code print
end
Washida Kami
le 31 Mar 2020
%uses the mod function
function txt = caesar(txt,key)
txt = double(txt) + key;
first = double(' ');
last = double('~');
% use mod to shift the characters - notice the + 1
% this is a common error and results in shifts
% being off by 1
txt = char(mod(txt - first,last - first + 1) + first);
end
%uses the circshift function
function y = caesar2(ch, key)
v = ' ' : '~';
[~, loc] = ismember(ch, v);
v2 = circshift(v, -key);
y = v2(loc);
end
2 commentaires
Noor Ul Zain
le 20 Août 2020
can someone please explain the mod function code, I also dont get why we add first, shouldnt we add first-1. Please please explain
Walter Roberson
le 20 Août 2020
Suppose txt == first, then txt-first is 0, and mod(0,something) is 0. Now suppose you had the first-1 that you propose, then the result would be first-1 . Clearly, though, it makes the most sense for the calculation to leave you within the first to last range, instead of before the range.
Rajat Munjal
le 13 Avr 2020
Modifié(e) : DGM
le 26 Fév 2023
function coded = caesar(ctbe,sa)
dd = double(ctbe)
if dd>=32 & dd<=126
ss =dd +sa
ss(ss<32) = rem((ss(ss<32)-32),95)+127
ss(ss>126)=rem((ss(ss>126)-126),95)+31
coded =char(ss);
end
end
2 commentaires
Rajat Munjal
le 13 Avr 2020
Can someone please help me in finding the mistake ?
Walter Roberson
le 13 Avr 2020
dd = double(ctbe)
ctbe will be a vector of char, so dd will be a vector of double.
if dd>=32 & dd<=126
dd>=32 & dd<=126 would be a logical vector. When you test a non-scalar with if or while, it is considered true if all of the items being tested are non-zero (true). If even one of the entries was not within that range then the test would be considered false as a whole... and you have no else condition so nothing would be assigned to coded
Short code with use of Logical Indexing:
function coded= caesar(string,shift)
mod_str=string+shift;
for i=1:length(mod_str)
mod_str(mod_str<32)=mod_str(mod_str<32)+95;
mod_str(mod_str>126)=mod_str(mod_str>126)-95;
end
coded=char(mod_str);
Omkar Kadam
le 9 Mai 2020
function coded = caesar(V,N)
ascii = char(32:126);
coded1 = (double(V) + N - 31);
found = false;
ii = 1;
coded2 = [];
while ~(found)
if ii < length(coded1)+1
j = coded1(ii);
ii = ii +1;
while j < 32
j = j + 126 - 31;
end
while j > length(ascii)
j = j - length(ascii);
end
coded2 = abs([coded2,j]);
else
found = true;
break;
end
end
coded = ascii(coded2); %this is 100% working code.
GAURAV RAJ
le 10 Mai 2020
help me in this . i wrote this code but i am getting error please tell me what's wrong in this
function y=caesar(a,b)
q=double(a);
for i=1:length(a)
d(i)=q(i)+b;
if d(i)>=32;
e(i)=rem(d(i),126);
else
e(i)=95+d(i);
end
if e(i)>=32 ;
y(i)=char(e(i));
elseif e(i)==0;
y(i)=char(126);
else
e(i)=e(i)+31;
y(i)=char(e(i));
end
end
end
1 commentaire
Walter Roberson
le 11 Mai 2020
Suppose b is -200 and q is double('A') = 65.
d = 65-200 -> d = -135
-135 >= 32 is false, so
e = 95 + -135 = -40
-40 >= 32 is false
-40 == 0 is false
e(i) = -40 + 31 = -9
y(i) = char(-9) which is same as char(0)
Arafat Roney
le 11 Mai 2020
function coded=caesar(c,s)
n=mod(s,95);
sc=c+n;
l=length(sc);
w=[];
for i=1:l
if sc(i)>126
p=31+(sc(i)-126);
elseif sc(i)<32
p=126-abs(sc(i)-31);
else
p=sc(i);
end
w=[w p];
end
coded=char(w);
end
Shandilya Kiran Bhatt
le 12 Mai 2020
Modifié(e) : Walter Roberson
le 12 Mai 2020
The code below is a long one but it is using a while loop and if you read it, it is an easy one and it is correct for any random shifts.
function coded = caesar(A,n)
a = double(A);
z = a + n;
for i =1: length(a)
if z(i)>126
b = z(i) - 126;
if b <=95
z(i) = 31 + b;
else
while b > 95
b = b-95;
end
z(i) = 31 + b;
end
end
if z(i) < 32
c = 32 - z(i);
if c <= 95
z(i) = 127 - c;
else
while c >95
c = c - 95;
end
z(i) = 127 -c;
end
end
end
encrypted_code = z;
coded = char(encrypted_code);
end
SAMARTH MAHESHKUMAR GEMLAWALA
le 15 Mai 2020
This code is quite lenghty, but logic that i have used is quite simple understand
function coded = caesar(A, n)
a = double(A)
ele=size(a)
for i=1:ele(1,2)
if n>=0
for j=1:n
a(i) = a(i)+1;
if a(i)>126
a(i)=32;
end
end
end
if n<0
for j=1:abs(n)
a(i) = a(i)-1;
if a(i)<32
a(i)=126;
end
end
end
end
coded = char(a);
end
Julian Veran
le 18 Mai 2020
function coded = caesar(M, n)
num = double(M); %Converts string into double
num2 = num;
N = n - 95 * fix(n/95);
for i = 1:length(num);
if num(i) + N < 32 %If ASCII value goes below 32
num2(i) = 126 - (31- num(i) - N);
elseif num(i) + N > 126 %If ASCII value goes beyond 126
num2(i) = 32 + (num(i) + N -127);
else
num2(i) = num(i) + N ; %If ASCII value goes normal
end
coded = char(num2);
end
1 commentaire
Tatiana Suaza Varela
le 19 Déc 2020
Hi! Sorry for the inconveniences, but please could you explain why we need to convert the string into double?
Julian Veran
le 18 Mai 2020
(using mod function)
function txt = caesar(txt,key)
txt = double(txt) + key;
first = double(' ');
last = double('~');
% use mod to shift the characters - notice the + 1
% this is a common error and results in shifts
% being off by 1
txt = char(mod(txt - first,last - first + 1) + first);
end
(using circ shify function)
function y = caesar2(ch, key)
v = ' ' : '~';
[~, loc] = ismember(ch, v);
v2 = circshift(v, -key);
y = v2(loc);
end
2 commentaires
Shenaz Fathima
le 15 Août 2020
I dont get the last line of ur code.. Can u explain it? (using mod function) What is the function of mod?
Rik
le 15 Août 2020
Have you read the documentation for the mod function?
doc mod
Timothy Simon Thomas
le 19 Mai 2020
%% CAESAR's SIPHER
% CAESAR(message,code): Message is the message to be encripted
% CODE represents the ASCII shift
% Wrapping always enabled
function coded = caesar(message,code)
while(code>95)
code=code-95;
end
while(code<-95)
code=code+95;
end
message=message+code; %base case
message(message>126)=char(double(message(message>126))-95) %overshoot
message(message<32)=char(double(message(message<32))+95) %undershoot
coded=char(message);
end
Taif Ahmed BIpul
le 21 Mai 2020
Modifié(e) : DGM
le 26 Fév 2023
function coded=caesar(v,n)
x=double(v)+n;
q=x(x<32);
p=x(x>126);
while q<32;
x(x<32)=x(x<32)+95;
q=x(x<32);
end
while p>126;
x(x>126)=x(x>126)-95;
p=x(x>126);
end
coded=char(x);
end
yazan ziyad
le 29 Mai 2020
Modifié(e) : DGM
le 26 Fév 2023
here you go
function [coded]=caesar(a,shift)
m=double(a)
codedd=m+shift;
for i=1:abs(shift)
codedd(codedd<32)=127-(32-codedd(codedd<32));
codedd(codedd>126)=31+(codedd(codedd>126)-126)
coded=char(codedd)
end
end
SONU NIGAM
le 29 Mai 2020
function coded = caesar(char_vec,shift_amount)
char_value = char_vec+shift_amount;
for ii = 1:length(char_value)
if char_value>126
coded = char(char_value-95);
elseif char_value<32
coded = char(char_value+95);
else
coded = char(char_value);
end
end
end
I got correct output but in the assignment when i run this program it shows error...What fault i did i m unable to notice,if anyone can explain me then plz help me.
Soroush sa
le 30 Mai 2020
Modifié(e) : DGM
le 26 Fév 2023
I'm beginner and I have written this code. Can anybody help me by expaining that what is wrong in here?
function coded = caesar(string,shift)
double_A = double(string);
position = double_A + shift;
for ii = 1:length(position)
if position > 126
new_position = position - 95;
elseif position < 32
new_position = position + 95;
else
new_position = position;
end
end
coded = char(new_position);
end
1 commentaire
Walter Roberson
le 30 Mai 2020
Consider what would happen if the shift were (say) 450 ?
Sumit Kumar Sharma
le 4 Juin 2020
function coded=caesar(a,b)
x=double(a);
k=mod(b,95);
q=[];
for j=1:length(x)
p=x(j)+k;
if p<=126 && p>=32
q=[q p];
elseif p>126
r=p-95;
q=[q r] ;
elseif p<32
s=p+95;
q=[q s];
end
end
coded=char(q);
end
Vistasp Edulji
le 22 Juin 2020
A much shorter solution is possible using logical arrays.
function coded =caesar(str, n)
coded = str + n;
while ( sum(coded >= 127) > 0 || sum(coded <= 31) >0 )
coded(coded >= 127) = 31 + (coded(coded>=127)-126);
coded(coded <= 31) = 127 - (32-coded(coded<=31));
end
coded = char(coded);
The while loop condition simply ensures that there is no overflow after each round of correction
The important thing is your output should be a string
Alankriti Mallick
le 26 Juil 2020
function coded= caesar(v,s)
v=v+s;
v(v>126)=rem(v(v>126),95);
v(v<32)=127-rem(32-v(v<32),95);
coded=char(v);
Ankit singh chauhan
le 16 Août 2020
Modifié(e) : DGM
le 26 Fév 2023
function cloud=caesar(m,n)
sum=double(m+n);
for i=1:length(sum)
if n>0
if (sum(i)<127)
cloud(i)=char(sum(i));
elseif sum(i)>126
store=sum(i)-126;
sto=mod(store,95);
if sto==0
s=126;
cloud(i)=char(s+sto);
else
s=32;
cloud(i)=char(s+sto-1);
end
end
else
if n<0
if (sum(i)>=32)
cloud(i)=char(sum(i));
else
if sum(i)<32
store=32-sum(i);
sto=mod(store,95);
cloud(i)=char(126-sto+1);
end
end
end
end
end
end
Juan Sebastián Hincapié Montes
le 21 Août 2020
Modifié(e) : Juan Sebastián Hincapié Montes
le 21 Août 2020
function [coded] = caesar(v ,sa)
secret = double(v);
code = ones(1, length(v));
for ii=1:length(secret)
if secret(ii)+sa > 126 %greater than 126
remainder=rem(sa,95);
if remainder + secret(ii)>126 %if the double plus the remainder is greater than 32
code(ii)=31+(remainder-(126-secret(ii)));
else
code(ii)=remainder+secret(ii); %if the double plus the remainder isn't greater than 32
end
elseif secret(ii)+sa < 32 %lower than 32
remainder=abs(rem(sa,95));
if secret(ii)-remainder < 32 %if the double plus the remainder is lower than 32
code(ii)=127-(remainder-(secret(ii)-32));
else
code(ii)=secret(ii)-remainder; %if the double plus the remainder isn't lower than 32
end
else
code(ii) = sa + secret(ii); %everything is normal
end
end
coded=char(code);
end
Mati Somp
le 5 Oct 2020
simple and fast
function coded = caesar(txt,nr)
char_set=char(32):char(126);
char_set3=[char_set char_set char_set];
coded = char_set3(txt+64+nr-floor(nr/95)*95);
end
4 commentaires
Rik
le 5 Oct 2020
If you want to make it actually fast you should probably use a persistent variable for char_set3.
I don't think this can be considered simple. I don't immediately see why you wrote it this way and why this works.
Mati Somp
le 6 Oct 2020
OK thanks for comment. Please point , where is the simplest (wihout readymade functions) and where fastest code. Why?
Rik
le 6 Oct 2020
I would say using mod is a considerably simpler setup. What would you consider a ready-made function?
I have not run any performance test comparing the other solutions in this thread. Have you?
Walter Roberson
le 6 Oct 2020
Addition and subtraction and division and floor and concatenation and array indexing and char and the colon operator, are all readymade functions.
Dhinesh Kumar
le 11 Oct 2020
function txt = caesar(txt,key)
txt = double(txt) + key;
first = double(' ');
last = double('~');
% use mod to shift the characters - notice the + 1
% this is a common error and results in shifts
% being off by 1
txt = char(mod(txt - first,last - first + 1) + first);
end
This also helps to solve the problem. Try it
XINYI CAI
le 15 Mar 2021
0 votes
Can someone help to explain how the ismember function work in this provided solution? Why it returns double instead of strings? Thanks in advance.
2 commentaires
v = char(32):char(126);
ch = 'hello';
[~, loc] = ismember(ch, v);
v1 = circshift(v, -7);
class(v1)
v1(loc)
ch = [65 41 83]
char(ch)
[~, loc] = ismember(ch, v);
v1 = circshift(v, -7);
v1(loc)
Looks okay to me, no matter whether you input numeric or text values.
The second output of ismember() is defined as indices, and would never be expected to be characters. For example,
v = blanks(100000);
v(end) = 'A';
[found, idx] = ismember('A', v)
It would not make sense for the second output (position) to return a character, as characters have maximum numeric equivalent of 65535.
XINYI CAI
le 15 Mar 2021
thank you! i got it
Raghav Arvind Thirumurugan
le 29 Mai 2021
Modifié(e) : Walter Roberson
le 21 Mar 2022
function coded=caesar(c,n)
x=double(c);
l=length(x);
for b=1:l
x(b)=x(b)+n;
end
for a=1:l
while x(a)<32 || x(a)>126
if x(a)<32
x(a)=x(a)+95;
else x(a)>126
x(a)=x(a)-95;
end
end
end
coded=char(x);
end
Selman Baysal
le 2 Jan 2022
I am agree with @Wilver Sánchez's solution. I highly recommend avoiding to use "for loop" (it is not the wrong way, but it sometimes increases the processing time; maybe not for this code).
% instead of using
for ii = 1:length(unicodeMessage)
if secret(ii) < 32
....
end
end
% more sophisticated way
secret(secret < 32) = ....
Then, my solution is that:
function coded = caesar(M,s)
% for other types of code, values of highest and lowest can be changed.
highest = 126; % max ASCII code
lowest = 32; % min ASCII code
codes = highest - lowest + 1; % number of codes in ASCII
n = fix(s/(codes)); % how many times the code will be wrapped
res = s - codes*n; % how much the code will be shifted (res: residual)
unicodeMessage = double(M);
secret = unicodeMessage + res;
secret(secret < 32) = 126 - (31 - secret(secret < 32));
secret(secret > 126) = 32 + (secret(secret > 126) - 127);
coded = char(secret);
end
Lokeswar Reddy
le 10 Juil 2022
Modifié(e) : DGM
le 26 Fév 2023
function out = caesar(m,n)
m = double(m)+n;
m = mod(m,95);
m(m>126) = m(m>126)-126 +31;
m(m<32) = m(m<32) -32+127;
out = char(m);
end
Muhammad
le 1 Août 2022
%Help required
function coded = caesar(X,Y)
X=char(X);
code=double(X)+Y;
if code>=126
code=code-95;
coded=fprintf('%s',code);
elseif code<=32
code=code+95;
coded=fprintf('%s',code);
else
code=double(X)+Y;
coded=fprintf('%s',code);
end
5 commentaires
Walter Roberson
le 1 Août 2022
The value returned by fprintf is the number of bytes that were generated after the formatting .
You should be using char() not fprintf()
Muhammad
le 1 Août 2022
Still not working.
caesar('MATLAB is Fun!',3) showing error
Walter Roberson
le 1 Août 2022
What is your revised code ?
Muhammad
le 1 Août 2022
function coded = caesar(X,Y)
X=char(X);
code=double(X)+Y;
if code>126
code=code-95;
coded=char('%s',code);
elseif code<32
code=code+95;
coded=char('%s',code);
else
code=double(X)+Y;
coded=char('%s',code);
end
Walter Roberson
le 1 Août 2022
Read the documentation for char()
Zia Ur Rehman
le 28 Août 2022
Hi folks,
I write this code, this is working fine with the problem.
Need further improvement if any from seniors as I'm very novice in coding and MATLAB. It took almost 90 minutes to solve.
function coded = caesar(a,b)
% removing the ';' so you can see how it works in output
c = double(a) % to convert the given char(string) into double(numeric)
d=c+b % adding the shift smount to encrypt
l= length(d) % measuring the length as we need to traverse every element to check if it lies in the limit(32:126)
for e = 1:l % applying loop to check each element if it lies in the limit
while d(e) > 126 % using while as if we use 'if' statement it will only execute once but we need execution untill the value comes in the limit
d(e) = d(e)-95 % if number is greater than 126 so wrap around by adding (126-32+1=95) we use +1 as we need next number not the same number
end
while d(e) < 32 % using while as if we use if statement it will only execute once but we need execution untill the value comes in the limit
d(e) = d(e) + 95 % if number is less than 32 so wrap around by subtracting (126-32+1=95) we use +1 as we need next number not the same number
end
end
coded=char(d) % d is now updated according to the limit
%coded = char(double(a) + b)
end
function [coded]=caesar(encrypt,shift)
coded_num=encrypt+shift;
big=coded_num(coded_num>126);
small=coded_num(coded_num<32);
coded_num(coded_num>126)=big-95*fix((big-32)/95);
coded_num(coded_num<32)=small-95*fix((small-32)/95-1);
coded=char(coded_num);
end
Muhammad Saleh
le 30 Oct 2023
function coded=caesar(v, shift)
if(shift>94)
shift=mod(shift,94);
end
if (shift<-94)
shift=-(mod(abs(shift),94));
end
%%if the string has strange input
if(max(double(v))>126 || min(double(v))<32)
fprintf("Error in the string");
coded=[];
return
end
%%if shifting does not voilate the range
if((max(double(v))+shift)<=126 && (min(double(v))+shift)>=32)
coded=char(double(v)+shift);
return
end
tempo=double(v);
for ii=1:strlength(v)
%% if shifting doesnot voilate the range
if(((tempo(1,ii)+shift)<=126) && (tempo(1,ii)+shift)>=32)
tempo(1,ii)=tempo(1,ii)+shift;
end
%% if shifting voilate the upper range
if((tempo(1,ii)+shift)>126)
tempo(1,ii)=mod(tempo(1,ii)+shift,127)+32;
end
%% if shifting voilate the lower range
if((tempo(1,ii)+shift)<32)
tempo(1,ii)=127+(mod(tempo(1,ii)+shift,32)-32);
end
end
coded=char(tempo);
end
Karel Octavianus Bachri
le 13 Avr 2024
Modifié(e) : Karel Octavianus Bachri
le 13 Avr 2024
finally solved,
function coded = caesar(mytext,shift)
tempshift=shift
%limit the shift from 0 to 95
while tempshift > 95
tempshift = tempshift - 95;
end
%limit the shift from -95 to 0
while tempshift < -95
tempshift = tempshift + 95;
end
tempcoded=zeros(1,length(mytext))
%shifting
tempcoded=mytext+tempshift
%wrapping using indexing
tempcoded(1,tempcoded>126)=tempcoded(1,tempcoded>126)-95
tempcoded(1,tempcoded<32)=tempcoded(tempcoded<32)+95
coded=char(tempcoded)
end
This question is locked.
Catégories
En savoir plus sur JSON Format dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
