28
\$\begingroup\$

The challenge here is to take a string and output all its rotations, by repeatedly moving the first character to the end, once per character in the string, ending with the original string:

john -> ohnj, hnjo, njoh, john

You may also cycle in the other direction, moving characters from the end:

john -> njoh, hnjo, ohnj, john

You should still output one rotation per letter even if the original word is reached before that:

heehee -> eeheeh, eheehe, heehee, eeheeh, eheehe, heehee

Character arrays are allowed, as long as the result works as shown above.

Shortest answer wins!

\$\endgroup\$
11
  • 7
    \$\begingroup\$ If a string like heehee returns to the original order in fewer cycles than its length, do we stop there? I expect this would make a big difference for many answers. \$\endgroup\$
    – xnor
    Commented Dec 8, 2018 at 22:43
  • 1
    \$\begingroup\$ May we cycle in the other direction? \$\endgroup\$
    – xnor
    Commented Dec 8, 2018 at 22:45
  • 2
    \$\begingroup\$ I edited the question including your clarifications, feel free to change it if it's not what you intended. \$\endgroup\$
    – xnor
    Commented Dec 8, 2018 at 23:28
  • 1
    \$\begingroup\$ @xnor that looks much clearer than my original post, thanks so much! \$\endgroup\$
    – SimpleGeek
    Commented Dec 9, 2018 at 13:38
  • 1
    \$\begingroup\$ Are we allowed to input/output character arrays? (The distinction can be important in some languages.) \$\endgroup\$ Commented Dec 9, 2018 at 18:09

78 Answers 78

2
\$\begingroup\$

Vyxal, 3 bytes

