22
\$\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\$
  • 5
    \$\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 '18 at 22:43
  • \$\begingroup\$ May we cycle in the other direction? \$\endgroup\$ – xnor Dec 8 '18 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 '18 at 23:28
  • 1
    \$\begingroup\$ @xnor that looks much clearer than my original post, thanks so much! \$\endgroup\$ – I_P_Edwards Dec 9 '18 at 13:38
  • 1
    \$\begingroup\$ Are we allowed to input/output character arrays? (The distinction can be important in some languages.) \$\endgroup\$ – LegionMammal978 Dec 9 '18 at 18:09

47 Answers 47

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\$
8
\$\begingroup\$

Haskell, 27 bytes

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

Try it online!

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

APL (Dyalog Unicode), 6 bytesSBCS

⍳∘≢⌽¨⊂

Try it online!

 the indices

 of

 the tally

⌽¨ each rotate (to the left)

 the entire string

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

Python 2, 38 bytes

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

Try it online!

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

JavaScript (ES6), 37 32 bytes

Returns an array of strings.

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

Try it online!

\$\endgroup\$
4
\$\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\$
3
\$\begingroup\$

05AB1E, 3 bytes

ā._

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

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\$
  • \$\begingroup\$ @LuisMendo Clever! Thanks! \$\endgroup\$ – Suever Dec 12 '18 at 10:50
3
\$\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\$
  • \$\begingroup\$ Since character arrays are allowed, Rest@Partition[#~Join~#,Length@#,1]& would be 36 bytes. \$\endgroup\$ – LegionMammal978 Dec 9 '18 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\$ – Misha Lavrov Dec 9 '18 at 22:45
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\$

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
    \$\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 '18 at 16:24
  • \$\begingroup\$ @Adám I think it's "#:. I learnt this here from Frownyfrog \$\endgroup\$ – Galen Ivanov Dec 9 '18 at 18:34
2
\$\begingroup\$

R, 58 bytes

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

Try it online!

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

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\$
  • \$\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 at 9:06
  • \$\begingroup\$ @ceilingcat Thanks, as always! \$\endgroup\$ – user77406 Jan 8 at 8:54
  • \$\begingroup\$ @ceilingcat You really should be called flooringcat. \$\endgroup\$ – user77406 Jan 8 at 8:54
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\$
1
\$\begingroup\$

Red, 49 43 bytes

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

Try it online!

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

Perl 6, 32 bytes

{m:ex/^(.*)(.+)$/».&{[R~] @$_}}

Try it online!

m:ex/^(.*)(.+)$/ exhaustively matches the given regex, splitting the input string at every possible place, except that the second substring must have at least one character--that prevents the input string from showing up twice in the output. Then each of the resulting Match objects' capture groups are reduced ([]) to a single string with R~, the reversed string concatenation operator.

\$\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\$
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\$
  • \$\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 Dec 9 '18 at 18:05
  • \$\begingroup\$ Got it down to 80 bytes, thanks to @david \$\endgroup\$ – sergiol Dec 10 '18 at 10:54
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\$

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

Ruby, 39 bytes

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

Try it online!

\$\endgroup\$
  • 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\$ – Sriotchilism O'Zaic Dec 11 '18 at 5:10
  • \$\begingroup\$ Thanks Garf. Not sure how I managed to mess both of those up. Should be all good now. \$\endgroup\$ – acornellier Dec 13 '18 at 4:45
1
\$\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\$
  • 1
    \$\begingroup\$ 43 bytes. \$\endgroup\$ – Bubbler Dec 10 '18 at 1:54
  • 1
    \$\begingroup\$ 36 bytes \$\endgroup\$ – Shaggy Jan 8 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\$ – guest271314 Jan 8 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 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\$ – guest271314 Jan 8 at 16:23
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\$
  • \$\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\$ – Ørjan Johansen Jan 12 at 2:22
  • \$\begingroup\$ @Ørjan Johansen Very nice, thank you. \$\endgroup\$ – wooshinyobject Jan 14 at 17:58
1
\$\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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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