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 (here2
)- 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 code-golf, 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.
ProgrammingPuzzlesAndCodeGolf
- the final tail length greater than 1 tripped me up. \$\endgroup\$print
inside alambda
. \$\endgroup\$