# 1P5: Nested boxes

This task is part of the First Periodic Premier Programming Puzzle Push.

You get a hierarchy of items in the following format:

2
Hat
1
Gloves

which need to be put in boxes, like so:

.------------.
| Hat        |
| .--------. |
| | Gloves | |
| '--------' |
'------------'

In the input format the numbers start a box with as many items as the number specifies. The first box has two items in it (the Hat and the box that contains the Gloves), the second one only contains a single item – the gloves.

As can be seen, boxes can live inside boxes, too. And they are always rounded ... sort of (pointy corners are a wound hazard and we wouldn't want that).

Below there are the nasty details for those that want to utilize every tiny bit of leeway the specification gives. Mind you, not reading the spec is no excuse for submitting wrong solutions. There is a test script and a few test cases at the very end.

Specification

• Boxes are constructed from the following characters:

• | (U+007C) is used to construct the vertical edges.
• - (U+002D) is used to construct the horizontal edges.
• ' (U+0027) are the round lower corners.
• . (U+002E) are the round upper corners.

A box therefore looks like this:

.--.
|  |
'--'

Note that while Unicode also has round corners and proper box-drawing characters, this task is in ASCII only. As much as I love Unicode I realize that there are languages and environments out there that didn't quite arrive in the second to last decade.

• Boxes can contain a sequence of items that are either text or other items. Individual items in a box are rendered from top to bottom. The sequence A, B, C thus renders as follows:

.---.
| A |
| B |
| C |
'---'

This of course applies to nested boxes too, which are an item just like text. So the sequence A, B, Box(C, Box(D, E)), F would render as follows:

.-----------.
| A         |
| B         |
| .-------. |
| | C     | |
| | .---. | |
| | | D | | |
| | | E | | |
| | '---' | |
| '-------' |
| F         |
'-----------'

• Boxes adjust their size to the content and nested boxes always extend to the size of their parent. There is always a space before and after the content, so that neither text nor nested boxes are too close to the outer box' edge. In short, the following is wrong:

.---.
|Box|
'---'

And the following is correct:

.-----.
| Box |
'-----'

Looks much nicer, too :-)

• Text items (see Input below) have to be reproduced exactly.

• There is always a single top-level box (cf. XML). However, one box can contain several other boxes.

Input

• Input is given on standard input; for easier testing likely redirected from a file.

• The input is given line-wise, with each line representing either a text item to put in the current box or opening a new box.

• Every line is terminated by a line break.

• Text items are marked by a line that does not consist of a number (see below). Text uses alphabetic characters, the space and punctuation (.,-'"?!()). Text will not start or end with a space and it will always have at least one character.

• A box starts with a single line with a number in it. The number tells the size of the box, i.e. the number of following items that are put into it:

2
A
B

yields a box with two text items:

.---.
| A |
| B |
'---'

A box will always contain at least one item.

• The end of boxes is not explicitly marked with a line; instead boxes are implicitly closed after the specified number of items are put into them.

• A box is always just a single item, regardless how many items are in it. E.g.

3
A
4
a
b
c
d
B

will yield a box with three items, the second of which is another box with four items.

Nesting also does not affect the fact that a box is just a single item.

Limits

• The maximum nesting level is five. I.e. there are at most five boxes inside of each other. This includes the outermost one.

• There is a maximum of ten items per box.

• Text items have a maximum length of 100 characters.

Output

• Output is the rendered box including all containing and nested items according to the rules outlined above.
• Output should be given on standard output and it has to match exactly. No leading or trailing whitespace is allowed.
• Each line must be terminated with a line break, including the last.

Winning condition

• Shortest code wins (i.e. gets the accepted answer).

Sample input 1

3
This is some text!
Oh, more text?
Just text for now, as this is a trivial example.

Sample output 1

.--------------------------------------------------.
| This is some text!                               |
| Oh, more text?                                   |
| Just text for now, as this is a trivial example. |
'--------------------------------------------------'

Sample input 2

4
Extreme
nesting
3
of
boxes
4
might
to
2
interesting
1
visuals.
Indeed!

Sample output 2

.--------------------------.
| Extreme                  |
| nesting                  |
| .----------------------. |
| | of                   | |
| | boxes                | |
| | .------------------. | |
| | | might            | | |
| | | lead             | | |
| | | to               | | |
| | | .--------------. | | |
| | | | interesting  | | | |
| | | | .----------. | | | |
| | | | | visuals. | | | | |
| | | | '----------' | | | |
| | | '--------------' | | |
| | '------------------' | |
| '----------------------' |
| Indeed!                  |
'--------------------------'

Sample input 3

1
1
1
1
1
Extreme nesting Part Two

Sample output 3

.------------------------------------------.
| .--------------------------------------. |
| | .----------------------------------. | |
| | | .------------------------------. | | |
| | | | .--------------------------. | | | |
| | | | | Extreme nesting Part Two | | | | |
| | | | '--------------------------' | | | |
| | | '------------------------------' | | |
| | '----------------------------------' | |
| '--------------------------------------' |
'------------------------------------------'

Sample input 4

3
Foo
2
Bar
Baz
2
Gak
1
Another foo?

Sample output 4

.----------------------.
| Foo                  |
| .------------------. |
| | Bar              | |
| | Baz              | |
| '------------------' |
| .------------------. |
| | Gak              | |
| | .--------------. | |
| | | Another foo? | | |
| | '--------------' | |
| '------------------' |
'----------------------'

Test Script

Since getting details right can be difficult at times we (Ventero and me) have prepared a test script you can run your solution with to check whether it's correct. It's available as both a PowerShell script and a bash script. Invocation is: <test-script> <program invocation>.

UPDATE: The test scripts have been updated; there were a number of test cases that did not honor the limits I defined. The PowerShell test script did not use case-sensitive comparison for checking the result. I hope everything is fine now. The number of test cases was reduced to 156, although the last one now is quite ... large.

UPDATE 2: I uploaded my test-case generator. Written in C#, targeting the .NET 2 runtime. It runs on Mono. It may help people to test their implementation. As a definitive worst-case given the limits in the task you can try:

nb.exe 1 10 10 5 100 100 | my invocation

which will generate only boxes up to the innermost level and utilize both the maximum number of items per box and the maximum length of text items. I didn't include this test case into the test script, though, since it's quite large and the output even larger.

UPDATE 3: I updated the PowerShell test script which was prone to throw errors depending on how the line endings were in the script and what line endings the solution printed. Now it should be agnostic to both. Sorry again for the confusion.

• You say boxes should adjust their size to their content. Yet in the last example, the first inner box adjusts it's size to the outer box. So, how do nested boxed get their size?
– Juan
Apr 27, 2011 at 21:58
• @Juan: Thanks for catching that. Amazing that slips like those still happen. Edited :-)
– Joey
Apr 27, 2011 at 22:00
• @Joey An oldy but a goody. Hopefully it can inspire some of our newer users to write good, well-specified questions. :-) Mar 4, 2014 at 14:25
• @Gareth, I should definitely try to find the time to write more of those again. But a well-specified question, test cases, reference implementation and stuff (things I consider essential for a competition, but that view isn't shared by many ;)) take time. It was much easier while in uni :D
– Joey
Mar 4, 2014 at 14:37

## Python, 204 chars

def P(n):x=raw_input();return eval('[(n+".","","-")]'+'+P(n+"| ")'*int(x))+[(n+"'",'','-')]if'0'<x<':'else[(n,x,' ')]
r=P('')
for q,t,f in r:print q+t+f*(max(len(2*x+y)for x,y,a in r)-len(2*q+t))+q[::-1]

P returns a list of triples, each of which is a line prefix/suffix (the suffix being the reverse of the prefix), some line text, and a line fill character. After calculating all the triples, they are printed using the right number of fill characters to make all the lines the same length.

Ungolfed version:

def get_lines(prefix):
line=raw_input()
result=[]
if line.isdigit():
result.append((prefix+'.', '', '-'))
for i in xrange(int(line)):
result += get_lines(prefix + '| ')
result.append((prefix+"'", '', '-'))
else:
result.append((prefix, line, ' '))
return result
lines=get_lines('')
width=max(2*len(prefix)+len(text) for prefix,text,fill in lines)
for prefix,text,fill in lines:
print prefix+text+fill*(width-2*len(prefix)-len(text))+prefix[::-1]
• Whoa, that was quick. And interesting idea with P there.
– Joey
Apr 27, 2011 at 21:47
• Wow, indeed. This is interesting, can you post the ungolfed version? I'd like to understand how the eval bit works. Heh, my ungolfed python solution is 1500+ chars :( Though I take a totally different (and inefficient) approach. Apr 28, 2011 at 0:38
• @Casey: eval is just a golfing shortcut for a loop, it isn't fundamental. I'll post an ungolfed version in a sec... Apr 28, 2011 at 5:20

## Ruby 1.9, 174 characters

r=->l{$*<<(l*2+i=gets.chop).size;/\d/?eval('[l+?.,p=?-,p,'+'*r["| "+l],'*i.to_i+"l+?',p,p]"):[l,i,?\s]} r[""].each_slice(3){|a,b,c|puts a+b+c*($*.max-(a*2+b).size)+a.reverse}

Somewhat similar to Keith's solution.

## APL (78)

{∧/⎕D∊⍨I←⍞:{∆,('-'⍪⍵⍪'-'),∆←'.|'''/⍨1(⊃⍴⍵)1}⍕⍪/{⍵↑[2]⍨⌈/⊃∘⌽∘⍴¨∆}¨∆←∇¨⍳⍎I⋄⍉⍪I}⍬
• whats this i dont even Mar 4, 2014 at 13:32
• I can't get this to run on tio.run to test the solution. Otherwise I'd switch the accepted answer as well.
– Joey
Oct 9, 2018 at 13:57

## Python - 355314 259 chars

w=0
def p(n,l):
global w;f=[(l-1,0)]
for k in' '*n:
i=raw_input()
try:f+=p(int(i),l+1)
except:f+=[(l,i)];w=max(w,4*l+len(i))
return f+[(l-1,1)]
for l,s in p(input(),1):p=w-4*l-2;print'| '*l+(".'"[s]+'-'*p+".'"[s]if s<2 else s+' '*(p+2-len(s)))+' |'*l
• almost a 100 char reduction, good job. Apr 29, 2011 at 2:51

## Ruby 1.9, 229228226223 222

g=->n{(1..n).map{g[Integer l=gets.chop]rescue l}}
w=->b{b.bytesize rescue b.map{|e|w[e]}.max+4}
p=->b,c{r=c-2
[?.+?-*r+?.,*b.map{|i|p[i,c-4]}.flatten.map{|k|"| #{k} |"},?'+?-*r+?']rescue[b.ljust(c)]}
puts p[b=g[1][0],w[b]]

## C, 390366 363 characters

#define F(n)for(int i=n;i--;)
#define H(n,s,a...)F(n)printf(s);printf(a);
#define I(s)H(v,"| ",s)H(l-2,"-",s)J
#define J H(v," |","\n")
S[1<<17][26],N[1<<17],P,a;E(p){int l=strlen(gets(S[p]));if(sscanf(S[p],"%d",N+p))F(N[p])l<(a=E(++P))?l=a:l;return l+4;}R(p,v,l){if(N[p]){I(".")F(N[p])R(++P,v+1,l-4);I("'")}else{H(v,"| ","%-*s",l,S[p])J}}main(){R(P=0,0,E(0)-4);}

Compile with gcc -std=gnu99 -w file.c

Not even close to Keith's version, but hey, it's good ol' C

• Passes only 159 of the 160 tests here.
– Joey
Apr 28, 2011 at 9:01
• Ouch. I think now it's OK. I was forgeting to allocate space for the \0 in the extreme case. Apr 28, 2011 at 9:13
• Looks still the same, Test #142 fails. By the way, the actual extreme case isn't even present as it has 10 MiB input and 78 MiB output. I didn't want the test script to be that large ;-)
– Joey
Apr 28, 2011 at 9:19
• weird, i'm getting 160/160 passed (I meant a string of 100 characters, which isn't present anyway) Apr 28, 2011 at 9:33
• Hm, weird. FreeBSD 8.2-RELEASE #5: Sun Feb 27 10:40:25 CET 2011 with gcc version 4.2.1 20070719 [FreeBSD] on x64 here. I'll take your word for the 160, then :-). And there should be a test case with 100 characters, actually (Tests 143–147).
– Joey
Apr 28, 2011 at 9:47

very functional python, 460 characters

r=range
s=lambda x:isinstance(x,str)
w=lambda x:reduce(max,[len(i)if s(i)else w(i)+4 for i in x])
z=lambda b,x:''.join(b for i in r(x))
def g(n=1):
t=[]
for i in r(n):
x=raw_input('')
try:t+=[g(int(x))]
except:t+=[x]
return t
o=list.append
def y(c,m):
f='| ';h=' |';e=z('-',m+2);a='.'+e+'.';b="'"+e+"'";t=[a]
for i in c:
if s(i):o(t,f+i+z(' ',m-len(i))+h)
else:[o(t,f+j+h)for j in y(i,m-4)]
return t+[b]
x=g()[0];m=w(x);print '\n'.join(y(x,m))
• Hm, this doesn't seem to work for me the | characters aren't spaced correctly. It is very similar to my python solution Apr 28, 2011 at 13:21
• Indeed, does not pass any of the test cases. eordano: We included those so that no one would submit answers that are plain wrong anymore.
– Joey
Apr 28, 2011 at 16:41
• I guess I pasted an old version of the code. Should work now. Sorry about being unprofessional. Apr 29, 2011 at 0:09
• Works for me! Nice solution, I like the functional approach. Apr 29, 2011 at 2:50
• Indeed, works now.
– Joey
Apr 29, 2011 at 15:42

f§(a,b)=(f a,b)
h c=(c,'-',c)
b l=h".":map(\(p,f,q)->("| "++p,f,q++" |"))l++[h"'"]
y[]s z=([(s,' ',"")],z)
y[(n,_)]_ z=b§foldr(\_(l,w)->(l++)§x w)([],z)[1..n]
m(p,_,q)=length$p++q n®a@(p,c,q)=p++replicate(n-m a)c++q++"\n" o(l,_)=l>>=(maximum(map m l)®) main=interact$o.x.lines

While golf'd, the method is pretty straight forward. Only limits are available memory.

## C# -1005 859 852 782 characters

using c=System.Console;using System.Linq;class N{static void Main(){new N();}N(){var i=R();c.WriteLine(i.O(0,i.G().W));}I R(){var s=c.ReadLine();int l=0,i=0;if(int.TryParse(s,out l)){var b=new I(l);for(;i<l;){b.m[i++]=R();}return b;}else{return new I(0,s);}}class P{public int W;public int H;}class I{public I[]m;bool z;string t;public I(int l,string r=""){z=l!=0;m=new I[l];t=r;}public P G(){var s=new P();if(z){var d=m.Select(i=>i.G());s.W=d.Max(y=>y.W)+4;s.H=d.Sum(y=>y.H)+2;}else{s.W=t.Length;s.H=1;}return s;}public string O(int l,int w){if(z){string s=A(l,"."+"-".PadRight(w-2,'-')+"."),e=s.Replace(".","'");foreach(var i in m){s+="\n"+i.O(l+1,w-4);}s+="\n"+e;return s;}else{return A(l,t.PadRight(w));}}}static string A(int l,string o){while(l-->0){o= "| "+o+" |";}return o;}}

I need to take another look at this as I'm sure it can be improved, but this is my initial go third pass at it.

Ungolf'd:

using c=System.Console;
using System.Linq;

