Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Decode.cpp : This file contains the 'main' function. Program execution begins and ends there.
- #include <iostream>
- using namespace std;
- string encrypt(const string& s, int n) {
- string new_string = "";
- for (int i = 0; i < s.length(); i++)
- {
- if (s[i] == ' ')
- {
- new_string += ' ';
- continue;
- }
- int how_far_away = s[i] - 'a';
- int new_character = (how_far_away + n) % 25;
- new_string += 'a' + new_character;
- }
- return new_string;
- }
- string remove_first_word(const string& s) {
- string new_string = "";
- for (int i = 0; i < s.length(); i++)
- {
- if (s[i] == ' ')
- {
- for (int j = i + 1; j < s.length(); j++) {
- // Start one position to the right of the space
- new_string += s[j];
- }
- return new_string;
- }
- }
- return new_string; //returns empty if there is only one word in the string
- }
- string first_word(const string& s) {
- string new_string = "";
- for (int i = 0; i < s.length(); i++)
- {
- if (s[i] != ' ')
- {
- new_string += s[i];
- }
- else
- {
- return new_string;
- }
- }
- return new_string; //Returns if this is the last word in the string
- }
- bool check_word(string s, const string& key)
- {
- if (s.length() != key.length()) //First check the if the lengths of the strings even match
- {
- return false;
- }
- for (int i = 0; i < s.length(); i++) //Then check each character
- {
- if (s[i] != key[i])
- {
- return false;
- }
- }
- return true;
- }
- string decode(const string& code, const string& key)
- {
- for (int i = 0; i < 26; i++)
- {
- string decoded_string = encrypt(code, i);
- string dummy_string = decoded_string; // We need a copy string that we can remove words from
- string decoded_word = first_word(dummy_string);
- while (!check_word(decoded_word, key) && (decoded_word.length() > 0)) //Remove_first_word keeps getting rid of the first word so if it isn't the right key, it will return a null string-- so must account for that
- {
- dummy_string = remove_first_word(dummy_string);
- decoded_word = first_word(dummy_string);
- }
- if (check_word(decoded_word, key))
- {
- return decoded_string;
- }
- }
- }
- int main()
- {
- string s = "YoonA eats";
- string x = "YoonA";
- string y = remove_first_word(s);
- string z = first_word(s);
- cout << y << endl;
- cout << z << endl;
- string encoded = "ojdl jt tnbsu jg if dbo tpmwf uijt";
- cout << encoded << endl;
- string decoded = decode(encoded, "smart");
- cout << encoded << endl;
- cout << decoded << endl; // prints "nick is smart if he can solve this"
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement