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

1 2
3
1
\$\begingroup\$

Swift 5.9, 65 59 57 bytes

var s="",r={s=$0
s.map{$0
s+=[s.removeFirst()]
print(s)}}

r(_:) is the closure to call.

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

PowerShell, 51 bytes

1..$s.Length|%{$s=$s[1..$s.Length]+$s[0]-join'';$s}

Try it online!

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

Octave, 54 bytes

@(x)arrayfun(@(j)circshift(x,[0,j]),1:sum(x|1),'un',0)

Try it online!

I see basically two options here: subsetting + concatenation and using a built-in circshift to rotate a string. The built-in approach turned to be the shorter one.

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

Forth (gforth), 62 bytes

: f >r i for j 0 do dup i j + k mod + 1 type loop cr next r> ;

Try it online!

Explanation

Input is the form of a standard forth string (addr & length) on the stack. Output is printed, one permutation per line, in "reverse" (moving characters from the end). Saved several bytes by abusing the return stack, to cut out a bunch of normal stack manipulation.

Code Explanation

: f           \ start a new word definition
  >r          \ place string length on the return stack
  i for       \ start a reverse counted loop from len to 0
    j 0 do    \ start a counted loop from 0 to len
      dup     \ duplicate the string starting address
      i j +   \ add current index and offset
      k mod   \ Get the total modulo the string length to get current char index
      +       \ add the current char index to the string starting address
      1 type  \ output the current char
    loop      \ end the inner counted loop
    cr        \ output a newline
  next        \ end the outer reverse counted loo
  r>          \ remove the string length from the return stack
;             \ end word definition
\$\endgroup\$
1
\$\begingroup\$

C++, 320 bytes

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char* argv[]){std::string i=std::string(argv[1]);std::vector<std::string>r;std::cout<<i<<" -> ";for(int a=0;a<i.size();a++){std::rotate(i.begin(),i.begin()+1,i.end());r.push_back(i);}for(const auto& b:r){std::cout<<b<<" ";}}
\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in C page for ways you can golf your program! You might want to edit in a Try it online link so others can test your code, and you can save a few bytes by renaming argc and argv, and not printing the abc -> part as it's not part of the challenge. \$\endgroup\$
    – emanresu A
    Commented Jul 11 at 22:03
  • \$\begingroup\$ 140 bytes \$\endgroup\$
    – ceilingcat
    Commented Nov 9 at 17:20
1
\$\begingroup\$

min, 30 bytes

(dup(swap rest append dup)map)

Takes a list of characters and outputs a list of lists of characters.

running the code + output

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

Pyth, 11 bytes

VSlQ+>QN<QN

Try it online!

Pretty much just a port of my Python answer

Explanation

==================================================
assign('Q',eval_input())
for N in num_to_range(Psorted(Plen(Q))):
 imp_print(plus(gt(Q,N),lt(Q,N)))
==================================================

V                    # for N in 
 S                   # 1-indexed range
  lQ                 # length of evaluated input
    +                # concatanate
     >QN             # all characters after index N in Q (Q[N:])
        <QN          # and all characters before index N in Q (Q[:N])
\$\endgroup\$
0
\$\begingroup\$

Clojure, 64 bytes