class NestedBoxes
{
static void Main()
{
new NestedBoxes();
}
NestedBoxes()
{
c.WriteLine(item.Print(0, item.GetSize().Width));
}
{
int count = 0, i = 0;
if (int.TryParse(line, out count))
{
var box = new Item(count);
for (; i < count;)
{
}
return box;
}
else
{

return new Item(0,line);
}
}
class Size
{
public int Width;
public int Height;
}
class Item
{
public Item[] items;
bool isBox;
string text;
public Item(int size,string word="")
{
isBox = size != 0; items = new Item[size]; text = word;
}
public Size GetSize()
{
var s = new Size();
if (isBox)
{
var sizes = items.Select(i => i.GetSize());
s.Width = sizes.Max(y => y.Width) + 4; s.Height = sizes.Sum(y => y.Height) + 2;
}
else
{
s.Width = text.Length;
s.Height = 1;
}
return s;
}
public string Print(int level, int width)
{
if (isBox)
{
string output = AddLevels(level, "." + "-".PadRight(width - 2, '-') + "."),
bottomLine = output.Replace(".", "'");
foreach (var item in items)
{
output += "\n" + item.Print(level + 1, width - 4);
}
output += "\n" + bottomLine;
return output;
}
}
static string AddLevels(int level, string output)
{
while(level-->0)
{
output = "| " + output + " |";
}
return output;
}
}
• @Joey, yeah, I definitely need to go through it all again. Need to play with the logic to try and cut it down also. Apr 29, 2011 at 15:54
• I'm not familiar with C, but in JS, you can combine multiple var statements to one, like this: var a = 1, b = 2, c = 3;. Can't you do the same thing in C? Apr 29, 2011 at 16:06
• @Nyuszika7H, this is C#, not C. You can't combine implicit var statements like that. You can only combine if they have an explicit type like Joey mentioned using string b="",e="". Apr 29, 2011 at 16:08
• @RebeccaChernoff: I worked on the other guys answer, 689 now. Apr 29, 2011 at 19:13
• @NickLarsen, nice - but I'm not looking. q: I still need some time to go through mine. This was my initial go at logic, I'm sure there are places I can be smarter about the logic, just need time to give it attention. Apr 29, 2011 at 19:19

# PHP, 403388 306 chars

<?b((int)fgets(STDIN),'');foreach($t as$r)echo$r[0].str_pad($r[2],$w-2*strlen($r[0]),$r[1]).strrev($r[0])."\n";function b($c,$p){global$t,$w;$t[]=array($p.".","-");while($c--){if(($d=trim(fgets(STDIN)))>0)b($d,"| ".$p);else$t[]=array("| ".$p," ",$d);$w=max($w,strlen($d.$p.$p)+4);}$t[]=array($p."'","-");}

Ungolfed:

box((int)fgets(STDIN), '');

foreach($table as$row) {
$prefix =$row[0];
$pad =$row[1];
$data =$row[2];
echo $prefix . str_pad($data, ($width - 2*strlen($prefix)), $pad) . strrev($prefix)."\n";
}

function box($count,$prefix) {
global $table,$width;
$table[] = array($prefix.".","-");
while($count--) { if(($data = trim(fgets(STDIN))) > 0) {
box($data, "| ".$prefix);
} else {
$table[] = array("| ".$prefix, " ", $data); }$width = max($width,strlen($data.$prefix.$prefix)+4);
}
$table[] = array($prefix."'","-");
}
?>

I borrowed the prefix-idea from Keith (is that allowed at all?), otherwise this is pretty much as the original. Still couldn't get below 300. Stuck with this. Onwards.

• Well, code is public here in every case, so borrowing ideas is allowed and perhaps even encouraged. I think that is also something that differentiates this site from other, similar ones. As gnibbler one noted we compete and collaborate at the same time.
– Joey
May 6, 2011 at 10:10

## PHP, 806769721653 619 chars

<?php function A($a,$b,$c,&$d){for($e=$b;$e>0;$e--){$f=fgets($a);if(false===$f){return;}$g=intval($f);if(0<$g){$h[]=A($a,$g,$c+1,$d);}else{$f=trim($f);$h[]=$f;$j=strlen($f)+4*$c;if($d<$j){$d=$j;}}}return $h;}$d=0;$h=A(STDIN,intval(fgets(STDIN)),1,&$d);function B($k,$c,$d){$f=str_pad('',$d-4*$c-2,'-',2);return C($k.$f.$k,$c,$d);}function C($f,$c,$d){$f=str_pad($f,$d-4*$c,' ');$f=str_pad($f,$d-2*$c,'| ',0);$f=str_pad($f,$d,' |');return$f;}function D($l,$c,$d){if(!is_array($l)){echo C($l,$c,$d)."\n";return;}echo B('.',$c,$d)."\n";foreach($l as $m){echo D($m,$c+1,$d);}echo B('\'',$c,$d)."\n";}D($h,0,$d);exit(0);?>

Ungolfed version:

<?php
function read_itemgroup($handle,$item_count, $depth, &$width) {

//$items = array(); for($i = $item_count;$i > 0; $i--) {$line = fgets( $handle ); if(false ===$line) {
return;
}

$line_int = intval($line);
if(0 < $line_int) { // nested group$items[] = read_itemgroup($handle,$line_int, $depth + 1,$width);
}
else {
// standalone item
$line = trim($line);
$items[] =$line;

// determine width of item at current depth
$width_at_depth = strlen($line) + 4 * $depth; if($width < $width_at_depth) {$width = $width_at_depth; } } } return$items;
}
$width = 0;$items = read_itemgroup(STDIN, intval(fgets( STDIN )), 1, &$width); //var_dump($items, $width); function render_line($corner, $depth,$width) {
$line = str_pad('',$width - 4 * $depth - 2, '-', 2); // 2 = STR_PAD_BOTH return render_item($corner . $line .$corner, $depth,$width);
}

