26
\$\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
    Dec 8, 2018 at 22:43
  • \$\begingroup\$ May we cycle in the other direction? \$\endgroup\$
    – xnor
    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
    Dec 8, 2018 at 23:28
  • 1
    \$\begingroup\$ @xnor that looks much clearer than my original post, thanks so much! \$\endgroup\$
    – SimpleGeek
    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\$ Dec 9, 2018 at 18:09

71 Answers 71

9
\$\begingroup\$

Haskell, 27 bytes

scanl(\(a:b)_->b++[a])=<<id

Try it online!

\$\endgroup\$
0
7
\$\begingroup\$

Jelly, 2 bytes

ṙJ

A monadic Link accepting a list of characters which yields a list of lists of characters

Try it online! (footer pretty prints by calling the link and joining with newline characters)

\$\endgroup\$
7
\$\begingroup\$

Python 2, 38 bytes

s=input()
for c in s:s=s[1:]+c;print s

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Python 3 is only 9 more bytes. \$\endgroup\$
    – wizzwizz4
    Dec 9, 2018 at 18:42
  • 1
    \$\begingroup\$ @wizzwizz4 Where'd you get 9? Python 3 - 39 bytes (stdin input without quotes) \$\endgroup\$ Dec 12, 2018 at 6:09
  • \$\begingroup\$ @pizzapants184 I forgot that strings were immutable; you're right; it's only 1 more byte. \$\endgroup\$
    – wizzwizz4
    Dec 12, 2018 at 6:56
7
\$\begingroup\$

JavaScript (ES6), 37 32 bytes

Returns an array of strings.

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

Try it online!

\$\endgroup\$
0
6
\$\begingroup\$

APL (Dyalog Unicode), 6 bytesSBCS

⍳∘≢⌽¨⊂

Try it online!

 the indices

 of

 the tally

⌽¨ each rotate (to the left)

 the entire string

\$\endgroup\$
5
\$\begingroup\$

Japt, 5 3 bytes

Takes input as a character array, outputs an array of character arrays

£=é

Try it here

£=é     :Implicit input of character array U
£       :Map
  é     :  Rotate U one element to the right
 =      :  Reassign to U for next iteration
\$\endgroup\$
4
\$\begingroup\$

MATL, 6 5 bytes

tf&+)

1 byte saved thanks to @luis!

Try it at MATL Online!

Explanation:

    # Implicitly grab input string
t   # Duplicate the input
f   # Create an array [1, ..., N] where N is the number of characters in the input
&+  # Add the transpose of this array to itself to create a 2D array of indices
    #
    #   +   1  2  3  4
    #       ----------
    #   1 | 2  3  4  5
    #   2 | 3  4  5  6
    #   3 | 4  5  6  7
    #   4 | 5  6  7  8
    #
)   # Use this 2D array to index into the original string using periodic indexing
    # Implicitly display the resulting character array
\$\endgroup\$
0
3
\$\begingroup\$

05AB1E, 3 bytes

ā._

Try it online!

\$\endgroup\$
0
3
\$\begingroup\$

J, 7 bytes

#\|."{]

Try it online!

Explanation:

  |."{    - rotate ( "{ is short for "0 1 - rank 0 1 ) 
      ]   - the input
#\        - lenght of the successive prefixes of the input 
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Using " like that is very clever, and requires dictionary knowledge of the language. Is there also a verb with rank 1 0? \$\endgroup\$
    – Adám
    Dec 9, 2018 at 16:24
  • \$\begingroup\$ @Adám I think it's "#:. I learnt this here from Frownyfrog \$\endgroup\$ Dec 9, 2018 at 18:34
3
\$\begingroup\$

R, 58 bytes

function(s,`[`=substring)paste0(s[n<-nchar(s):1],s[1,n-1])

Try it online!

\$\endgroup\$
3
\$\begingroup\$

brainfuck, 59 bytes

,[>,]<[>>[>]+[<]<[<]>-[[>]>[>]<+[<]<[<]>-]>[.>]>[.>]<[<].<]

Try it online!

Outputs each string separated by null bytes.

Explanation:

,[>,]    # Get input
<[       # Start loop over input
  >>[>]       # Go to end of the string
  +           # Set it to one to mark it
  [<]<[<]>    # Move to the beginning of input
  -[[>]>[>]<+[<]<[<]>-]   # Transfer the first character to the end
  >[.>]>[.>]  # Print the rotated string
  <[<].       # Print a nul byte
<]       # Repeat loop while input
\$\endgroup\$
3
\$\begingroup\$

