From: William James Date: 2005-10-14T01:56:54+09:00 Subject: Re: A (minor) coding challenge William James wrote: > rubyhacker@gmail.com wrote: > > This is one of those things that "anyone can do" and it doesn't > > take that long. But it's always fun/educational to see how > > different people would do it. > > > > Given: A text is in two languages (say, English and French) -- > > assume separate files or whatever is convenient. They're > > formatted properly, so that paragraphs correspond to each other > > predictably. We define a "paragraph" as simply a group of non-blank > > lines followed by one or more blank lines or end of file. (Thus > > even a simple title or heading would count.) Assume a page length > > N (lines per page). > > > > Reformat both texts such that: > > > > 1. Corresponding paragraphs start on corresponding lines of the > > page. > > > > 2. If either paragraph is shorter than the other, it will be padded > > with blank lines so that the next paragraphs coincide. > > > > 3. Preserve any "extra" blank lines that were already there > > between paragraphs. > > > > 4. Neither text will allow a page break in the middle of a paragraph. > > If it won't fit in either case, do a page break for both. > > > > 5. If you want to simplify output, represent a page break as "----" > > or the equivalent. > > > > > > I'll be playing at this in my spare minutes. > > > > Let the games begin. > > > > > > Hal > > > Lines_per_page = 60 > > def grab( i ) [ deleted lines ] > > handles.each { |h| h.close } Added a few comments and made improvements. Lines_per_page = 60 # Read and parse a file. def grab( i ) IO.read( ARGV[i] ).split( /^((?:[ \t]*\n)*[ \t]*\n)/ ).map{ |s| s.scan( /.*?\n|.+$/ ) } end texts = grab(0).zip(grab(1)).inject([]){ |arr,pair| m = [ pair.first.size, pair.last.size ].max if pair.first.first =~ /\S/ # Equalize lengths of parallel paragraphs. 2.times { |i| pair[i] += Array.new( m - pair[i].size ) { "" } } arr << pair else # Equalize runs of blank lines and make them breakable. m.times { arr << [ [""], [""] ] } end arr } class Array def page_break each { |handle| handle.puts "----" } end end handles = [] 2.times {|i| handles << File.open( "out-junk#{ i }", "w" ) } count = 0 texts.each { |x| psize = x.first.size # Print paragraph or blank line. if psize > Lines_per_page - count handles.page_break count = 0 end 2.times { |i| handles[i].puts x[i] } count += psize } handles.each { |h| h.close }