function render_item($line,$depth, $width) {$line = str_pad($line,$width - 4 * $depth, ' ');$line = str_pad($line,$width - 2 * $depth, '| ', 0); // 0 = STR_PAD_LEFT$line = str_pad($line,$width, ' |');
return $line; } function render($item, $depth,$width) {
if(!is_array($item)) { echo render_item($item, $depth,$width) . "\n";
return;
}
echo render_line('.', $depth,$width) . "\n";
foreach($item as$nested_item) {

## F# - 341 characters

let rec f(x,y)=[
let q,d=Core.int.TryParse l
if q then
yield x+".","",'-',"."+y
for i=1 to d do yield!f(x+"| ",y+" |")
yield x+"'","",'-',"'"+y
else yield x,l,' ',y]
let l=f("","")
for w,x,y,z in l do printfn"%s"(w+x.PadRight(List.max(l|>List.map(fun(w,x,y,z)->2*w.Length+x.Length))-2*w.Length,y)+z)

An F# version of Keith's solution. Lists are immutable by default, so this version stuffs the entire recursive function into a list, returns the list, from which the items are extracted using the for..do loop and a yield!. I couldn't find a way to reverse the prefix concisely, so I just attached the suffix onto the triples.

FYI, the TryParse method returns a double (bool,int).

n/):B;[(~{[B"."+"""-"]B"| "+:B;@@{(.10,`-{[B\" "]\}{~A}if}*B[2>:B"'"+"""-"]\}:A~;].{~;1$++,}%$-1=:§;{~§3$.+3$+,-*+1$-1%++}%n* Using a similar approach as Keith's solution. # Clojure - 480 chars (use '[clojure.contrib.string :only (repeat)])(let [r ((fn p[%](repeatedly % #(let [x (read-line)](try(doall(p(Integer/parseInt x)))(catch Exception e x))))) 1)]((fn z[m,n,o] (let[b #( let[p(dec o)](println(str(repeat p "| ")%(repeat(- m(* 4 p)2)"-")%(repeat p " |"))))](b \.)(doseq[i n](if(seq? i)(z m i(inc o))(println(str(repeat o "| ")i(repeat(- m(count i)(* o 4))" ")(repeat o " |")))))(b \')))((fn w[x](reduce max(map(fn[%](if(seq? %)(+ (w %)4)(count %)))x)))r)(first r) 1)) This is my first Clojure program as well as my first Clojure golf attempt, so, needless to say, this shouldn't be taken as representative of Clojure solutions in general. I'm sure it could be shortened significantly, especially if Keith Randall's method of parsing and building the boxes at once was implemented. • Man, half of this source must be whitespace. And mandatorily so :-). Interesting, though and I wonder whether one will see a Lisp variant win a code golf ;-) – Joey Apr 30, 2011 at 6:17 • I'm sure its possible... though like I said, I'm probably not going to be the one to do it. Apr 30, 2011 at 18:44 ## C# - 472 470 426 422 398 characters using System.Linq;using y=System.Console;class W{static void Main(){var c=new int[5];var s=new string[0].ToList();int n=0,i;var l="";do{try{c[n]=int.Parse(l=y.ReadLine());l=".{1}.";n++;i=1;}catch{l+="{0}";i=0;}G:while(i++<n)l="| "+l+" |";s.Add(l);if(n>0&&--c[n-1]<0){n--;l="'{1}'";i=0;goto G;}}while(n>0);s.ForEach(z=>y.WriteLine(z,l="".PadLeft(s.Max(v=>v.Length)-z.Length),l.Replace(' ','-')));}} • Nice. A goto! By the way, you can omit the parentheses around the lambda arguments z and v, bringing this down to 421. – Joey May 23, 2011 at 19:17 ## Scala - 475 characters object N2 extends App{type S=String;def b(x:List[S],t:Int,s:S,e:S):List[S]={var l=x;o=o:+(s+".-±-."+e+"-");for(i<-1 to t)if(l.head.matches("\\d+"))l=b(l.tail,l.head.toInt,s+"| ",e+" |")else{o=o:+(s+"| "+l.head+"±"+e+" | ");l=l.drop(1)};o=o:+(s+"'-±-'"+e+"-");return l};var o:List[S]=List();val l=io.Source.stdin.getLines.toList;b(l.tail,l.head.toInt,"","");(o map(x=>x.replaceAll("±",x.last.toString*((o sortBy((_:S).length)).last.length-x.length)).dropRight(1)))map println} ## C# 1198 1156 1142 689 671 634 Characters using z=System.Console;using System.Collections.Generic;using System.Linq; class T{bool U;List<T> a=new List<T>();string m;IEnumerable<string>R(int s){if(U){yield return ".".PadRight(s-1,'-')+".";foreach(var e in a.SelectMany(b=>b.R(s-4)))yield return ("| "+e).PadRight(s-e.Length)+" |";yield return "'".PadRight(s-1,'-')+"'";}else yield return m;}int L(){return U?a.Max(x=>x.L())+4:m.Length;} static void Main(){var p=O(int.Parse(z.ReadLine()));z.WriteLine(string.Join("\r\n",p.R(p.L())));} static T O(int n){var k=new T(){U=true};while(n-->0){var l=z.ReadLine();int c;k.a.Add(int.TryParse(l,out c)?O(c):new T{m=l});}return k;}} • Ungolfed version is up on github - github.com/paulduran/CodeGolf Apr 29, 2011 at 6:30 • Joining with \n appears to suffice in the end. – Joey Apr 29, 2011 at 8:23 • Getting rid of the interface freed up a lot of characters, the rest was mostly standard golfing. There is plenty more that can be done here, I would expect this could get below 600. Apr 29, 2011 at 19:12 • Nice work Nick. I suspected the interface was a bit of overkill, to be honest. a simple flag would have sufficed in this situation as u have shown. Apr 30, 2011 at 5:33 ## Pip, 89 bytes (non-competing) (The language is newer than the challenge. Also, I couldn't quite outgolf APL.) Code is 87 bytes, +2 for -rn flags. (z:{I+YPOi{Y{Vz}M,ym:MX#*Y$ALyY'|.s._.sX++m-#_.'|MyY".."J'-X++mALyAL"''"J'-Xm}yALl}i:g)

Try it online!

The function z processes the first item of the input list (g, copied into global variable i so as to be available inside function calls). If this is a number n, it calls itself recursively n times, pads the resulting list of lines to a full rectangle, wraps each line in "| " " |", and adds .---. and '---' lines before returning the new list. If it is a string, it simply converts it to a one-item list and returns it. The final result is printed newline-separated (-n flag). More detail available on request.

• I usually don't have a problem with languages newer than the challenge, especially considering that the problem isn't so trivial that a newly-created language would have operations specifically for solving it :-)
– Joey
Sep 21, 2016 at 8:39
• This fails the fourth sample.
– Joey
Aug 22, 2017 at 15:41

# Java (1369 chars incl. EOLs)

Couldn't leave this without a Java implementation. Java is supposed to be more verbose that the slicks of Python and Ruby, so I went for an elegant, recursive solution.

The idea is a Tree (Graph) of objects (strings and boxes), containing one another starting from a "head" box. As you linearly parse the input file you add strings and boxes to the "current" box and while you are adding the maximum length of the container is adjusted. When a container reaches the amount of predefined items that it can hold you backtrack to the previous container. At the end of the input file, you have a "head" container that already has a "maxLength" calculated, so you simply call its print() method.

import java.io.*;import java.util.*;
public class N{private static String rPad(String s,int l){return s+str(l-s.length(),' ');}
private static String str(int l, char c){StringBuffer sb=new StringBuffer();while(l-->0){sb.append(c);}return sb.toString();}
private static class Box {Box prnt=null;String txt=null;int items;List<Box> c=new ArrayList<Box>();int maxLength=0;
public void print(String prefix,int l,String suffix){if (txt == null){System.out.println(prefix+"."+str(l-2,'-')+"."+suffix);for(Box b:c){b.print(prefix+"| ",l-4," |"+suffix);}System.out.println(prefix+"'"+str(l-2,'-')+"'"+suffix);}else{System.out.println(prefix+rPad(txt,l)+suffix);}}
protected void notify(int l){if (l+4>this.maxLength){this.maxLength=l + 4;if (this.prnt != null){this.prnt.notify(this.maxLength);}}}}

It is really an enjoyable solution to write. I liked the question a lot. As I mentioned earlier, I went for solution elegance not minimalist approach, sadly Java doesn't have Python's print "-"*4 to produce "----" :-)

Here's the ungolfed version:

import java.io.*;
import java.util.*;

public class NestedBoxes
{

private static String rPad ( String s, int l )
{
return s + str(l - s.length(), ' ');
}

private static String str ( int l, char c )
{
StringBuffer sb = new StringBuffer();
while (l-- > 0)
{
sb.append(c);
}
return sb.toString();
}

private static class Box
{

Box parent = null;
String text = null;
int items;
List<Box> contents = new ArrayList<Box>();

int maxLength = 0;

public Box ( Box p, int n )
{
parent = p;
items = n;
if (p != null)
{
}
}

public Box ( Box p, String s )
{
parent = p;
text = s;
if (p != null)
{
p.notify(s.length());
}
}

public void print ( String prefix, int l, String suffix )
{
if (text == null)
{
System.out.println(prefix + "." + str(l - 2, '-') + "." + suffix);
for (Box b : contents)
{
b.print(prefix + "| ", l - 4, " |" + suffix);
}
System.out.println(prefix + "'" + str(l - 2, '-') + "'" + suffix);
}
else
{
System.out.println(prefix + rPad(text, l) + suffix);
}
}

protected void notify ( int l )
{
if (l + 4 > this.maxLength)
{
this.maxLength = l + 4;
if (this.parent != null)
{
this.parent.notify(this.maxLength);
}
}
}
}

public static void main ( String[] args ) throws IOException
{
Box b = null;
String s;
while ((s = in.readLine()) != null)
{
try
{
int n = Integer.parseInt(s);
b = new Box(b, n);
}
catch (NumberFormatException nfe)
{
b = new Box(b, s);
}

{