Scrambled Words
October 8, 2019
We convert the input to a list, save capitalization, and remove it. The main loop collects the letters of a word, scrambles the letters at the end of the word, and copies everything else. When the input is exhausted, the accumulating output is reversed into its proper order, capitalization is restored, and the output is converted back to a string:
(define (scramble str) (let* ((cs (string->list str)) (upper (map char-upper-case? cs)) (cs (map char-downcase cs))) (let loop ((cs cs) (word (list)) (zs (list))) (cond ((null? cs) ; end of input (list->string (map (lambda (u? c) (if u? (char-upcase c) c)) upper (reverse zs)))) ((char-alphabetic? (car cs)) ; in a word (loop (cdr cs) (cons (car cs) word) zs)) ((pair? word) ; end of word (loop cs (list) (append (shuffle word) zs))) (else ; not in a word (loop (cdr cs) word (cons (car cs) zs)))))))
We use shuffle
from the Standard Prelude. Here are some examples:
> (scramble "Programming Praxis is fun!") "Grprnimaogm Srxpia is unf!" > (scramble "Programming Praxis is fun!") "Gnagmrroimp Rxsiap si nfu!" > (scramble "Programming Praxis is fun!") "Angmrrimgpo Ixaprs si fun!"
You can run the program at https://ideone.com/0r5Ckb.
Nice little drill. Here is my take on it using Julia 1.1.1: https://pastebin.com/WsrMBkKD. Cheers!
Favourite language again – this time a bit golfish – so I apologies in advance
Expanding this out a bit – with comments…
Just tweaked it – that was a bit too long…
Here is a solution in R7RS Scheme, emphasizing clarity over length or
efficiency. It is quite similar to @programmingpraxis’s solution, but
has no external dependencies (other than a couple of procedures from
the popular SRFIs 1 and 27).
Output:
A straightforward C++ solution, using library functions for scanning strings and shuffling – I’d originally used a FSA, but using find_if etc. is quite neat:
I probably should have included the string header there and I’m not sure why the compiler didn’t complain about missing the std:: for find_if and find_if_not.
Here’s a solution in Python.
Output:
Here’s a Haskell version.
[…] the previous exercise, we wrote a program to scramble the letters in each word of a string, retaining capitalization and […]
[…] program to scramble the letters of each word in a string. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments […]