A collection of etudes, updated weekly, for the education and enjoyment of the savvy programmer
A string like abc
has three rotations: abc
, bca
, and cab
.
Your task is to write a program that computes all the rotations of 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 below.
Pages: 1 2
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