String Rotations
February 28, 2020
The heart of our program is a function that generates all the rotations of a list; it first doubles the list, then takes successive cdr
s of the doubled list:
(define (rots xs) (let ((len (length xs))) (do ((xxs (append xs xs) (cdr xxs)) (rots (list) (cons (take len xxs) rots)) (n len (- n 1))) ((zero? n) rots))))
Given that, it is easy to find the rotations of a string:
(define (string-rotations str) (map list->string (rots (string->list str))))
Here is an example:
> (string-rotations "Praxis") ("sPraxi" "isPrax" "xisPra" "axisPr" "raxisP" "Praxis")
You can run the program at https://ideone.com/WD67A9.
The suggested solution doesn’t take into account a string that non-trivially rotates to itself.
Here’s some Python that does the right thing. Note the ‘1’ offset for the find:
Here is a simple solution using R7RS Scheme and a few well-known
procedures from SRFI 1.
Output:
Here’s a solution in C, using the handling proposed by @matthew to prevent duplicates.
Example:
Here’s a Haskell version (that allows duplicates).
Python Solutio
OUTPUT –>
hello, this program rotates strings
shello, this program rotates string
gshello, this program rotates strin
ngshello, this program rotates stri
ingshello, this program rotates str
ringshello, this program rotates st
tringshello, this program rotates s
stringshello, this program rotates
stringshello, this program rotates
s stringshello, this program rotate
es stringshello, this program rotat
tes stringshello, this program rota
ates stringshello, this program rot
tates stringshello, this program ro
otates stringshello, this program r
rotates stringshello, this program
rotates stringshello, this program
m rotates stringshello, this progra
am rotates stringshello, this progr
ram rotates stringshello, this prog
gram rotates stringshello, this pro
ogram rotates stringshello, this pr
rogram rotates stringshello, this p
program rotates stringshello, this
program rotates stringshello, this
s program rotates stringshello, thi
is program rotates stringshello, th
his program rotates stringshello, t
this program rotates stringshello,
this program rotates stringshello,
, this program rotates stringshello
o, this program rotates stringshell
lo, this program rotates stringshel
llo, this program rotates stringshe
ello, this program rotates stringsh