Transpose a page of text
J (31 40)
f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'
This is a function that takes a string, and returns a string (i.e. a character vector with linefeeds inserted in the right places, and not a matrix.)
Edit: no trailing whitespace on any line.
Test:
f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'
string=:stdin''
I am a text.
Transpose me.
Can you do it?
^D
$string
42
$f string
53
f string
ITC
ra
aan
mn
sy
apo
ou
ts
eed
x o
tm
.ei
.t
?
Python 2.7 (97 79 94 90)
EDIT: Missed the function requirement;
I'm fairly sure this will be improved on since I'm sort of a beginner here, but to start with;
c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))
The code uses a simple split
to split the string into a vector of rows. It then uses map
with a function value as None
(the unity function) and the splat operator to transpose and pad the vector (similar functionality to zip_longest
in Python3)
The rest of the code just maps None
to space, trims and reassembles the matrix to a single string again.
>>> a = 'I am a text.\nTranspose me.\nCan you do it?'
>>> c(a)
'ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n ?'
>>> len("""c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))""")
88
# (+2 since `\n` is considered by `len` to be a single char)
Ruby 111
Golfed:
def f t;s=t.lines;s.map{|l|l.chomp.ljust(s.map(&:size).max).chars}.transpose.map{|l|l.join.rstrip+?\n}.join;end
Ungolfed:
def transpose_text(text)
max_length = text.lines.map(&:size).max
text.lines.map do |line|
line.chomp.ljust(max_length).chars
end.transpose.map do |chars|
chars.join.rstrip + "\n"
end.join
end
Ruby has an array transpose function, so this simply pads the lines out, turns them into an array of characters, uses Ruby's Array#transpose function, then turns the array of characters back into lines.
Golfing it was simply using single-character identifiers, removing spaces, using a temporary for text.lines, and putting the calculation for max_length inline (there are no points for efficiency).