ForWhile 23 bytes

{:0$(.0@,0@(.0@,#:)9#)}

Input: a char array followed by its length (stored on stack)

Output: prints rotations of input separated by tab (newline would need an additional character)

online interpreter

Explanation

{          \ define anonymous procedure
:0$        \ store copy of string length at address 0
(.         \ start for-loop, ignore loop-counter
0@,        \ rotate top (string length) stack elements
0@(.0@,#:) \ print string but keep it on the stack
9#         \ print tab
)          \ end outer for-loop
}          \ end procedure

Calling the procedure:

{:0$(.0@,0@(.0@,#:)9#)} \ procedure
1$                      \ store procedure at address 1
"ForWhile"              \ procedure argument
1@?                     \ call procedure

prints:

orWhileF    rWhileFo    WhileFor    hileForW    ileForWh    leForWhi    eForWhil    ForWhile
\$\endgroup\$
2
\$\begingroup\$

Attache, 13 bytes

Rotate#{1:#_}

Try it online!

Explanation

Rotate#{1:#_}
      #          fork(f, g) = ${ f[x, g[x]] }; this forks:
Rotate               rotate's the input by
       {1:#_}        each number from 1 to the length of the input

Alternatives

15 bytes: {_&Rotate!1:#_}

16 bytes: {Rotate[_,1:#_]}

16 bytes: Rotate@Rotations

16 bytes: Rotate#(1&`:@`#)

17 bytes: Rotate#{1+Iota@_}

18 bytes: Rotate#(1&`+@Iota)

19 bytes: Rotate#(Succ=>Iota)

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

Python 2, 54 48 bytes

lambda i:[i[x:]+i[:x]for x in range(1,len(i)+1)]

Try it online!

Well beaten by xnor but posted as an alternative approach anyway.

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

C# (Visual C# Interactive Compiler), 34 bytes

x=>x.Select(c=>x=x.Substring(1)+c)

Try it online!

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

Wolfram Language (Mathematica), 35 26 bytes

Partition[#,Tr[1^#],1,-1]&

Try it online!

Takes a list of characters as input.

Partition (but not its variant StringPartitionused below) has an optional fourth argument for treating its input as cyclic (and for specifying how exactly to do so), which makes this solution simpler than the string one - in addition to not having any 15-character built-in functions.

Wolfram Language (Mathematica), 44 bytes

Rest@StringPartition[#<>#,StringLength@#,1]&

Try it online!

The same, but takes a string as input.

Turns "john" into "johnjohn", then takes all the length-StringLength["john"] substrings of this string with offset 1, producing {"john","ohnj","hnjo","njoh","john"}, then drops the first of these with Rest.

\$\endgroup\$
2
  • \$\begingroup\$ Since character arrays are allowed, Rest@Partition[#~Join~#,Length@#,1]& would be 36 bytes. \$\endgroup\$ Dec 9, 2018 at 22:23
  • \$\begingroup\$ @LegionMammal978 Thanks! There's probably also a shorter approach with character arrays, though I haven't thought of anything yet. \$\endgroup\$ Dec 9, 2018 at 22:45
2
\$\begingroup\$

Ruby, 39 bytes

->s{a=s.chars.to_a;a.map{a.rotate!*''}}

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to the site! It doesn't look like your TIO link corresponds to your answer. It also seems your answer doesn't fit with our input/output requirements. You can use either a function or STDIN/STDOUT but we don't allow variable reassignment. \$\endgroup\$
    – Wheat Wizard
    Dec 11, 2018 at 5:10
  • \$\begingroup\$ Thanks Garf. Not sure how I managed to mess both of those up. Should be all good now. \$\endgroup\$ Dec 13, 2018 at 4:45
2
\$\begingroup\$

C (32-bit), 58 51 50 bytes

-1 byte for a nice round number thanks to ceilingcat

i;f(s){for(i=0;i++<printf("%s%.*s\n",s+i,i,s)-2;);}

Try it online!

Degolf

i;           // "Global" i.
f(s){   // s is pointer to string, which conveniently fits in a 32 bit integer.
    for(i=0; // Initialize i.
        // Increment i and take its complement, and add it to the
        // return value of printf(); which just happens to be strlen(s)+1.
        // ~i + strlen(s) + 1 == strlen(s) + 1 - i - 1, so the last printed
        // string is the original string.
        ~++i + printf("%s%.*s\n",s+i,i,s);
        // The printf prints two strings: first until the terminating \0,
        // the second until a \0 or until i chars have been printed. It also
        // prints a linefeed.
}
\$\endgroup\$
4
  • \$\begingroup\$ Suggest ~++i+printf("%s%.*s\n",s+i,i,s) instead of i++<printf("%s%.*s\n",s+i,i,s)-2 \$\endgroup\$
    – ceilingcat
    Jan 7, 2019 at 9:06
  • \$\begingroup\$ @ceilingcat Thanks, as always! \$\endgroup\$
    – user77406
    Jan 8, 2019 at 8:54
  • \$\begingroup\$ @ceilingcat You really should be called flooringcat. \$\endgroup\$
    – user77406
    Jan 8, 2019 at 8:54
  • \$\begingroup\$ 49 bytes \$\endgroup\$
    – c--
    Jul 4, 2023 at 20:29
2
\$\begingroup\$

JavaScript, 48 43 36 bytes

-5 bytes courtesy of @Bubbler *-7 bytes courtesy of @Shaggy

Input is a character array and output is an array of character arrays.

s=>s.map(_=>([a,...b]=s,s=[...b,a]))

Try it online!

\$\endgroup\$
7
  • 1
    \$\begingroup\$ 43 bytes. \$\endgroup\$
    – Bubbler
    Dec 10, 2018 at 1:54
  • 1
    \$\begingroup\$ 36 bytes \$\endgroup\$
    – Shaggy
    Jan 8, 2019 at 16:00
  • \$\begingroup\$ @Shaggy Is that a valid byte count and entry? Does [..."john"] not count as manipulation of the input string to an array before the function call? \$\endgroup\$ Jan 8, 2019 at 16:12
  • \$\begingroup\$ @guest271314, input is a character and output is an array of character arrays which are permitted by the challenge spec and our I/O defaults. \$\endgroup\$
    – Shaggy
    Jan 8, 2019 at 16:18
  • \$\begingroup\$ @Shaggy Updated. Can you kindly leave your above comment? Or should your comment be included at the answer to avoid confusion? Or is neither necessary? \$\endgroup\$ Jan 8, 2019 at 16:23
2
\$\begingroup\$

brainfuck, 38 bytes

,[>>,]<<<+>[[.>>]<<[<<]>-[+>.>-].<<+>]

Try it online!

Based on the idea of JoKing to use null-characters as space symbols. This code marks the current letters to print and loops until it reaches the left end.

,[>>,]<<    input string with empty cells in between
<+>         set first marker
[           main loop
  [.>>]     print remaining characters
  <<[<<]    return to start
  >-[+>.>-] print until marker (remove marker)
  .         print null
  <<+       set new marker
  >         restart loop with next character to the left
]           stop if there's no character to the left
\$\endgroup\$
2
\$\begingroup\$

Fig, \$13\log_{256}(96)\approx\$ 10.701 bytes

$#GLxWxO'+]xq

Try it online!

This is so long

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

Go, 105 bytes

func f(s[]rune)(o[][]rune){for i:=0;i<len(s);i++{o=append([][]rune{append(s[i:],s[:i]...)},o...)}
return}

Attempt This Online!

Without the requirement of the original being at the end, this saves 13 bytes:

92 bytes

func f(s[]rune)(o[][]rune){for i:=0;i<len(s);i++{o=append(o,append(s[i:],s[:i]...))}
return}

Attempt This Online!

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

Stax, 3 bytes

:(m

Run and debug it

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

Ruby -nl, 26 bytes

$_.scan(/./){puts$'+$`+$&}

Attempt This Online!

\$\endgroup\$
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\$

Thunno 2, 3 bytes

ż€Ỵ

Attempt This Online!

Explanation

ż€Ỵ  # Implicit input
ż    # Push the length range
 €   # For each number in this range:
  Ỵ  #  Rotate the input left that many times
\$\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\$
1
\$\begingroup\$

Charcoal, 10 bytes

⮌Eθ⭆θ§θ⁻μκ

Try it online! Link is to verbose version of code. Explanation:

  θ         Input string
 E         Map over characters
    θ       Input string
   ⭆        Map over characters and join
      θ     Input string
     §      Circularly indexed by
       ⁻    Difference between
        μ   Inner index
         κ  Outer index
⮌           Reversed
            Implicitly print each string on its own line

To rotate in the opposite direction, replace Minus with Plus.

\$\endgroup\$

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.