Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 4, 2018 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/b364246ef61e1f0e6846383cb8797847 to your computer and use it in GitHub Desktop.
Save jianminchen/b364246ef61e1f0e6846383cb8797847 to your computer and use it in GitHub Desktop.
Decrypt message - 30 minutes - written in C programming. Great analysis of the algorithm, good name for function and variable names.
#include <stdio.h>
#include <stdlib.h>
char addUntilASCII(int a){
while(! ('a' <= a && a <= 'z')){
a += 26;
}
return (char) a;
}
void decrypt(char *word, char *out) {
// your code goes here
int currStep2 = 1;
int j=0;
for(int i=0; word[i] != '\0'; i++ ){
int diff = word[i] - currStep2;
char letter = addUntilASCII(diff);
out[j++] = letter;
currStep2 += letter;
}
out[j] = 0;
}
int main() {
char *s1 = "dnotq";
char s2[5] = {0};
decrypt(s1, s2);
printf("%s\n", s2);
return 0;
}
/*
Encryption
c = 99 r = 114 i
+ 1 _> 100 100 + 114 = 214 105
d -> 214 - x * 26 in range of [97, 97 + 26] 214 + 105 = 319
n 0
Decryption
d n o t q
c r i m e
n -> r
114 + 100 - x * 26 = 110 <------- you do not want to find 214, what you want to find 114 ,
take 110 - 100 first, and then add 26 continuously until it is bigger >= 97
114 - x * 26 = 110 - 100 = 10
114 = 10 + x * 26
110 -> 114, we know 114 in the rang eof a - z
10 + 26 * x -> 97 - 97 + 26
dec + prevStep2 - (26x) = enc
'a' <= dec <= 'z'
o->i
enc - currStep2 = -103
addUntilAscii(-103) == 105
currStep2 = sum( all the previously decoded letters) + 1
99 114 105 109
100 1+ 99 + 114 1 + 99 + 114 + 105
decrypt(word):
output = []
currStep2 = 1
for enc in word:
diff = enc = currStep2
letter = addUntilASCII(diff)
currStep2 += letter
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment