title: Rotate ASCII Art by 45 Degrees

text:
# Question
Title: Rotate ASCII Art by 45 Degrees
Your task is to take an ASCII art image and output it rotated clockwise by 45 degrees and scaled by a factor of \\$\sqrt 2\\$. The scaling comes from using a lattice pattern which introduces space between the characters.

To explain it visually, a \\$3 \times 3\\$ block would be processed like so:

```
123
456
789

```

becomes

```
  1
 4 2
7 5 3
 8 6
  9

```

Characters will not be transformed, so boxes will look strange after rotation:

```
+-+
| |
+-+

```

becomes

```
  +
 | -
+   +
 - |
  +

```

To explain the process more explicitly, the output consists of a diamond lattice pattern where the top row corresponds to the top-left character of the input, the next row corresponds with the right and below neighbors, next row is those neighbors, and so forth until all of the characters have been placed on the lattice.

## Examples

```
           FISHKISSFISHKIS
       SFISHKISSFISHKISSFISH            F
    ISHK   ISSFISHKISSFISHKISS         FI
  SHKISS   FISHKISSFISHKISSFISS       FIS
HKISSFISHKISSFISHKISSFISHKISSFISH    KISS
  FISHKISSFISHKISSFISHKISSFISHKISS  FISHK
      SSFISHKISSFISHKISSFISHKISSFISHKISSF
  ISHKISSFISHKISSFISHKISSFISHKISSF  ISHKI
SSFISHKISSFISHKISSFISHKISSFISHKIS    SFIS
  HKISSFISHKISSFISHKISSFISHKISS       FIS
    HKISSFISHKISSFISHKISSFISHK         IS
       SFISHKISSFISHKISSFISH            K
         ISSFISHKISSFISHK

```

Source

Becomes

```
     H
      K S
       I H I
      F S K S
 S     I S I H S
  S I   S F S K F
   F S   H I S   I
  H I H   K S     S F
   K S K S I H     H I
    I H I S S K   I K S
   H S K S F S I F S I H
    K S I S I F S I S S K
     I F S F S I S S F S I
      S I S I H S F H I F S
     S S S F S K H I K S I S
      F F H I H I K S I H S F
       I I K S K S I H S K H I
      I S S I H I S S K S I K S
       S H H S K S F S I F S I H
        S K K S I S I F S I S S K
         F I I F S F S I S S F S I
          I S S I S I H S F H I F S
           S S S S F S K H I K S I
            H F F H I H I K S I H S
             K I I K S K S I H S K H
              I S S I H I S S K S I
               S H H S K S F S I F S
                S K K S I S I F S I S
                 F I I F S F S I S S
                  I S S I S I H S F S
                   S S S S F S K H I
                    H F F H I H I K S
                     K I I K S K S I H
                        S S I H I S S
                         H H S K S F S
                            K S I S I
                                 S F S
                                      H F K F F F
                                       K I I I I
                                      I I S S S
                                       S S H S
                                      S H S K
                                       F K F
                                      F I I
                                       I S
                                      I S
                                       S
                                      K

```

---

```
      _,,ddF"""Ybb,,_
    ,d@#@#@#@g,   `"Yb,
  ,d#@#V``V@#@#b      "b,
 d@#@#I    I@#@8        "b
d@#@#@#A..A@#@#P         `b
8#@#@#@#@#@#@8"           8
8@#@#@#@#@#@J             8
8#@#@#@#@#P               8
Y@#@#@#@#P    ,db,       ,P
 Y@#@#@#@)    @DWB      aP
  "Y#@#@#b    `69'    aP"
    "Y@#@#g,,     _,dP"
      `""YBBgggddP""'

```

Source

Becomes

```
     d d ,
    8 @ @ d ,
   8 # # # # d _
  8 @ @ @ @ @ @ ,
 Y # # # # # # # ,
  @ @ @ @ @ I V @ d
 Y # # # # #   ` # d
  @ @ @ @ @ A   ` @ F
 " # # # # # .   V # "
  Y @ @ @ @ @ .   @ @ "
   # # # # # # A I # g "
  " @ @ @ @ @ @ @ @ @ , Y
   Y # # # # # # # # #   b
    @ @ @ P P @ @ @ @ b   b
   ` # # )     J 8 # 8     ,
    " @ b         " P     ` ,
     " #                   " _
      Y g                   Y
       B ,     ,             b
        B ,   @ d             ,
         g   ` D b           "
          g   6 W ,           b
           g   9 B             ,
            d   '             "
             d                 b
              P _             `
               " ,             b
                " d           8
                 ' P a       8
                    " P a , 8
                       " P P

```

---

```
                             ...,?77??!~~~~!???77?<~....
                        ..?7`                           `7!..
                    .,=`          ..~7^`   I                  ?1.
       ........  ..^            ?`  ..?7!1 .               ...??7
      .        .7`        .,777.. .I.    . .!          .,7!
      ..     .?         .^      .l   ?i. . .`       .,^
       b    .!        .= .?7???7~.     .>r .      .=
       .,.?4         , .^         1        `     4...
        J   ^         ,            5       `         ?<.
       .%.7;         .`     .,     .;                   .=.
       .+^ .,       .%      MML     F       .,             ?,
        P   ,,      J      .MMN     F        6               4.
        l    d,    ,       .MMM!   .t        ..               ,,
        ,    JMa..`         MMM`   .         .!                .;
         r   .M#            .M#   .%  .      .~                 .,
       dMMMNJ..!                 .P7!  .>    .         .         ,,
       .WMMMMMm  ?^..       ..,?! ..    ..   ,  Z7`        `?^..  ,,
          ?THB3       ?77?!        .Yr  .   .!   ?,              ?^C
            ?,                   .,^.` .%  .^      5.
              7,          .....?7     .^  ,`        ?.
                `<.                 .= .`'           1
                ....dn... ... ...,7..J=!7,           .,
             ..=     G.,7  ..,o..  .?    J.           F
           .J.  .^ ,,,t  ,^        ?^.  .^  `?~.      F
          r %J. $    5r J             ,r.1      .=.  .%
          r .77=?4.    ``,     l ., 1  .. <.       4.,
          .$..    .X..   .n..  ., J. r .`  J.       `'
        .?`  .5        `` .%   .% .' L.'    t
        ,. ..1JL          .,   J .$.?`      .
                1.          .=` ` .J7??7<.. .;
                 JS..    ..^      L        7.:
                   `> ..       J.  4.
                    +   r `t   r ~=..G.
                    =   $  ,.  J
                    2   r   t  .;
              .,7!  r   t`7~..  j..
              j   7~L...$=.?7r   r ;?1.
               8.      .=    j ..,^   ..
              r        G              .
            .,7,        j,           .>=.
         .J??,  `T....... %             ..
      ..^     <.  ~.    ,.             .D
    .?`        1   L     .7.........?Ti..l
   ,`           L  .    .%    .`!       `j,
 .^             .  ..   .`   .^  .?7!?7+. 1
.`              .  .`..`7.  .^  ,`      .i.;
.7<..........~<<3?7!`    4. r  `          G%
                          J.` .!           %
                            JiJ           .`
                              .1.         J
                                 ?1.     .'
                                     7<..%

```

Source

Becomes

```
                                                      . .
                                                     .   .
                                                      .   .
                                                     b     .
                                                    .       .
                                                     ,       .
                                                  . J .       .
                                                 . %   ?       .
                                                  + .   4 . .
                                                 P ^ 7     ! ? .
                                                l     ; ^       7 .
                                               ,     .           ` .
                                            d         ,             ^ .
                                           . M r     ,                 ,
                                            W M       ,                 =
                                             M M     d                   ` .
                                              M N   J ,                     .
                                             ? M J . M                       ?
                                              T M . M a           , .         7
                                               H M . # .             = .       ` .
                                              ? B m !   .     . . , .   ^ .       .
                                               , 3       ` , J % `   ^ .   ,       .
                                                                        ?   7       ,
                                               7     ?                   7   7       ?
                                      r .       ,     ^                   ?   7       7
                                 .   r   J .           .                   ?   . ?     7
                                , ? .   % . .   `       .                   ?   . ` .   ?
                                 . ` $ . J   = . <                     .     7 .     .   ?
                                      . 7 .     . .                 . M ,     ~ l .   ~   !
                                   .   . 7   .   .       ?         . M M       .   I . 7   ~
                                    . .   = $ ^   .       7         M M L           . . ^   ~
                                     1 5   ?       d       7       M M N       1       ? `   ~
                                      J     4   ,   n       ?     . M M             ?   7     ~
                                       L     .   , G .       !     M M !       5     i   !     !
                                            .     , . .         .   # `       .       .   1     ?
       . .                             1     X   5 t , .   .     .             ;     .   .   I   ?
      . ` ^ , .                         .     .   r   7     .     ,           F       > .   .     ?
       7     ` ? .                     J       .         .   .     ?       . F         r   .       7
        <       ` .                     S         ` J ,   .   .     ! . . . t             . !       7
         .         ^ .         .         .         `   ^ . .   .       P %               . `         ?
          .           J       j ,       ` .     `   ,     .     ?     . 7               `             <
           .           ? .       7       >       ` .       , .   7 .   . !             `               ~
            .           ? , r 8   !     +           n       o .     , .     .                           .
             .           , 7   .       =   .       . .       . .     ^ Y                                 .
              .             ,     7   2     .     . % .       . ,     . r   .         .                   .
               .         <         ~ r         .   ,             7     `     >         ,                   .
                .         . `       L       r   .         l       . .       .         6       4 .
                 .       1   T       .     $     ^ .     .       . . = . . . .       .         . = .       `
                  .           .       .   r   `     =   . , .   ? ? J   ^ %         . .         .   ,       7
                   ~     L   ~ .       . t     t     ` J %   ,   ^   = .           . !           .   ^ .     !
                    <   .     . .     . $ `   ,             J     .   ! `         . ~                   ,     .
                     < .     L   .   G = = 7   .       ` . . . 1       7 ' , . . ,               ?       7     .
                      3     .     .       . ~ t     J     $ '     ,     ,   ` ^ !                 <       ! .
                       ?   .       . j     ? .     r .   . .   r   r . J                           .         .
                        7 . .       . ,     7 .   J     L J ? L   . . ^ .           Z                         . ?
                         ! `       ,         r   .   ~     7 ` . . . 1               7             .           ? 1
                          ` .       . %     j     ;   = 4   ?   ' `                 ? `             =           ? .
                             .   . .             j     . .   ?       <   `           ,               .           7
                              ` . % 7         .   .     .     7       .   ?
                               7 `   .         . r .     G     <     J     ~         5               ?
                                .     .         ,         .     .     .     .         .     .         ,
                               4       .         ^ ;             .   t               ?
                                .       .           ?               .       .         .               4
                               J   . . . .           1           7 .         =       1                 .
                                . r ^ ^ ` .           .           . ;         .     .                 ,
                                 `       ! .         .             :                 ,         `       ,
                                J           .     . . .                       4     F           ?     .
                                 i . ` , .   .     >                           . . F             ^     ;
                                  J !   ` ?   ?     =                         ` , %               .   .
                                 .         7   T     .                         '                   .   ,
                                  1         !   i . .                                                 ,
                                   .         ?   . D .                                                 ,
                                              7   .                                                 ? ,
                                   ?           + ` l                                                 ^ ,
                                    1           . j                                                   C
                                     .         .   ,
                                                i 1
                                                 .
                                      7         G ;
                                       <         %
                                        .     . %
                                         . . J `
                                          % '

```

## Rules and Notes

* Input and output may be in any convenient format and character encoding as long as it supports all printable ASCII characters (U+0020 - U+007E, LF)
* You may assume the input contains only printable ASCII characters (defined above)
* You must support art up to \\$100 \times 100\\$ characters.
* You may assume the input is right-padded, as to be a perfect rectangular grid of characters.
    + If it conveniences you, you may also assume the input is padded to be exactly \\$100 \times 100\\$ characters.
* Use the ASCII space to align and space characters.
* Characters may be overpadded (or even underpadded) in any direction as long as the result is properly aligned.

Happy Golfing!

# Answer
> 19 votes
# Charcoal, 2 bytes

```
↘Ａ

```

Try it online! Link is to verbose version of code. Takes input as either a single newline-delimited string literal or as an array of strings. Explanation:  reads the input and  outputs it in the desired diagonal direction. Version which accepts a blank-line terminated list of lines from STDIN:

```
ＷＳ⊞υι↘υ

```

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

# Answer
> 11 votes
# Canvas, 6 bytes

```
／⤢ ＊＼⤢

```

Try it here!

```
/        pad each line with one less space than the previous
 ⤢       transpose the object
   *     place a space between every character
    \    pad each line with one more space than the previous
     ⤢   transpose the object back

```

Example:

```
123
456
789
/:
  123
 456
789
⤢:
  7
 48
159
26
3
 *:
    7
  4 8
1 5 9
2 6
3
\:
    7
   4 8
  1 5 9
   2 6
    3
⤢:

  1
 4 2
7 5 3
 8 6
  9

```

# Answer
> 6 votes
# Python 3.8 (pre-release), 104 bytes

```
lambda a:[" "*abs(l+~i)+" ".join(a[i-j][j]for j in range(i+1)if j<l>i-j)for i in range((l:=len(a))*2-1)]

