Snakify a String
Ruby, 87 bytes
->s,n{p=0
a=(' '*(w=s.size)+$/)*n
w.times{|i|a[p]=s[i];p+=[w+1,1,-w-1,1][i/(n-1)%4]}
a}
Some minor abuse of the rule Trailing spaces on each line are allowed.
Each line of output is w
characters long, plus a newline, where w
is the length of the original string, i.e. long enough to hold the whole input. Hence there is quite a lot of unnecessary whitespace to the right for large n
.
Ungolfed in test program
f=->s,n{
p=0 #pointer to where the next character must be plotted to
a=(' '*(w=s.size)+$/)*n #w=length of input. make a string of n lines of w spaces, newline terminated
w.times{|i| #for each character in the input (index i)
a[p]=s[i] #copy the character to the position of the pointer
p+=[w+1,1,-w-1,1][i/(n-1)%4] #move down,right,up,right and repeat. change direction every n-1 characters
}
a} #return a
puts $/,f['a',3]
puts $/,f['Hello,World!',3]
puts $/,f['ProgrammingPuzzlesAndCodeGolf',4]
puts $/,f['IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.',5]
puts $/,f['!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',10]
Pyth, 48 45 44 43 42 bytes
=Y0juXGZX@G~+Z-!J%/HtQ4q2J~+Y%J2@zHlzm*;lz
Try it online.
This approach does the same trailing whitespace abuse as the Ruby answer.
JavaScript (ES6), 143 bytes
(s,n)=>[...s].map((c,i)=>(a[x][y]=c,i/=n)&1?y++:i&2?x--:x++,a=[...Array(n--)].map(_=>[]),x=y=0)&&a.map(b=>[...b].map(c=>c||' ').join``).join`\n`
Where \n
represents a literal newline. Ungolfed:
function snakify(string, width) {
var i;
var result = new Array(width);
for (i = 0; i < width; i++) result[i] = [];
var x = 0;
var y = 0;
for (i = 0; i < string.length; i++) {
result[x][y] = string[i];
switch (i / (width - 1) & 3) {
case 0: x++; break;
case 1: y++; break;
case 2: x--; break;
case 3: y++; break;
}
for (i = 0; i < width; i++) {
for (j = 0; j < r[i].length; j++) {
if (!r[i][j]) r[i][j] = " ";
}
r[i] = r[i].join("");
}
return r.join("\n");
}