Align lists like coreutils' `ls`

Bash, 48 46 bytes

cd `mktemp -d`
xargs -d\\n tee
stty cols $1
ls

Guaranteed to work like ls.


GolfScript, 79 characters

n%:I{)I/{{,}$-1=,}:L%{2++}*"#{ARGV[0]}"~)<}I,,?)/{.L{:x' '*+x<}+%}%zip{'  '*n}/

Assumes a two spaces between the columns (although it can be changed easily to one which saves 2 characters).


Python 3 (394)

Feels longish, but works and isn't horrible to read;

import sys,math
f=sys.stdin.read().splitlines()
l,w=len(f),int(sys.argv[1])
for y in range(w,0,-1):
 n=math.ceil(l/y)
 r=[f[i:l:n]for i in range(0,n)]
 c=[max(len(s[i]) if i<len(s) else 0 for s in r) for i in range(y)]
 if sum(c)+len(c)*2-2<=w:break
for i in range(len(r)):
 s=len(r[i])
 for j in range(s):
  t=r[i][j]
  sys.stdout.write(t+(' '*(c[j]-len(t)+2) if j<s-1 else '\n'))

Basically it tries with fewer and fewer columns until they all fit. It will always output at least one column even if the file names won't fit the width.

Tags:

Code Golf