Roll the carpetLay out the CarpetWind me a number snake!Tips for golfing in 05AB1ESpiral neighbourhoodsWrite...
What does it exactly mean if a random variable follows a distribution
Can I legally use front facing blue light in the UK?
Why do UK politicians seemingly ignore opinion polls on Brexit?
Can the Produce Flame cantrip be used to grapple, or as an unarmed strike, in the right circumstances?
Piano - What is the notation for a double stop where both notes in the double stop are different lengths?
I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine
Email Account under attack (really) - anything I can do?
What is the meaning of "of trouble" in the following sentence?
What happens when a metallic dragon and a chromatic dragon mate?
What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?
Is every set a filtered colimit of finite sets?
How is it possible for user's password to be changed after storage was encrypted? (on OS X, Android)
Does a dangling wire really electrocute me if I'm standing in water?
When blogging recipes, how can I support both readers who want the narrative/journey and ones who want the printer-friendly recipe?
How to move the player while also allowing forces to affect it
"My colleague's body is amazing"
Does bootstrapped regression allow for inference?
Need help identifying/translating a plaque in Tangier, Morocco
Why do we use polarized capacitors?
What is the offset in a seaplane's hull?
How to deal with fear of taking dependencies
Is Fable (1996) connected in any way to the Fable franchise from Lionhead Studios?
Extreme, but not acceptable situation and I can't start the work tomorrow morning
How to manage monthly salary
Roll the carpet
Lay out the CarpetWind me a number snake!Tips for golfing in 05AB1ESpiral neighbourhoodsWrite the shortest code to match a tail-repeating string where one character falls off the head in each repetitionShortest code to dump a file into workable memoryFour steps to the left: vipers. Four steps to the right: a cliff. Don't die!Is it a lipogram?Turn a string into a windmillString Addition (Adding a Maximum of 9+9+9)The Three 'R's: Reverse, Reorder, RepeatVisit and exit an arrayOptimal Alphabet SteppingLay out the Carpet
$begingroup$
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.
code-golf string
$endgroup$
|
show 5 more comments
$begingroup$
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.
code-golf string
$endgroup$
3
$begingroup$
Closely related
$endgroup$
– Giuseppe
Apr 5 at 12:59
2
$begingroup$
Also this one: codegolf.stackexchange.com/questions/125966/…, but none include the termination check.
$endgroup$
– Bromind
Apr 5 at 13:03
3
$begingroup$
Suggested test case:ProgrammingPuzzlesAndCodeGolf- the final tail length greater than 1 tripped me up.
$endgroup$
– Sok
Apr 5 at 13:48
$begingroup$
Where is the head on the secondcarpetexample, where nothing is rolled up?
$endgroup$
– Embodiment of Ignorance
Apr 5 at 15:36
1
$begingroup$
I think you've swapped the words "head" and "tail" here: "if the width of the new head [...] is greater or equal than the length of the tail [...]".
$endgroup$
– Erik the Outgolfer
Apr 5 at 21:08
|
show 5 more comments
$begingroup$
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.
code-golf string
$endgroup$
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.
code-golf string
code-golf string
edited Apr 5 at 21:40
Bromind
asked Apr 5 at 12:56
BromindBromind
20416
20416
3
$begingroup$
Closely related
$endgroup$
– Giuseppe
Apr 5 at 12:59
2
$begingroup$
Also this one: codegolf.stackexchange.com/questions/125966/…, but none include the termination check.
$endgroup$
– Bromind
Apr 5 at 13:03
3
$begingroup$
Suggested test case:ProgrammingPuzzlesAndCodeGolf- the final tail length greater than 1 tripped me up.
$endgroup$
– Sok
Apr 5 at 13:48
$begingroup$
Where is the head on the secondcarpetexample, where nothing is rolled up?
$endgroup$
– Embodiment of Ignorance
Apr 5 at 15:36
1
$begingroup$
I think you've swapped the words "head" and "tail" here: "if the width of the new head [...] is greater or equal than the length of the tail [...]".
$endgroup$
– Erik the Outgolfer
Apr 5 at 21:08
|
show 5 more comments
3
$begingroup$
Closely related
$endgroup$
– Giuseppe
Apr 5 at 12:59
2
$begingroup$
Also this one: codegolf.stackexchange.com/questions/125966/…, but none include the termination check.
$endgroup$
– Bromind
Apr 5 at 13:03
3
$begingroup$
Suggested test case:ProgrammingPuzzlesAndCodeGolf- the final tail length greater than 1 tripped me up.
$endgroup$
– Sok
Apr 5 at 13:48
$begingroup$
Where is the head on the secondcarpetexample, where nothing is rolled up?
$endgroup$
– Embodiment of Ignorance
Apr 5 at 15:36
1
$begingroup$
I think you've swapped the words "head" and "tail" here: "if the width of the new head [...] is greater or equal than the length of the tail [...]".
$endgroup$
– Erik the Outgolfer
Apr 5 at 21:08
3
3
$begingroup$
Closely related
$endgroup$
– Giuseppe
Apr 5 at 12:59
$begingroup$
Closely related
$endgroup$
– Giuseppe
Apr 5 at 12:59
2
2
$begingroup$
Also this one: codegolf.stackexchange.com/questions/125966/…, but none include the termination check.
$endgroup$
– Bromind
Apr 5 at 13:03
$begingroup$
Also this one: codegolf.stackexchange.com/questions/125966/…, but none include the termination check.
$endgroup$
– Bromind
Apr 5 at 13:03
3
3
$begingroup$
Suggested test case:
ProgrammingPuzzlesAndCodeGolf - the final tail length greater than 1 tripped me up.$endgroup$
– Sok
Apr 5 at 13:48
$begingroup$
Suggested test case:
ProgrammingPuzzlesAndCodeGolf - the final tail length greater than 1 tripped me up.$endgroup$
– Sok
Apr 5 at 13:48
$begingroup$
Where is the head on the second
carpet example, where nothing is rolled up?$endgroup$
– Embodiment of Ignorance
Apr 5 at 15:36
$begingroup$
Where is the head on the second
carpet example, where nothing is rolled up?$endgroup$
– Embodiment of Ignorance
Apr 5 at 15:36
1
1
$begingroup$
I think you've swapped the words "head" and "tail" here: "if the width of the new head [...] is greater or equal than the length of the tail [...]".
$endgroup$
– Erik the Outgolfer
Apr 5 at 21:08
$begingroup$
I think you've swapped the words "head" and "tail" here: "if the width of the new head [...] is greater or equal than the length of the tail [...]".
$endgroup$
– Erik the Outgolfer
Apr 5 at 21:08
|
show 5 more comments
9 Answers
9
active
oldest
votes
$begingroup$
Charcoal, 15 bytes
FS«F¬℅§KV⁰⟲⁶→Pι
Try it online! Link is to verbose version of code. Explanation:
FS«
Loop over the carpet.
F¬℅§KV⁰
Check whether there's anything above the cursor.
⟲⁶
If not then roll the carpet.
→Pι
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.
$endgroup$
$begingroup$
That's awesome. So basically Charcoal has a builtin "roll" operator in⟲?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
@Jonah Well, it won't roll for me as it goes, but by outputting the string character-by-character I can roll as I go, yes.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
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
$endgroup$
add a comment |
$begingroup$
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.
$endgroup$
add a comment |
$begingroup$
J, 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 , ]
$endgroup$
$begingroup$
Ah, J... letters are for noobs
$endgroup$
– RK.
2 days ago
$begingroup$
,.can do what1 1$]does and$can be used as{..
$endgroup$
– FrownyFrog
2 days ago
$begingroup$
@FrownyFrog ty. I got it to 70 bytes with your first suggestion but wasn't sure if I understood$ can be used as {.-- can you clarify?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
The last line of the explanation, you use {. to truncate, that one can be a $ as far as I understand.
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Also you can replace the right [: with a @
$endgroup$
– FrownyFrog
yesterday
add a comment |
$begingroup$
R, 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
}
$endgroup$
add a comment |
$begingroup$
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
$endgroup$
add a comment |
$begingroup$
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!
$endgroup$
$begingroup$
sadly, op says you have to print
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
Python 3, 124 bytes
r=lambda t,h=[]:len(h)>len(t)and h[:-1]+[h[-1]+list(t)]or r(t[max(len(h),1):],list(zip(*h[::-1]))+[list(t)[:max(len(h),1)]])
Try it online!
$endgroup$
$begingroup$
need to print it
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
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. inputcarpetis $[0,6,4,2]$ instead and input0123456789ABCDEFGHIis $[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.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "200"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f182727%2froll-the-carpet%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Charcoal, 15 bytes
FS«F¬℅§KV⁰⟲⁶→Pι
Try it online! Link is to verbose version of code. Explanation:
FS«
Loop over the carpet.
F¬℅§KV⁰
Check whether there's anything above the cursor.
⟲⁶
If not then roll the carpet.
→Pι
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.
$endgroup$
$begingroup$
That's awesome. So basically Charcoal has a builtin "roll" operator in⟲?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
@Jonah Well, it won't roll for me as it goes, but by outputting the string character-by-character I can roll as I go, yes.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
Charcoal, 15 bytes
FS«F¬℅§KV⁰⟲⁶→Pι
Try it online! Link is to verbose version of code. Explanation:
FS«
Loop over the carpet.
F¬℅§KV⁰
Check whether there's anything above the cursor.
⟲⁶
If not then roll the carpet.
→Pι
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.
$endgroup$
$begingroup$
That's awesome. So basically Charcoal has a builtin "roll" operator in⟲?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
@Jonah Well, it won't roll for me as it goes, but by outputting the string character-by-character I can roll as I go, yes.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
Charcoal, 15 bytes
FS«F¬℅§KV⁰⟲⁶→Pι
Try it online! Link is to verbose version of code. Explanation:
FS«
Loop over the carpet.
F¬℅§KV⁰
Check whether there's anything above the cursor.
⟲⁶
If not then roll the carpet.
→Pι
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.
$endgroup$
Charcoal, 15 bytes
FS«F¬℅§KV⁰⟲⁶→Pι
Try it online! Link is to verbose version of code. Explanation:
FS«
Loop over the carpet.
F¬℅§KV⁰
Check whether there's anything above the cursor.
⟲⁶
If not then roll the carpet.
→Pι
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.
edited 2 days ago
answered 2 days ago
NeilNeil
82.6k745179
82.6k745179
$begingroup$
That's awesome. So basically Charcoal has a builtin "roll" operator in⟲?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
@Jonah Well, it won't roll for me as it goes, but by outputting the string character-by-character I can roll as I go, yes.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
That's awesome. So basically Charcoal has a builtin "roll" operator in⟲?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
@Jonah Well, it won't roll for me as it goes, but by outputting the string character-by-character I can roll as I go, yes.
$endgroup$
– Neil
2 days ago
$begingroup$
That's awesome. So basically Charcoal has a builtin "roll" operator in
⟲?$endgroup$
– Jonah
2 days ago
$begingroup$
That's awesome. So basically Charcoal has a builtin "roll" operator in
⟲?$endgroup$
– Jonah
2 days ago
1
1
$begingroup$
@Jonah Well, it won't roll for me as it goes, but by outputting the string character-by-character I can roll as I go, yes.
$endgroup$
– Neil
2 days ago
$begingroup$
@Jonah Well, it won't roll for me as it goes, but by outputting the string character-by-character I can roll as I go, yes.
$endgroup$
– Neil
2 days ago
add a comment |
$begingroup$
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
$endgroup$
add a comment |
$begingroup$
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
$endgroup$
add a comment |
$begingroup$
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
$endgroup$
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
edited Apr 5 at 14:31
answered Apr 5 at 13:44
SokSok
4,187925
4,187925
add a comment |
add a comment |
$begingroup$
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.
$endgroup$
add a comment |
$begingroup$
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.
$endgroup$
add a comment |
$begingroup$
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.
$endgroup$
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.
edited 2 days ago
answered 2 days ago
ZgarbZgarb
26.6k462230
26.6k462230
add a comment |
add a comment |
$begingroup$
J, 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 , ]
$endgroup$
$begingroup$
Ah, J... letters are for noobs
$endgroup$
– RK.
2 days ago
$begingroup$
,.can do what1 1$]does and$can be used as{..
$endgroup$
– FrownyFrog
2 days ago
$begingroup$
@FrownyFrog ty. I got it to 70 bytes with your first suggestion but wasn't sure if I understood$ can be used as {.-- can you clarify?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
The last line of the explanation, you use {. to truncate, that one can be a $ as far as I understand.
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Also you can replace the right [: with a @
$endgroup$
– FrownyFrog
yesterday
add a comment |
$begingroup$
J, 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 , ]
$endgroup$
$begingroup$
Ah, J... letters are for noobs
$endgroup$
– RK.
2 days ago
$begingroup$
,.can do what1 1$]does and$can be used as{..
$endgroup$
– FrownyFrog
2 days ago
$begingroup$
@FrownyFrog ty. I got it to 70 bytes with your first suggestion but wasn't sure if I understood$ can be used as {.-- can you clarify?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
The last line of the explanation, you use {. to truncate, that one can be a $ as far as I understand.
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Also you can replace the right [: with a @
$endgroup$
– FrownyFrog
yesterday
add a comment |
$begingroup$
J, 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 , ]
$endgroup$
J, 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 , ]
edited yesterday
answered Apr 5 at 17:27
JonahJonah
2,6611017
2,6611017
$begingroup$
Ah, J... letters are for noobs
$endgroup$
– RK.
2 days ago
$begingroup$
,.can do what1 1$]does and$can be used as{..
$endgroup$
– FrownyFrog
2 days ago
$begingroup$
@FrownyFrog ty. I got it to 70 bytes with your first suggestion but wasn't sure if I understood$ can be used as {.-- can you clarify?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
The last line of the explanation, you use {. to truncate, that one can be a $ as far as I understand.
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Also you can replace the right [: with a @
$endgroup$
– FrownyFrog
yesterday
add a comment |
$begingroup$
Ah, J... letters are for noobs
$endgroup$
– RK.
2 days ago
$begingroup$
,.can do what1 1$]does and$can be used as{..
$endgroup$
– FrownyFrog
2 days ago
$begingroup$
@FrownyFrog ty. I got it to 70 bytes with your first suggestion but wasn't sure if I understood$ can be used as {.-- can you clarify?
$endgroup$
– Jonah
2 days ago
1
$begingroup$
The last line of the explanation, you use {. to truncate, that one can be a $ as far as I understand.
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Also you can replace the right [: with a @
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Ah, J... letters are for noobs
$endgroup$
– RK.
2 days ago
$begingroup$
Ah, J... letters are for noobs
$endgroup$
– RK.
2 days ago
$begingroup$
,. can do what 1 1$] does and $ can be used as {..$endgroup$
– FrownyFrog
2 days ago
$begingroup$
,. can do what 1 1$] does and $ can be used as {..$endgroup$
– FrownyFrog
2 days ago
$begingroup$
@FrownyFrog ty. I got it to 70 bytes with your first suggestion but wasn't sure if I understood
$ can be used as {. -- can you clarify?$endgroup$
– Jonah
2 days ago
$begingroup$
@FrownyFrog ty. I got it to 70 bytes with your first suggestion but wasn't sure if I understood
$ can be used as {. -- can you clarify?$endgroup$
– Jonah
2 days ago
1
1
$begingroup$
The last line of the explanation, you use {. to truncate, that one can be a $ as far as I understand.
$endgroup$
– FrownyFrog
yesterday
$begingroup$
The last line of the explanation, you use {. to truncate, that one can be a $ as far as I understand.
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Also you can replace the right [: with a @
$endgroup$
– FrownyFrog
yesterday
$begingroup$
Also you can replace the right [: with a @
$endgroup$
– FrownyFrog
yesterday
add a comment |
$begingroup$
R, 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
}
$endgroup$
add a comment |
$begingroup$
R, 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
}
$endgroup$
add a comment |
$begingroup$
R, 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
}
$endgroup$
R, 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
}
edited Apr 5 at 14:32
answered Apr 5 at 13:45
GiuseppeGiuseppe
17.6k31153
17.6k31153
add a comment |
add a comment |
$begingroup$
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
$endgroup$
add a comment |
$begingroup$
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
$endgroup$
add a comment |
$begingroup$
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
$endgroup$
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
answered Apr 5 at 18:47
Jonathan AllanJonathan Allan
54k535174
54k535174
add a comment |
add a comment |
$begingroup$
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!
$endgroup$
$begingroup$
sadly, op says you have to print
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
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!
$endgroup$
$begingroup$
sadly, op says you have to print
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
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!
$endgroup$
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!
answered 2 days ago
PieCotPieCot
97959
97959
$begingroup$
sadly, op says you have to print
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
sadly, op says you have to print
$endgroup$
– ASCII-only
yesterday
$begingroup$
sadly, op says you have to print
$endgroup$
– ASCII-only
yesterday
$begingroup$
sadly, op says you have to print
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
Python 3, 124 bytes
r=lambda t,h=[]:len(h)>len(t)and h[:-1]+[h[-1]+list(t)]or r(t[max(len(h),1):],list(zip(*h[::-1]))+[list(t)[:max(len(h),1)]])
Try it online!
$endgroup$
$begingroup$
need to print it
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
Python 3, 124 bytes
r=lambda t,h=[]:len(h)>len(t)and h[:-1]+[h[-1]+list(t)]or r(t[max(len(h),1):],list(zip(*h[::-1]))+[list(t)[:max(len(h),1)]])
Try it online!
$endgroup$
$begingroup$
need to print it
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
Python 3, 124 bytes
r=lambda t,h=[]:len(h)>len(t)and h[:-1]+[h[-1]+list(t)]or r(t[max(len(h),1):],list(zip(*h[::-1]))+[list(t)[:max(len(h),1)]])
Try it online!
$endgroup$
Python 3, 124 bytes
r=lambda t,h=[]:len(h)>len(t)and h[:-1]+[h[-1]+list(t)]or r(t[max(len(h),1):],list(zip(*h[::-1]))+[list(t)[:max(len(h),1)]])
Try it online!
answered 2 days ago
PieCotPieCot
97959
97959
$begingroup$
need to print it
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
need to print it
$endgroup$
– ASCII-only
yesterday
$begingroup$
need to print it
$endgroup$
– ASCII-only
yesterday
$begingroup$
need to print it
$endgroup$
– ASCII-only
yesterday
add a comment |
$begingroup$
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. inputcarpetis $[0,6,4,2]$ instead and input0123456789ABCDEFGHIis $[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.
$endgroup$
add a comment |
$begingroup$
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. inputcarpetis $[0,6,4,2]$ instead and input0123456789ABCDEFGHIis $[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.
$endgroup$
add a comment |
$begingroup$
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. inputcarpetis $[0,6,4,2]$ instead and input0123456789ABCDEFGHIis $[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.
$endgroup$
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. inputcarpetis $[0,6,4,2]$ instead and input0123456789ABCDEFGHIis $[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.
answered 17 hours ago
Kevin CruijssenKevin Cruijssen
42.4k570217
42.4k570217
add a comment |
add a comment |
If this is an answer to a challenge…
…Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.
…Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
Explanations of your answer make it more interesting to read and are very much encouraged.…Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.
More generally…
…Please make sure to answer the question and provide sufficient detail.
…Avoid asking for help, clarification or responding to other answers (use comments instead).
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f182727%2froll-the-carpet%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
$begingroup$
Closely related
$endgroup$
– Giuseppe
Apr 5 at 12:59
2
$begingroup$
Also this one: codegolf.stackexchange.com/questions/125966/…, but none include the termination check.
$endgroup$
– Bromind
Apr 5 at 13:03
3
$begingroup$
Suggested test case:
ProgrammingPuzzlesAndCodeGolf- the final tail length greater than 1 tripped me up.$endgroup$
– Sok
Apr 5 at 13:48
$begingroup$
Where is the head on the second
carpetexample, where nothing is rolled up?$endgroup$
– Embodiment of Ignorance
Apr 5 at 15:36
1
$begingroup$
I think you've swapped the words "head" and "tail" here: "if the width of the new head [...] is greater or equal than the length of the tail [...]".
$endgroup$
– Erik the Outgolfer
Apr 5 at 21:08