(Ǔ…

Explanation:

(   # For each char in the input
 Ǔ  # Rotate left
  … # Print without popping

Try it Online!

\$\endgroup\$
2
\$\begingroup\$

Julia 1.0, 31 bytes

!s=(r=keys(s)).|>i->(s*s)[i.+r]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Arturo, 30 bytes

$->s[0-1map s=>[rotate s<=1+]]

Try it!

\$\endgroup\$
2
\$\begingroup\$

JavaScript (Node.js), 41 bytes

Another JS answer, which doesn't beat any of the previous JS ones.
Input is an array of characters (as seen in other answers), and output is an array of strings.
Rotates the string the inverted way, as allowed by OP.

s=>[...s].map(_=>[...s]=s.pop()+s.join``)

Try it online!


Different approach that swaps each character with their corresponding one, obtained via calculation of its index (correct rotation direction, 58 bytes) :

s=>s.map((_,i)=>s.map((_,j)=>s[(i+j+1)%s.length]).join``)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Uiua SBCS, 7 bytes

⇌≡↻⇡⊃⧻¤

Try it!

If it is allowed to start with the input rather than end with it, then remove the reverse for -1 byte.

⇌≡↻⇡⊃⧻¤
    ⊃⧻¤  # fix the input and get its length
   ⇡     # range
 ≡↻      # rotate input by each number in the range
⇌        # reverse
\$\endgroup\$
2
\$\begingroup\$

Brachylog, 8 bytes

l≥ℕ₁;?↺₍

Generator solution: takes a string as input, outputs one rotation at a time when called repeatedly. Try it online!

Explanation

l≥ℕ₁;?↺₍
l          Length of input string
 ≥         Get a number less than or equal to that
  ℕ₁       which is also an integer greater than or equal to 1
    ;?     Put it in a list with the input string
      ↺₍   Rotate the latter the former number of times
\$\endgroup\$
2
\$\begingroup\$

Zsh, 35 bytes

for i ({0..$#1})<<<${1:$i}${1:0:$i}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Bash, 44 40 bytes

-4 bytes by roblogic

for((;i++<${#1};)){ echo ${1:i}${1::i}
}

Attempt This Online!

Use as body of a bash function or as a bash script. takes the string as first arg and outputs to stdout.

explanation:

for ((;i<${#1};i++)){ # ${#1} is the length of $1, so this is a for loop counting character positions
echo ${1:$i}${1::$i}  # ${1:x:y} is the substring of $1 starting at position x ending at position y.
}
\$\endgroup\$
2
  • \$\begingroup\$ 40 bytes with a few minor golfs. \$\endgroup\$
    – roblogic
    Commented Aug 28 at 14:36
  • 1
    \$\begingroup\$ @roblogic i remember trying to do that and failing, bash being as helpful as always with error messages. good job! \$\endgroup\$ Commented Aug 29 at 7:17
1
\$\begingroup\$

Red, 49 43 bytes

func[s][forall s[print move head s tail s]]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Tcl, 78 bytes

proc R t {time {puts [set t [regsub -all (.?)(.*) $t {\2\1}]]} [string le $t]}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Pushy, 4 bytes

L:{"

Try it online!

L:    \ Length of the string times do:
  {   \    Cyclically shift left once
   "  \    Print
\$\endgroup\$
1
\$\begingroup\$

V, 8 bytes

ýñx$pÙñd

Try it online!

Hexdump:

00000000: fdf1 7824 70d9 f164                      ..x$p..d
\$\endgroup\$
3
  • \$\begingroup\$ ýñx$pÙñd gives 8 by removing the need to H tio.run/##K/v///DewxsrVAoOzzy8MeX/f6/8jDwA \$\endgroup\$
    – user41805
    Commented Dec 9, 2018 at 19:43
  • \$\begingroup\$ @Cowsquack Even better: ý<M-->ñx$pÙ \$\endgroup\$
    – DJMcMayhem
    Commented Dec 9, 2018 at 20:54
  • \$\begingroup\$ Doesn't that repeat the last line? \$\endgroup\$
    – user41805
    Commented Dec 10, 2018 at 6:18
1
\$\begingroup\$

Powershell, 44 bytes

($s=$args|% t*y)|%{$h,$t=$s;-join($s=$t+$h)}

Test script:

$f = {

($s=$args|% t*y)|%{$h,$t=$s;-join($s=$t+$h)}

}

@(
    ,('john', 'ohnj', 'hnjo', 'njoh', 'john')
    ,('heehee', 'eeheeh', 'eheehe', 'heehee', 'eeheeh', 'eheehe', 'heehee')
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$result"-eq"$expected"
    $result
}

output:

True
ohnj
hnjo
njoh
john
True
eeheeh
eheehe
heehee
eeheeh
eheehe
heehee
\$\endgroup\$
1
\$\begingroup\$

Tcl, 80 91 bytes

proc P s {time {puts [set s [string ra $s 1 e][string in $s 0]]} [string le $s]}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Reassign text at each time saves some bytes proc R t {time {puts [set t [string ra $t 1 end][string in $t 0]]} [string len $t]} \$\endgroup\$
    – david
    Commented Dec 9, 2018 at 18:05
  • \$\begingroup\$ Got it down to 80 bytes, thanks to @david \$\endgroup\$
    – sergiol
    Commented Dec 10, 2018 at 10:54
1
\$\begingroup\$

Java (JDK), 85 bytes

s->{for(int i=s.length();i-->0;)System.out.println(s.substring(i)+s.substring(0,i));}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 82 bytes

	S =INPUT
T	X =X + 1
	S LEN(1) . L REM . R
	OUTPUT =S =R L LE(X,SIZE(S))	:S(T)
END

Try it online!

\$\endgroup\$
1
\$\begingroup\$

MathGolf, 5 bytes

hÅ╫o;

Try it online!

Explanation

h       length of array/string without popping
 Å      start block of length 2
  ╫     left-rotate bits in int, list/str
   o    print TOS without popping
    ;   discard TOS
\$\endgroup\$
1
\$\begingroup\$

Lua, 61 bytes

function(s)for i=1,#s do print(s:sub(i+1)..s:sub(1,i))end end

Try it online!

Split string at successive indices from one to the length of the string (one-based indexing), concatenate the pieces in the reverse order, print.

\$\endgroup\$
1
\$\begingroup\$

C (clang), 57 54 bytes

i;f(int*a){for(i=0;a[i++];printf("%S%.*S ",a+i,i,a));}

Try it online!

Takes input as a wide string.

\$\endgroup\$
2
  • \$\begingroup\$ Loop until a[i++] to save 7 bytes. \$\endgroup\$
    – user77406
    Commented Dec 12, 2018 at 6:15
  • \$\begingroup\$ Oh, no char*. You'd still save bytes, though (just make i global and f(char*a). \$\endgroup\$
    – user77406
    Commented Dec 12, 2018 at 6:26
1
\$\begingroup\$

Common Lisp, 88 bytes

(lambda(x)(loop for s from 1 to(length x)do(format t"~a~a "(subseq x s)(subseq x 0 s))))

Try it online!

\$\endgroup\$
1
\$\begingroup\$

MBASIC, 69 66 bytes

-3 bytes, thanks to Ørjan Johansen

1 INPUT S$:L=LEN(S$):FOR I=1 TO L:S$=MID$(S$+S$,2,L):PRINT S$:NEXT
\$\endgroup\$
2
  • \$\begingroup\$ I suspect you can shorten that to 1 INPUT S$:L=LEN(S$):FOR I=1 TO L:S$=MID$(S$+S$,2,L):PRINT S$:NEXT. \$\endgroup\$ Commented Jan 12, 2019 at 2:22
  • \$\begingroup\$ @Ørjan Johansen Very nice, thank you. \$\endgroup\$ Commented Jan 14, 2019 at 17:58
1
\$\begingroup\$

Pepe, 64 52 bytes

rEEEEeREEeRREeeeREEReREEEeeReReeeReeERREeeerEEEEERee

Try it online! Uses newlines for separation.

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog Unicode), 13 bytes

{(↓,↑)∘⍵¨⍳≢⍵}

Try it online!

Over twice as long as the other APL answer, but uses a different more literal tactic. Test harness stolen from that answer.

{(↓,↑)∘⍵¨⍳≢⍵}
{           } ⍝ Define function
         ⍳≢   ⍝ Indexes of
           ⍵  ⍝ The input
        ¨     ⍝ For each item in ^
 (   )        ⍝ Apply the following function:
  ↓              ⍝ Drop n elements
    ↑            ⍝ Take n elements
   ,             ⍝ Concatenate the 2 above results
      ∘⍵      ⍝ Bind the right input of the above function to the input
\$\endgroup\$
1
\$\begingroup\$

Lua, 52 bytes

s=...for i=1,#s do s=s:sub(2)..s:sub(1,1)print(s)end

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Rockstar, 79 77 bytes

Listen to S
X's 0
While S at X
Cut S
Rock roll S in S
Join S
Say S
Let X be+1

Try it (Code will need to be pasted in)

\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 32 bytes

s=>[...s].map(_=>s=s.slice(1)+_)

Try it online!

JavaScript (Node.js), 32 bytes

s=>s.map(_=>s=[...s.slice(1),_])

Try it online!

Found similarity

\$\endgroup\$
1
\$\begingroup\$

Nekomata, 3 bytes

x→Ř

Attempt This Online!

x       Enumerate; push [0, 1, ..., len(input) - 1]
 →      Increment
  Ř     Rotate right by that amount (automatically vectorized)

Unfortunately x is 0-indexed, so we have to increment it before rotating.

\$\endgroup\$
1
\$\begingroup\$

Racket - 179 bytes

#!racket
(let([s(read-line)][a string-append])(let g([r s][i(string-length s)])(display(a r(if(= i 0)""" -> ")))(if(= i 0)(void)(g(a(substring r 1)(~a(string-ref r 0)))(- i 1)))))

Try it online!


Explanation

On line one we have the required language expression. Yesterday, I learnt that #![language] is short for #lang [language], but it is discouraged in normal programs.

On line two, we define an immediately invoked function using let. The parent let receives a line of input from the user and passes it to it's child let called g. The child let acts as a recursive loop that uses the length of the parent string as an iterator. The first if check is in charge of pretty printing the rotated string. (While it would save some bytes to remove it, I like the way it looks.) The second check is used to determine whether the string should be rotated again or if the program should end.

To rotate the string, we split the string at index 1 and append the first character to the end of the string.

#lang racket

(let ([str (read-line)] [str-app string-append])
  (let loop ([rotated str] [idx (string-length str)])
    (display (str-app rotated (if (= idx 0) "" " -> ")))
    (if (= idx 0)
      (void)
      (loop (str-app (substring rotated 1)
                     (~a (string-ref rotated 0)))
            (- idx 1)))))

Output (Input: Heya!)

Heya! -> eya!H -> ya!He -> a!Hey -> !Heya -> Heya!
\$\endgroup\$
1
\$\begingroup\$

J-uby, 23 bytes

:*%[:& &:rotate,:+@|:+]

Attempt This Online!

Explanation

:* % [:& & :rotate, :+@ | :+]
                    :+@ | :+   # Range 1..(input length)
:* % [            ,         ]  # Map with...
      :& & :rotate             #   Rotate input chars
\$\endgroup\$
1
\$\begingroup\$

TI-Basic, 40 bytes

For(I,1,length(Ans)-1
sub(Ans,2,length(Ans)-1)+sub(Ans,1,1
Disp Ans
End
Ans

Takes input in Ans. Rotates to the left.

\$\endgroup\$
2
  • \$\begingroup\$ Wouldn't it be shorter to store length(Ans)-1 in a variable? \$\endgroup\$
    – MarcMush
    Commented Mar 13 at 14:36
  • 1
    \$\begingroup\$ @MarcMush It wouldn't because you would have to store the input in a string variable. \$\endgroup\$
    – Yousername
    Commented Mar 13 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.