```

Try it online!

-5 bytes thanks to ovs (Python 3.8 things)

# Answer
> 2 votes
# , ~~56~~ 45 bytes

-11 bytes thanks to FrownyFrog!

```
-@}:@(i.@-@#,#\@{.)|."_1+/@${."1|.@,@,.&' '/.

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~18~~ 12 bytes

```
RāRú€Sζðýāú»

```

Port of *@dzaima*'s Canvas answer, so make sure to upvote him!!

Input as a list of lines.

Try it online.

**Explanation:**

```
R             # Reverse the (implicit) input-list
 ā            # Push a list in the range [1, length of input-list],
              # without popping the list itself
  R           # Reverse this list to [length, 1]
   ú          # Pad the reversed input-list with that many leading spaces
    €S        # Split each string on spaces
      ζ       # Zip/transpose; swapping rows/columns, with space default as filler
       ðý     # Join each inner character-list by spaces
         ā    # Push a list in the range [1, length of this string-list],
              # without popping the list itself
          ú   # Pad the list of strings with that many leading spaces
           »  # Join the string-list by newlines (and output the result implicitly)

```

---

**Original ~~18~~ 17 bytes answer:**

```
€g2.ýIεNFR]JŽE5SΛ

```

Input as a list of lines.

Try it online.

**Explanation:**

```
€g     # Get the length of each line of the (implicit) input
       # (assumes they are all padded with spaces to make them of equal length)
  2.ý  # Intersperse this list with 2 (i.e. [3,3,3] becomes [3,2,3,2,3])
Iε     # Map the strings in the input to:
  NF   #  Loop the 0-based index amount of times:
    R  #   And reverse the current string that many times
 ]J    # After the loop and map: join the strings to a single string
ŽE5S   # Push compressed integer 3575, converted to a list of digits: [3,5,7,5]
Λ      # Use the canvas with these three options (which is output immediately by default)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ŽE5` is `3575`.

Some more info about the 05AB1E Canvas builtin can be found in this tip of mine.

The Canvas builtin takes three parameters:

* \\$a\\$ Length: The size(s) of the line(s). This can be a single integer, or a list of integers
* \\$b\\$ String: The character(s) we want to display. This can be a single character, a string, a list of characters, or a list of strings (in the last three cases it will use all of them one-by-one including wrap-around)
* \\$c\\$ Direction: The direction the character-lines should be drawn in. In general we have the digits `[0,7]` for the directions, for which we can use one or multiple. There are also some special options that require a certain character (`+`, `×`, `8`).

In this challenge I use the following options:

\\$c\\$: Let's start with the directions. For this I use \\$\[3,5,7,5\]\\$ which translates to \\$\[↘,↙,↖↙\]\\$. This means the string is printed in the following matter:

```
     S
      ↘
   ↙↖   ↘
   ↘   ↖  ↘
↙↖   ↘   ↖↙
↘  ↖   ↘
  .  ↖ ↙
    .

```

\\$b\\$: Since we print in this direction, this means the list of strings we input has to be modified slightly, which is what we do with the reverse on each 0-based odd-indexed string in the list.

\\$a\\$: Finally, the lengths of how it is printed. This will be the length of each lines for the directions \\$3\\$ (\\$↘\\$) and \\$7\\$ (\\$↖\\$). The \\$2\\$ for the directions \\$5\\$ (\\$↙\\$), which means to print one character (with a character overlap of the trailing part of the previous line) in a south-west direction, and then we print the next line (with again one character overlap, hence the use of \\$2\\$ instead of \\$1\\$). This overlapping is better explained in the tip I linked earlier.

# Answer
> 0 votes
# Jelly, 26 bytes

```
JU’;ZJ$x@€⁶ðżµUŒDUṙLN‘ƊṚK€

```

Try it online!

# Answer
> 0 votes
# Jelly, 19 bytes

```
ỴṚµLḶṚŒḄ⁶ẋżŒDṙLK€ƲY

```

Try it online!

# Answer
> 0 votes
# JavaScript (ES6), 102 bytes

```
f=
s=>(z=[...Array(100)],o=z.map(v=>z.map(_=>" ")),s.map((r,y)=>r.map((c,x)=>o[y+x][s.length+~y+x]=c)),o)

```

Try it online!

Input and output as list of lists.

**Explanation:**

Creates a 100x100 grid of spaces. Then loops through the input, setting the appropriate entry in the grid. The index of the character to set is calculated as `x' = length of input - 1 + y + x` and `y' = y + x`.

The returned result is a 100x100 list of lists, with the output in the upper left corner.

# Answer
> 0 votes
# Ruby, 94 bytes

```
->l{w=(2..y=l.size+b=l[z=0].size).map{' '*y};l.map{|r|b.times{|x|w[x+z][b+~z+x]=r[x]};z+=1};w}

```

Try it online!

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 153 bytes

```
z=>{var m=new char[100,100];var s=z.Split('\n');var l=s[0].Length;for(int x=0;x<l-1;x++)for(int y=0;y<s.GetLength(0);y++)m[x+y,l+~y+x]=s[y][x];return m;}

```

Try it online!

Asks for a string and returns a 2D char 100 x 100 array.

I tried using LINQ/Collections, but I eventually give up.

# Answer
> 0 votes
# Wolfram Language (Mathematica), 79 bytes

```
SparseArray[100+{#2+#,#2-#}&@@#&/@Range@100~Tuples~2->Flatten@#,{301,301}," "]&

```

Try it online!

The input should be padded as exactly 100x100. The output is an array of 301x301. The result of rotating sonic (with proper formatting):

---
Tags: code-golf, ascii-art
---


# Question
Title: Do I have a twin with permutated remainders?
We define \\$R\_n\\$ as the list of remainders of the Euclidean division of \\$n\\$ by \\$2\\$, \\$3\\$, \\$5\\$ and \\$7\\$.

Given an integer \\$n\ge0\\$, you have to figure out if there exists an integer \\$0\<k\<210\\$ such that \\$R\_{n+k}\\$ is a permutation of \\$R\_n\\$.

## Examples

The criterion is met for \\$n=8\\$, because:

* we have \\$R\_8=(0,2,3,1)\\$
* for \\$k=44\\$, we have \\$R\_{n+k}=R\_{52}=(0,1,2,3)\\$, which is a permutation of \\$R\_8\\$

The criterion is not met for \\$n=48\\$, because:

* we have \\$R\_{48}=(0,0,3,6)\\$
* the smallest integer \\$k\>0\\$ such that \\$R\_{n+k}\\$ is a permutation of \\$R\_{48}\\$ is \\$k=210\\$ (leading to \\$R\_{258}=(0,0,3,6)\\$ as well)

## Rules

* You may either output a truthy value if \\$k\\$ exists and a falsy value otherwise, or two distinct and consistent values of your choice.
* This is .

## Hint

> *Do you really need to compute \\$k\\$? Well, maybe. Or maybe not.*

## Test cases

Some values of \\$n\\$ for which \\$k\\$ exists:

```
3, 4, 5, 8, 30, 100, 200, 2019

```

Some values of \\$n\\$ for which \\$k\\$ does not exist:

```
0, 1, 2, 13, 19, 48, 210, 1999

```

# Answer
> 22 votes
# , ~~63~~ ~~59~~ ~~46~~ 43 bytes

```
\(n,a=c(2,3,5,7))any(diff(s<-n%%a)&s[-1]<a)

```

Attempt This Online!

-4 bytes thanks to Giuseppe
-13 bytes by switching to `diff`
-3 bytes inspired by a suggestion from Dominic van Essen

(The explanation contains a spoiler as to how to solve the problem without computing \\$k\\$.)

Explanation: Let \\$s\\$ be the list of remainders. Note the constraint that s\[1\]\<2, s\[2\]\<3, s\[3\]\<5 and s\[4\]\<7. By the Chinese Remainder Theorem, there exists a \\$k\\$ iff there is a permutation of \\$s\\$, distinct from \\$s\\$, which verifies the constraint. In practice, this will be verified if one of the following conditions is verified:

* s\[2\]\<2 and s\[2\]!=s\[1\]
* s\[3\]\<3 and s\[3\]!=s\[2\]
* s\[4\]\<5 and s\[4\]!=s\[3\]

# Answer
> 8 votes
# Haskell, 69 bytes

Based on the Chinese remainder theorem

```
m=[2,3,5,7]
f x|s<-mod x<$>m=or[m!!a>b|a<-[0..2],b<-drop a s,s!!a/=b]

```

Try it online!

# Answer
> 5 votes
# Perl 6, ~~64~~ ~~61~~ ~~59~~ 43 bytes

```
{map($!=(*X%2,3,5,7).Bag,^209+$_+1)∋.&$!}

```

Try it online!

-16 thanks to @Jo King

# Answer
> 5 votes
# C# (Visual C# Interactive Compiler), ~~125~~ ~~42~~ ~~38~~ 36 bytes

```
n=>n%7<5&5<n%35|n%5<3&3<n%15|-~n%6>3

```

Direct port of @xnor's answer, which is based off of @RobinRyder's solution.

Saved 4 bytes thanks to @Ørjan Johansen!

Saved 2 more thanks to @Arnauld!

Try it online!

# Answer
> 5 votes
# Haskell, 47 bytes

```
g.mod
g r|let p?q=r p/=r q&&r q<p=2?3||3?5||5?7

```

Try it online!

# Answer
> 4 votes
# Wolfram Language (Mathematica), 67 bytes

```
!FreeQ[Sort/@Table[R[#+k],{k,209}],Sort@R@#]&
R@n_:=n~Mod~{2,3,5,7}

```

Try it online!

# Answer
> 4 votes
# Python 2, 41 bytes

```
lambda n:n%5!=n%7<5or n%3!=n%5<3or-~n%6/4

```

Try it online!

Uses the same characterization as Robin Ryder. The check `n%2!=n%3<2` is shortened to `-~n%6/4`. Writing out the three conditions turned out shorter than writing a general one:

**46 bytes**

```
lambda n:any(n%p!=n%(p+1|1)<p for p in[2,3,5])

```

Try it online!

# Answer
> 2 votes
# Ruby, 54 bytes

```
->n{[2,3,5,7].each_cons(2).any?{|l,h|n%l!=n%h&&n%h<l}}

```

Try it online!

Uses Robin Ryder's clever solution.

# Answer
> 2 votes
# Java (JDK), 36 bytes

```
n->n%7<5&5<n%35|n%5<3&3<n%15|-~n%6>3

```

Try it online!

## Credits

* Port of xnor's solution, improved by Ørjan Johansen.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 56 bytes

```
Or@@(Min[s-#]>0&/@Rest@Permutations@Mod[#,s={2,3,5,7}])&

```

Try it online!

Finds all non-identity permutations of the remainders of the input modulo 2, 3, 5, 7, and checks if any of them are below `{2,3,5,7}` in each coordinate. Note that `Or@@{}` is `False`.

# Answer
> 1 votes
# PHP, ~~81~~ ~~78~~ 72 bytes

```
while($y<3)if($argn%($u='235'[$y])!=($b=$argn%'357'[$y++])&$b<$u)die(T);

```

A riff on @Robin Ryder's answer. Input is via `STDIN`, output is `'T'` if truthy, and empty `''` if falsy.

```
$ echo 3|php -nF euc.php
T
$ echo 5|php -nF euc.php
T
$ echo 2019|php -nF euc.php
T
$ echo 0|php -nF euc.php

$ echo 2|php -nF euc.php

$ echo 1999|php -nF euc.php

```

Try it online!

### Or 73 bytes with `1` or `0` response

`while($y<3)$r|=$argn%($u='235'[$y])!=($b=$argn%'357'[$y++])&$b<$u;echo$r;`

```
$ echo 2019|php -nF euc.php
1
$ echo 1999|php -nF euc.php
0

```

Try it online (all test cases)!

### Original answer, ~~133~~ 127 bytes

```
function($n){while(++$k<210)if(($r=function($n){foreach([2,3,5,7]as$d)$o[]=$n%$d;sort($o);return$o;})($n+$k)==$r($n))return 1;}

```

Try it online!

# Answer
> 1 votes
# , 72 bytes

```
n=scan();b=c(2,3,5,7);for(i in n+1:209)F=F|all(sort(n%%b)==sort(i%%b));F

```

Try it online!

# Answer
> 1 votes
# Jelly, 15 bytes

```
8ÆR©PḶ+%Ṣ¥€®ċḢ$

```

Try it online!

I’m sure there’s a golfier answer. I’ve interpreted a truthy value as being anything that isn’t zero, so here it’s the number of possible values of k. If it needs to be two distinct values that costs me a further byte.

### Explanation

```
8ÆR             | Primes less than 8 [2,3,5,7]
   ©            | Copy to register
    P           | Product [210]
     Ḷ          | Lowered range [0, 1, ..., 208, 209]
      +         | Add to input
         ¥€     | For each of these 210 numbers...
       %   ®    |   Modulo 2, 3, 5, 7
        Ṣ       |   And sort
            ċḢ$ | Count how many match the first (input) number’s remainders

```

# Answer
> 1 votes
# Python 3, 69 bytes

```
lambda x:int('4LR2991ODO5GS2974QWH22YTLL3E3I6TDADQG87I0',36)&1<<x%210

```

Try it online!

Hardcoded

# Answer
> 1 votes
# 05AB1E, 16 bytes

```
Ƶ.L+ε‚ε4Åp%{}Ë}à

```

Try it online or verify all test cases.

**Explanation:**

```
Ƶ.L          # Create a list in the range [1,209] (which is k)
   +         # Add the (implicit) input to each (which is n+k)
    ε        # Map each value to:
     ‚       #  Pair it with the (implicit) input
      ε      #  Map both to:
       4Åp   #   Get the first 4 primes: [2,3,5,7]
          %  #   Modulo the current number by each of these four (now we have R_n and R_n+k)
           { #   Sort the list
      }Ë     #  After the inner map: check if both sorted lists are equal
     }à      # After the outer map: check if any are truthy by taking the maximum
             # (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶ.` is `209`.

# Answer
> 1 votes
# , 40 bytes

```
1 e.(>:+i.@209)-:&(/:~)&(2 3 5 7&|"1 0)]

```

Try it online!

Brute force...

---
Tags: code-golf, decision-problem, number-theory
---


# Question
Title: Reorder a Master List Based on a Reordered Subset
I recently had a problem to solve at work where I had two lists: a master list, and a smaller list that contains a subset of the items in the master list potentially in a different order. I needed to reorder the master list in such a way that the items in the subset would appear in the same order without changing the order of the items not found in the list and keeping items in the same location whenever possible. Okay, that probably sounds confusing, so I'll break it down:

* The master list defines the default order of items.
* The subset list defines relative order of certain items.
* Where the master list has two elements out of order according to the subset list, the item that is earlier in the master list should be moved to the earliest index where it is in the correct location relative to other items within the subset list. (i.e. immediately after the later item)

Your task is to implement this reordering algorithm.

## Example Test Cases

```
Master: [1, 2, 3]
Subset: []
Result: [1, 2, 3]

```

---

```
Master: [9001, 42, 69, 1337, 420]
Subset: [69]
Result: [9001, 42, 69, 1337, 420]

```

---

```
Master: [9001, 42, 69, 1337, 420, 99, 255]
Subset: [69, 9001, 1337]
Result: [42, 69, 9001, 1337, 420, 99, 255]

```

---

```
Master: [1, 2, 3, 4, 5]
Subset: [2, 5]
Result: [1, 2, 3, 4, 5]

```

---

```
Master: [apple, banana, carrot, duck, elephant]
Subset: [duck, apple]
Result: [banana, carrot, duck, apple, elephant]

```

---

```
Master: [Alice, Betty, Carol, Debbie, Elaine, Felicia, Georgia, Helen, Ilene, Julia]
Subset: [Betty, Felicia, Carol, Julia]
Result: [Alice, Betty, Debbie, Elaine, Felicia, Carol, Georgia, Helen, Ilene, Julia]

```

---

```
Master: [snake, lizard, frog, werewolf, vulture, dog, human]
Subset: [snake, werewolf, lizard, human, dog]
Result: [snake, frog, werewolf, lizard, vulture, human, dog]

```

---

```
Master: [Pete, Rob, Jeff, Stan, Chris, Doug, Reggie, Paul, Alex]
Subset: [Jeff, Stan, Pete, Paul]
Result: [Rob, Jeff, Stan, Pete, Chris, Doug, Reggie, Paul, Alex]

```

---

```
Master: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Subset: [8, 1, 2, 12, 11, 10]
Result: [3, 4, 5, 6, 7, 8, 1, 2, 9, 12, 11, 10]

```

---

```
Master: [lol, rofl, lmao, roflmao, lqtm, smh, jk, wat]
Subset: [wat, lmao, rofl]
Result: [lol, roflmao, lqtm, smh, jk, wat, lmao, rofl]

```

## Rules

* Standard loopholes, yadda yadda, convenient I/O, blah blah.
* Even though the examples use numbers and strings, you only need to support one element type, whether that's integers, strings, or anything else with well-defined equality semantics, including heterogeneous lists if that's convenient in your language.
* You may assume both the master list and the subset list contain no duplicates
* You may assume that all items found in the subset list are found in the master list
* Either list may be empty
* You must, at minimum, support arrays up to 100 elements long.
* Reordering may be implemented in-place or through the creation of a new list/array.

Happy Golfing!

# Answer
# Retina 0.8.2, 51 bytes

```
+`(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)
$1$4,$3
1A`

```

Try it online! Takes input as a comma-separated list of subwords on the first line and a comma-separated master list of words on the second line. Explanation:

```
(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)

```

Find two adjacent subwords where the second word precedes the first on the master list.

```
$1$4,$3

```

Move the second word to appear after the first word in the master list.

```
+`

```

Repeat until no words appear out of order.

```
1A`

```

Delete the subwords.
> 4 votes

# Answer
# JavaScript (ES6),  ~~96 89 74~~  71 bytes

This started as a bulky mess and was eventually shrunk to a rather concise and elegant form. I'd like to thank the *.splice()* method for its fruitful collaboration on that one. ;)

Takes input as `(master)(subset)`. Outputs by updating the master list.

```
m=>s=>s.map(p=x=>m.splice(p,0,...m.splice(i=m.indexOf(x),p>i||!(p=i))))

```

Try it online!

### How?

We are using two nested *.splice()* methods on the same array to conditionally move an element from position \\$i\\$ to position \\$p\\$:

```
m.splice(p, 0, ...m.splice(i, condition))

```

If the condition is truthy (coerced to \\$1\\$):

* the inner *.splice()* removes and returns the element at position \\$i\\$ as a singleton array \\$\[element\]\\$
* thanks to the spread syntax, this element is expanded as a 3rd argument for the outer *.splice()*, which causes it to be inserted back at position \\$p\\$

If the condition is falsy (coerced to \\$0\\$):

* the inner *.splice()* removes nothing and returns an empty array
* as a result, the outer *.splice()* receives *undefined* as its 3rd argument and nothing is inserted either

### Commented

```
m => s =>                 // m[] = master list, s[] = subset list
  s.map(                  //
    p =                   // p = position in the master list of the last element from
                          //     the subset list (initialized to a non-numeric value)
    x =>                  // for each element x in the subset list:
    m.splice(             //   insert in the master list:
      p,                  //     at position p
      0,                  //     without removing any element
      ...m.splice(        //     remove from the master list and flatten:
        i = m.indexOf(x), //       i = position of x in the master list
        p > i             //       if p is greater than i, remove x from its current
                          //       position and insert it at position p
        || !(p = i)       //       otherwise, set p to i and don't remove/insert anything
      )                   //     end of inner splice()
    )                     //   end of outer splice()
  )                       // end of map()

```
> 4 votes

# Answer
## Haskell, 79 bytes

```
(m:n)#u@(s:t)|m==s=m:n#t|all(/=m)u=m:n#u|(x,_:z)<-span(/=s)n=(x++s:m:z)#u
m#_=m

```

Try it online!

```
(m:n)#u@(s:t)                 -- m: head of master list
                              -- n: tail of master list
                              -- s: head of subset
                              -- t: tail of subset
                              -- u: whole subset
   |m==s                      -- if m==s
        =m:n#t                -- return 'm' and append a recursive call with 'n' and 't'
   |all(/=m)u                 -- if 'm' is not in 'u'
             =m:n#u           -- return 'm' and append a recursive call with 'n' and 'u'
   |                          -- else (note: 's' is element of 'n')
    (x,_:z)<-span(/=s)n       -- split 'n' into a list 'x' before element 's' and
                              -- a list 'z' after element 's' and
       = (x++s:m:z)#u         -- make a recursive call with
                              -- x++s:m:z as the new master list (i.e. 'm' inserted into 'n' after 's')
                              -- and 'u'
m # _ = m                     -- if either list is emtpy, return the master list

```
> 2 votes

# Answer
# Ruby, ~~73~~ 68 bytes

```
->a,b{0while b.zip(a&b).find{|m,n|m!=n&&a=a[0..a.index(m)]-[n]|a};a}

```

Try it online!

### How?

* The intersection between `a` and `b` contains all elements of `b`, but in the same order as we would find them in `a`
* So, if we iterate on `b` and on the intersection in parallel, as soon as we find a difference, we can relocate a single element.
* Relocation is done by cutting `a` on the position of the element we found in `b`, then removing the element we found in the intersection, and then adding the remainder of a.
* Repeat from the beginning, until all elements of `b` are in the right order in `a`
> 2 votes

# Answer
# Python 2, ~~124~~ ~~109~~ ~~106~~ ~~99~~ 96 bytes

```
def f(a,b,i=0):
 while b[i+1:]:x,y=map(a.index,b)[i:i+2];i+=1;x>y>a.insert(x,a.pop(y))
 return a

```

Try it online!
> 1 votes

# Answer
# , 49 bytes

```
[:(<@({:+i.@>:@-/)@i.~C.])^:(>/@i.~)&.>/]|.@;2<\[

```

Try it online!

## explanation

We take the subset as the left arg and the full input as the right.

We'll work through the code with a specific example for clarity:

```
5 2 4 f 1 2 3 4 5

```

Take the boxed infixes of size two of the subset:

```
2 <\ [

```

producing:

```
┌───┬───┐
│5 2│2 4│
└───┴───┘

```

append them to the original input, and reverse the whole thing:

```
] |.@;

```

We get:

```
┌───┬───┬─────────┐
│2 4│5 2│1 2 3 4 5│
└───┴───┴─────────┘

```

Solving the problem becomes a right to left reduction on the above. We need only find the right verb to insert `/` between the items.

Each iteration of the reduction will update the rightmost box (the full input, which we're transforming) so it conforms to the ordering constraint represented by the pair to its left. When the reduction is finished, the input will respect the complete subset ordering.

If the ordering of the pair is the same as ordering in the input, the following will evaluate to 0 and we'll do nothing:

```
^:(>/@i.~)

```

Otherwise it will evaluate to 1 and we'll apply the verb to the left of `^:`

```
   {: + i.@>:@-/)@i.~ C. ]

```

which moves the left item to the right of the right item. This movement is simply a *cyclic permutation* of all the items between (and including) the two elements in question.

J has primitive to apply such a cyclic permutation:

```
<cyclic permutation definition> C. ]

```

and the remainder of the verb does nothing but pick out the indexes we need to cycle:

```
{: + i.@>:@-/)@i.~

```

which seems longer than it should be, but I wasn't able to golf that phrase further.

Finally we rebox the result `<@` and we're done.
> 1 votes

# Answer
# Perl 6, 40 bytes

```
{*.permutations.first(*.grep(.any)eq$_)}

```

Try it online!

Anonymous code block that takes the input curried (like `f(subList)(masterList)`, and finds the first lexographical permutation of the indexes of the master list where the elements from the sub list are in the correct order.

Intuitively, the first satisfying permutation will leave the correctly ordered elements in the original order, while moving the incorrectly placed ones the minimum needed distance forward in order to have them in the correct order, which places them directly after the previous element in the subset.

### Explanation:

```
{*                                     } # Anonymous code block that returns a lambda
  .permutations                          # In all permutations of the master list
               .first(                )  # Find the first permutation
                     (*.grep(.any)       # Where the order of the subset
                                  eq$_   # Is the same as the given order

```
> 1 votes

# Answer
# Jelly, 9 bytes

```
Œ!iⱮṢƑ¥ƇḢ

```

Try it online! or Test suite

Inefficient, particularly with large master lists. Generates all possible permutations, filters out those where the subset is in the wrong order, and then returns the first.

### Explanation

```
Œ!        | Generate all permutations of the master list
      ¥Ƈ  | Filter including only those where...
  iⱮ      |   the index of each sublist item in this permutation...
     Ƒ    |   is...
    Ṣ     |   in order.
        Ḣ | Finally take the first item

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 118 bytes

```
a=>b=>{for(int j;b.Any();)foreach(var e in b.Intersect(a.Take(j=a.IndexOf(b.Dequeue())))){a.Remove(e);a.Insert(j,e);}}

```

Try it online!

Leveraging some classes in the `System.Collections.Generic` namespace. The master is a `List<T>` and the subset is a `Queue<T>`.

```
// a: master
// b: subset
a=>b=>{
  // continue until b is empty
  for(int j;b.Any();)
    // iterate over values that are out of order in a
    // per the head of b using loop variable e
    foreach(var e in
      // the out of order values are determined by
      // intersecting remaining values in b with
      b.Intersect(
        // values in a occurring before the current head of b
        // save the position in a to variable j and remove the head of b
        a.Take(j=a.IndexOf(b.Dequeue()))
      )
    ){
      // push back the out of order element in a
      a.Remove(e);
      a.Insert(j,e);
    }
}

```
> 0 votes

# Answer
# Jelly, 24 bytes

```
i@€MƤFṬœṗƲḊ;JḟF}W€ʋ@¥ṢFị

```

Try it online! or Test suite

### Explanation

A dyadic link that takes the subset as the left and master list as right arguments. The below example uses 9001, 42, 69, 1337, 420, 99, 255 as master and 69, 9001, 1337 as subset.

```
i@€                      | Find the index of each subset item in the master list [3, 1, 4]
         Ʋ               | Previous 4 links as a monad
   MƤ                    | Find the index of the maximum for each prefix of this list [1, 1, 3]
     F                   | Flatten (because the previous result are actually each length one lists)
      Ṭ                  | Convert to a boolean list [1,0,1]
       œṗ                | Partition the [3, 1, 4] list before each 1 [[], [3, 1], [4]]
          Ḋ              | Remove the empty first list [[3, 1], [4]]
                    ¥    | Previous two links as a dyad
                  ʋ@     | Previous 4 links as a dyad with reversed arguments
            J            | Sequence along the master list [1, 2, 3, 4, 5, 6, 7]
             ḟF}         | Filter out items in the flattened [3, 1, 4] list
                W€       | Wrap each item as a list [[2], [5], [6], [7]]
           ;             | Concatenate rhis to the [[3, 1], [4]] list
                     Ṣ   | Sort (effectively by first item in each list) [[2], [3, 1], [4], [5], [6], [7]]
                      F  | Flatten
                       ị | Look up in original master list (and implicitly output)

```
> 0 votes

---
Tags: code-golf, array
---


title: Roll the carpet

text:
# Question
Title: Roll the carpet
This question is inspired by Kevin Cruijssen's question.

Now that the carpet is laid out, we want to roll it. Your task is to write a program that takes a string and returns a spiral made from this string (representing a rolled carpet viewed from the side).

The procedure for one step of rolling the carpet is the following. There is an example to illustrate what I mean. Notice that the example starts with a partially rolled carpet for better understanding:

```
ac
rpet

```
* separate the "head" from the "tail" of the carpet: the head is what has been rolled so far, the tail is what remains to be rolled.

```
Head: ac   Tail:
      rp          et

```
* Rotate the head 90°, clockwise.

```
Rotated head: ra   Tail (unchanged):
              pc                       et

```
* if the width of the new head (here `2`) is less or equal than the length of the tail (here `2`)
    + then, put it on top of the tail
    + else, the carpet (as it was at the begining of the step) was rolled

```
New carpet: ra
            pc
            et

```

Repeat the procedure as many times as needed.

---

Two examples showing all steps of the carpet rolling:

```
carpet

 c
 arpet

  ac
  rpet

    ra
    pc
    et

```

```
0123456789

 0
 123456789

  10
  23456789

    21
    30
    456789

      432
      501
      6789

```

---

## Some precisions:

* You don't need to show all intermediate steps, only the rolled carpet (e.g. if you find a non-iterative way to compute the result, it's perfect). Also, you don't need to print any leading whitespace, in the examples above, I only show them to align stuff.
* Input is a String, a list/array of char
* Output is printed to stdout or to a file.
* Input is nice: the length is at least 1 char, and at most a constant sufficiently small so that it doesn't cause problems, but you can't use that constant in your program; the content of the string is only nice characters (\[a-zA-Z0-9\]), encoding at your preference.
* This is , so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, add an explanation for your answer if you think it is needed.

# Answer
# Charcoal, 15 bytes

```
ＦＳ«Ｆ¬℅§ＫＶ⁰⟲⁶→Ｐι

```

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

```
ＦＳ«

```

Loop over the carpet.

```
Ｆ¬℅§ＫＶ⁰

```

Check whether there's anything above the cursor.

```
⟲⁶

```

If not then roll the carpet.

```
→Ｐι

```

Move right and output the current character.

Example: For the input `0123456789`, the following actions occur:

```
0

```

`0` is printed.

```
01

```

The cursor moves right and `1` is printed.

```
0
1

```

Since there is nothing above the `1`, the canvas is rotated.

```
0
12

```

The cursor moves right and the `2` is printed.

```
10
2

```

Since there is nothing above the `2`, the canvas is rotated.

```
10
23

```

The cursor moves right and the `3` is printed.

```
10
234

```

The cursor moves right and the `4` is printed.

```
21
30
4

```

Since there is nothing above the `4`, the canvas is rotated.

```
21
30
45

```

The cursor moves right and the `5` is printed.

```
21
30
456

```

The cursor moves right and the `6` is printed.

```
432
501
6

```

Since there is nothing above the `6`, the canvas is rotated.

```
432
501
67

```

The cursor moves right and the `7` is printed.

```
432
501
678

```

The cursor moves right and the `8` is printed.

```
432
501
6789

```

The cursor moves right and the `9` is printed.
> 7 votes

# Answer
# Pyth, 37 bytes

```
.U+j;bZ.WgleHJlhH,+_MChZ<eZJ>eZJ,]hQt