(fn[w](take(count w)(rest(iterate #(str(subs % 1)(first %))w))))

Try it online!

See the pre-golfed code below for an explanation. Returns a (lazy) list of strings.

(defn cycle-word [word]
  (->> ; Take the word
       word

       ; Create an infinite list of iterations of strings where
       ;   the first character is moved to the end of the subs(tring)
       (iterate #(str (subs % 1) (first %)))

       ; Drop the first result since we don't want it to start with the original word
       (rest)

       ; Then take as many iterations from the infinite list as the word has characters
       (take (count word))))

(cycle-word "john")
=> ("ohnj" "hnjo" "njoh" "john")
\$\endgroup\$
0
\$\begingroup\$

Pyth, 7 bytes

_.e.>Qk

Accepts input as a string or as a list of characters, output is a list of the same. Try it online here.

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

Ruby, 33 bytes

->s{s.chars.map{s=s[1..-1]+s[0]}}

Try it online!

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

JavaScript, 36 bytes

Saved 3 bytes thanks to @Shaggy by using shift() instead of splice().

a=>a.map(x=>a.push(a.shift())&&a+"")

Try it online!

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

Runic Enchantments, 59 bytes

>iu0l:1-}[{ R{:0=1\
/:$ak$0l1-[{U$:/?-/
\}?*2=0:-1{]{~ /;$~

Try it online!

Can handle inputs up to 8 characters (spaces need to be escaped, however).

Essentially just a bunch of stack manipulation, with integer 0 denoting the end of the stack and the original length used as a counter held at the end.

Without using the stack-of-stacks commands [ and ] the solution is slightly larger (63 bytes) but can handle strings up to 16 characters:

>iu0l1-}l1-sRl1-s:0 \
/s:$ak$0l1-sU$:/?-1=/
\-1l}?*5=0:-1{~/;${

Try it online!

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

Reticular, 56 38 bytes

iSL:%=@qB[:%`@d]:%`*[[o]:%`1-*p$]:%`*;

Try it online!

Explanation with input "Hee"

iS                # Read input string and put its chars into an array
L:%=              # Get length of string and save it as `%`
@qB               # Reverse array and push its items to the stack
                   Stack: [H, e, e]
[:%`@d]:%`*       # Duplicates the top length(str) items in the stack
                   a total of length(str) number of times
                   Stack before: [H, e, e]
                   Stack after: [H, e, e, H, e, e, H, e, e, H, e, e]
[[o]:%`1-*p$]:%`* # Output the top length(str) items from the stack
                    with a trailing newline, and then
                    pop the next item in the stack.
                    Iterate this `%` number of times
                    Stack before: [H, e, e, H, e, e, H, e, e, H, e, e]

                    Stack after 1st iteration: [e, e, H, e, e, H, e, e]
                    Output: Hee
                    Stack after 2nd iteration: [e, H, e, e]
                    Output: Hee
                            eeH
                    Stack after 3rd iteration: []
                    Output: Hee
                            eeH
                            eHe

;                 # Exit
\$\endgroup\$
0
\$\begingroup\$

PHP, 63 bytes

for($s=$argv[1];$x++<strlen($s);)echo$s=substr($s,1).$s[0]," ";

Try it online!

Output

$php strrot.php john
ohnj hnjo njoh john

$php strrot.php heehee
eeheeh eheehe heehee eeheeh eheehe heehee
\$\endgroup\$
0
\$\begingroup\$

C# (.NET Core), 103, 79 bytes

Without LINQ.

EDIT: ASCII-only golfing -24 bytes with a better use of a for loop and substring return!

p=>{var s="";for(int j=0;j++<p.Length;s+=p+" ")p=p.Substring(1)+p[0];return s;}

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 79 \$\endgroup\$
    – ASCII-only
    Commented Jan 18, 2019 at 3:08
0
\$\begingroup\$

cQuents, 11 bytes

=A#|LA)&_lZ

Try it online!

Explanation

=A#|LA)&_lZ

=A              first term in sequence is the input
  #|LA)         add second input n: length of input
       &        output first n terms in sequence
                each term equals:
        _l                        unary rotate left of 
          Z                                            previous term

Replace _l with _r to rotate right instead of left.

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

sed 4.2.2 -r, 34 bytes

h;:
x;s/(.)(.*)/\2\1/p
x;s/.//;//b

Try it online!

honestly surprised there's not a sed answer here yet, this is something sed does well. it holds the string, and then puts the first char at the end and deletes a char from the held string until there's no more held string

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

Raku, 20 bytes

{.rotate(all 1..$_)}

Try it online!

Anonymous code block that has input/output as a list of characters. The output is a Junction object that contains all the rotated arrays. I'm not sure how legal this is, since extracting values from a Junction is not normal.

Explanation:

{                  }   # Anonymous codeblock
 .rotate(         )    # Rotate the input list
         all 1..$_     # By all of the range 1 to length of the input array
                          # all creates a junction of values
                          # And it runs the function on each value

The all can be replaced by any of any, one, [&], [|], [^].

If the Junction isn't allowed, here's an alternate solution:

Raku, 20 bytes

{{.rotate(++$)xx$_}}

Try it online!

There's probably a better way to reset the anonymous variable ++$ than by wrapping the code in another code block... There is! And it's the same size as the Junction solution somehow.

\$\endgroup\$
1 2
3

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.