Rectangle of text

Ruby 112 100

I'm new to Ruby and this is my first code golf. I drew upon memowe's perl implementation and tried to make a Ruby version of it. This is 112 100 characters and assumes you assign a string to x. Looking forward to seeing others.

l=x.size
puts x[0..w=l/2-h=l/4]
1.upto(h-1){|i|puts x[-i]+' '*(w-1)+x[w+i]}
puts x[w+h..l-h].reverse

Edited to implement suggestions. I think it's 100 characters now. Thanks guys!


PostScript 50 binary, 113 ASCII

This uses graphical output. Hexdump of the program using binary tokens:

$ hexdump -C textRect_binary.ps 
00000000  74 5b 30 20 39 5b 74 92  62 34 92 36 92 38 92 10  |t[0 9[t.b4.6.8..|
00000010  32 92 19 5d 7b 92 2c 7b  32 92 19 7d 92 83 92 3e  |2..]{.,{2..}...>|
00000020  92 6e 7d 92 49 5d 39 20  39 92 6b 91 c7 39 92 8e  |.n}.I]9 9.k..9..|
00000030  92 c3                                             |..|
00000032

Download to try it. Using Ghostscript, the to-be-rendered text can be passed to the program as follows:

gs -st=helloworld textRect_binary.ps 

Graphical output looks like this:

rendered output

The same code using ASCII tokens looks like this:

t[0 9[t length
4 div dup
ceiling
2 copy]{cvi{2 copy}repeat
exch neg}forall]9 9 moveto/Courier 9 selectfont
xyshow

The strategy is to use xyshow for defining where we move after showing each character before showing the next character. We're starting in the lower left corner, moving clockwise, i.e. first up, then right, then down then left. We're always moving 9 units, so first we have a relative movement of 0 9, then 9 0, then 0 -9, then -9 0. We can get from one pair of these numbers to the next with the sequence exch neg.

We need to build an array for xyshow that holds these pairs of numbers, one pair for each character. This means, if we have helloworld as example string, which has 10 characters, we want to go up twice, then right thrice, then down twice and left thrice. We get these values (two and three) by dividing the string length by 8, once rounding to the floor, once to the ceiling.

So, we copy 0 9 twice, then switch to the relative x/y coordinates using exch neg, copy those thrice and so on.

This commented code shows what happens on the stack:

t[0 9                % t [ 0 9
[t length            % t [ 0 9 [ length
4 div dup            % t [ 0 9 [ length/4 length/4
ceiling              % t [ 0 9 [ length/4=height width
2 copy]              % t [ 0 9 [height width height width]
{%forall             % t [ 0 9 ... x y height_or_width
  cvi                % t [ 0 9 ... x y height_or_width_integer
  {2 copy}           % t [ 0 9 ... x y height_or_width_integer {2 copy}
  repeat             % t [ 0 9 ... x y .. x y
  exch neg           % t [ 0 9 ... x y .. y -x
}forall]             % t [0 9 ... -9 0]
9 9 moveto/Courier 9 selectfont
xyshow

GolfScript, 56 53 40 38 characters

1/..,4/):l<n@l>{)" "l*2>@(n@.,l-}do-1%

You may test the script online.

Tags:

Code Golf