```

Try it online here, or verify all the test cases at once here.

```
.U+j;bZ.WgleHJlhH,+_MChZ<eZJ>eZJ,]hQtQ   Implicit: Q=eval(input())
                                         Trailing Q inferred
                                 ]hQ     First character of Q, wrapped in an array
                                    tQ   All but the first character of Q
                                ,        2-element array of the two previous results
                                           This yields array with rolled carpet (as array of strings) followed by the tail
       .W                                While condition function is truthy, execute inner function, with initial value of the above:
         gleHJlhH                          Condition function, input H
             JlhH                            Number of layers in the current rolled carpet, store in J
          leH                                Lenth of the tail
         g   J                               Is the above greater than or equal to J?
                 ,+_MChZ<eZJ>eZJ           Inner function, input Z
                   _MChZ                     Rotate the current rolled carpet (transpose, then reverse each row)
                  +     <eZJ                 Append the first J characters of the tail as a new row
                 ,                           Pair the above with...
                            >eZJ             ... all but the first J characters of the tail - this is the new tail
.U+j;bZ                                  Join the carpet roll on newlines and append the tail, implicit print

```
> 3 votes

# Answer
# Husk, 24 bytes

```
►S=ÖLmFȯ:T↔ø§z:oΘḣĠ+CṘ2N

