**Discussion 5** 09/22, 09/24 [(back to course webpage)](./mcs360_fall2020.html) # Problem 1 Raphael is an elementary school teacher. One fine day after school he had received an important call, and had written down a string `original` on the blackboard in a hurry. However, when he returned to his class after submitting some documents in the main office, he noticed that the mischievous Gin has erased his important string `original`, and instead replaced it with a string `scrambled`. All is not lost, though. Raphael knows Gin's obfuscation tricks like the back of his hand. He knows from prior experience that Gin does the following to any string that he fancies: he takes its first letter, writes the second letter to the left of the first, then the third to the right of the new string, and so on. For example, under Gin's wrath the string `alberio` becomes `ielabro`, and `betelguese` becomes `eegeebtlus`. Help Raphael get back his original string original from the string that Gin has left on the blackboard! Write a program that takes as console input (cin) a string scrambled and prints out the original string original to the console (cout)! ## Example run ``` Enter the scrambled string: cpsia The original string was: spica ``` ## Hints
Hint 1 Note that things are different depending on when the length of the string (let's call it `n=original.length()`) is odd or even.
Hint 2 Suppose you have a string of odd length as the original string, say `spica`. It scrambles to `cpsia`. What is `scrambled[n/2]` (the middle entry of the scrambled string) in the original string? What is `scrambled[n/2 - 1]`? `scrambled[n/2 + 1]`?
## Solution (partial)
Solution for strings having odd length ~~~~~~~~cpp #include #include int main() { std::string scrambled; std::cout << "Enter the scrambled string: "; std::cin >> scrambled; int n = scrambled.length(); std::string unscrambled; if(n%2 == 1) { unscrambled += scrambled[n/2]; int gap = 1; while(unscrambled.length() != n) { unscrambled += scrambled[n/2 - gap]; unscrambled += scrambled[n/2 + gap]; gap++; } } std::cout << "The unscrambled string: " << unscrambled; return 0; } ~~~~~~~~
The even length case is similar, and I'll leave it to you guys to complete the solution! ;)