```

Try it online!

## Explanation

```
Implicit input, say s="carpets"

CṘ2N  Break s into chunks:
   N   Natural numbers: [1,2,3,4,..
 Ṙ2    Repeat each twice: [1,1,2,2,3,3,4,4,..
C      Break s into chunks of these lengths: ["c","a","rp","et","s"]
       The last chunk is shorter if we run out of characters.

§z:oΘḣĠ+  Attempt to merge suffix of chunks:
      Ġ    Cumulative reduce chunk list from right
       +   by concatenation: ["carpets","arpets","rpets","ets","s"]
   oΘḣ     Prefixes of chunk list (empty and nonempty): [[],["c"],..,["c","a","rp","et","s"]]
§z         Zip these by
  :        appending: [["carpets"],["c","arpets"],..,["c","a","rp","et","s"]]
           These are all versions of the chunk list where some suffix has been merged.

mFȯ:T↔ø  Roll each list:
m         Map
 F        reduce from left
      ø   starting from empty character matrix
  ȯ:T↔    by this function:
    T↔     Reverse and transpose (rotating by 90 degrees)
  ȯ:       then append next chunk as new row.
         Result: [["carpets"],["c","arpets"],..,["epr","tca","s"]]

►S=ÖL  Select the matrix rolled by the correct amount:
►       Find element that maximizes
 S=     being equal to
   ÖL   sort by length.
        This selects a matrix whose rows have non-decreasing lengths.
        Ties are broken by choosing the rightmost one.
       Result: ["ra","pc","ets"]

Implicitly print each row separated by newlines.

```
> 3 votes

# Answer
# , 69 bytes

*-3 bytes thanks to FrownyFrog*

```
[:(}:@[,{:@[,])&>/[:((|:@|.@[,#@[$]);#@[}.])&>/^:(<:&#&>/)^:_,.@{.;}.

```

Try it online!

## explanation

```
[: (}:@[ , {:@[ , ])&>/ [: ((|:@|.@[ , #@[ {. ]) ; #@[ }. ])&>/^:(<:&#&>/)^:_ }. ;~ 1 1 $ {.

```

The algorithm is straightforward despite being a bit verbose for J.

Overall Strategy: Reduce the input to a square table, with a (possibly empty) leftover piece.

As we reduce, we'll use a 2 element list of boxes. Our "result so far" will be the first box, and "items remaining to be processed" will be the 2nd box. The first box will be initialized to the head of the input (but converted to a table):

```
1 1 $ {.

```

and "items remaining to be processed" will be the input's tail:

```
}. ;~

```

Now we have:

```
┌─┬─────┐
│c│arpet│
└─┴─────┘

```

where the 'c' is actually a 1x1 table.

We reduce that down using a J Do... While loop:

```
^:(...)^:_

```

Where the part in parenthesis is the "keep going" condition:

```
<:&#&>/

```

which says "keep going while the length of the right box is greater than or equal to the length of the left box (ie, the side length of the square matrix)

What does "keep going" mean? That's defined in the verb to the left of the first `^:`, which tells us how to take the current result and produce the next iteration. That verb is:

```
((|:@|.@[ , #@[ {. ]) ; #@[ }. ])&>/

```

Let's break it down:

```
((|:@|.@[ , #@[ {. ]) ; #@[ }. ])&>/
(  verb in parens               )&>/ NB. put the verb in parens
                                     NB. between the two items
                                     NB. of our list, and unbox
                                     NB. them into left / right
                                     NB. args ([ / ]) for the verb
 (|:@|.@[ , #@[ {. ]) ; #@[ }. ]     NB. breaking down verb in
                                     NB. parens...
                      ; ....         NB. new "remaining items":
                            }. ]     NB. remove from remaining
                        #@[          NB. the size of a side of
                                     NB. the result matrix
                ....  ;              NB. new "result":
  |:@|.@[                            NB. rotate existing result
          ,                          NB. and put it on top of
            #@[ {. ]                 NB. the items we removed
                                     NB. from remaining items

```

That is, this is just algorithm described in the OP translated literally into J.

Finally we deal with the (possibly 0) leftover items, the tail of our carpet roll:

```
(}:@[ , {:@[ , ])&>/

```

This says "take all but the last elm of the result":

```
}:@[

```

and append it to `,` the last items of the result `{:@[` with the remaining items appended to that last item `, ]`
> 2 votes

# Answer
# , ~~146~~ 132 bytes

```
function(s){m=F[F]
while({m=rbind(t(m)[,F:0],s[1:F])
s=s[-1:-F]
length(s)>sum(F<-dim(m))})0
write(m[F:1,],1,F[1],,"")
cat(s,sep="")}

```

Try it online!

Implements the carpet-rolling procedure. Takes input as a list of characters and prints to stdout.

Saved 14 bytes by finding a way to use a `do-while` loop and initializing using `F`.

```
function(s){
m=F[F]					# logical(0); create an empty array (this gets automatically promoted to character(0) later
while(					# do-while loop
      {m=rbind(t(m)[,F:0],s[1:F])	# rotate m counterclockwise and add the first F characters of s to the bottom
       s=s[-1:-F]			# remove those characters
       length(s)>sum(F<-dim(m))})0	# while the number of characters remaining is greater than the sum of m's dimensions
write(m[F:1,],1,F[1],,"")		# write the rolled portion write writes down the columns, we reverse each column
cat(s,sep="")				# and write the remaining characters
}

```
> 1 votes

# Answer
# Jelly, 30 bytes

Seems overly long...

```
ḢW,ðZU;Ls@¥©ḢWɗ,®Ẏ¤ð/ẈṢƑ$¿ḢY;Ɗ

```

**Try it online!**

### How?

```
ḢW,ðZU;Ls@¥©ḢWɗ,®Ẏ¤ð/ẈṢƑ$¿ḢY;Ɗ - Main Link: list of characters
Ḣ                              - pop and yield head
 W                             - wrap in a list
  ,                            - pair with (the remaining list after Ḣ)
                         ¿     - while...
                        $      - ...condition: last two links as a monad:
                     Ẉ         -   length of each
                       Ƒ       -   is invariant under:
                      Ṣ        -     sort
                    /          - ...do: reduce by:
   ð               ð           -   the enclosed dyadic chain -- i.e. f(head, tail):
    Z                          -     transpose
     U                         -     reverse each (giving a rotated head)
              ɗ                -     last three links as a dyad:
          ¥                    -       last two links as a dyad:
       L                       -         length (i.e. number of rows in current roll)
         @                     -         with swapped arguments:
        s                      -           split (the tail) into chunks of that length
           ©                   -       (copy to register for later)
            Ḣ                  -       pop and yield head (Note register "copy" is altered too)
             W                 -       wrap in a list
      ;                        -     concatenate (the rotated head with the first chunk of the tail)
                  ¤            -     nilad followed by link(s) as a nilad:
                ®              -       recall from register (other chunks of tail, or an empty list)
                 Ẏ             -       tighten (the chunks to a flat list)
               ,               -     pair (the concatenate result with the tightened chunks)
                             Ɗ - last three links as a monad:
                          Ḣ    -   pop and yield head
                           Y   -   join with newline characters
                            ;  -   concatenate (the remaining tail)
                               - when running as a full program implicitly prints

```
> 1 votes

# Answer
# 05AB1E, 41 bytes

```
g©L¦€DD2šηO®>‹Ï©IŽ8OS®g4α._.ΛðÜI®O®g->.$«

```

Way too long, but I wanted to use the Canvas.. Which was probably a bad choice now that I've finished it and it turned out to be this long..

Try it online. (No test suite, because there seems to be a weird issue with the  builtin..)

**Explanation:**

Let me start by giving a general explanation of the Canvas and what I wanted my code to accomplish. More detailed information can be found in this relevant 05AB1E tip of mine, but for this challenge I wanted to have do the following:

The Canvas builtin takes three parameters:

* \\$a\\$: The size(s) of the line(s). For this challenge, this would be a list `[2,2,3,3,4,4,5,5,...]`.
* \\$b\\$: The character(s) we want to display. For this challenge, this would simply be the input-string.
* \\$c\\$: The direction in which we want to draw these character-lines. For this challenge this would be the directions \\$\[2,0,6,4\]\\$ (\\$\[→,↑,←,↓\]\\$) rotated \\$n\\$ amount of times depending on the input-string to have a different starting direction (i.e. input `carpet` is \\$\[0,6,4,2\]\\$ instead and input `0123456789ABCDEFGHI` is \\$\[6,4,2,0\]\\$ instead).

As for the code:

```
g                # Get the length of the (implicit) input-string
 ©               # Store it in the register (without popping)
  L              # Create a list in the range [1,length]
   ¦             # Remove the first item to make the range [2,length]
    €D           # Duplicate each to get the list [2,2,3,3,4,4,5,5,...]
      D2š        # Create a copy and prepend a 2: [2,2,2,3,3,4,4,5,5,...]
         η       # Get the prefixes: [[2],[2,2],[2,2,2],[2,2,2,3],...]
          O      # Sum each prefix: [2,4,6,9,12,16,20,...]
           ®     # Push the length from the register again
            >‹   # Check for each summed prefix if it's <= length
              Ï  # And only leave the truthy values
               © # And store this in the register (without popping)
                 # (This is our `a` for the Canvas builtin)
I                # Push the input-string
                 # (This is our `b` for the Canvas builtin)
Ž8O              # Push compressed integer 2064
   S             # Converted to a list of digits: [2,0,6,4]
    ®g           # Push the list from the register, and get its length
      4α         # Get the absolute difference with 4
        ._       # And rotate the [2,0,6,4] that many times towards the left
                 # (This is our `c` for the Canvas builtin)
.Λ               # Now use the Canvas builtin, without printing it yet
  ðÜ             # Remove any trailing spaces (since the Canvas implicitly makes a rectangle)
     ®O          # Push the sum of the list from the register
       ®g-       # Subtract the length of the list from the register
          >      # And add 1
    I      .$    # Remove that many leading characters from the input-string
             «   # And append it at the end of the roll created by the Canvas
                 # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž8O` is `2064`.
> 1 votes

# Answer
# MATLAB / Octave, 154 bytes

Not the shortest one, but to golf in MATLAB/Octave is always fun :)

```
function h=r(t,h);n=fliplr(h');s=size(n,2);q=numel(t);if s<=q h=r(t(max(s,1)+1:end),[n; t(1:max(s,1))]);elseif q>0 h(:,end+q)=' ';h(end,end-q+1:end)=t;end

```

Try it online!
> 0 votes

# Answer
# Python 3, 112 bytes

```
r=lambda t,h=[[]]:len(h)>len(t)and h[:-1]+[h[-1]+list(t)]or r(t[len(h):],list(zip(*h[::-1]))+[list(t)[:len(h)]])

```

In this case, the output is the value of the function.

Try it online!

If you prefer, here another (longer, **129 bytes**) solution that prints directly the rolled input:

```
r=lambda t,h=['']:len(h)>len(t)and set(map(print,h[:-1]+[h[-1]+t]))or r(t[len(h):],list(map(''.join,zip(*h[::-1])))+[t[:len(h)]])

```

Try it online!
> 0 votes

---
Tags: code-golf, string
---