Skip to content

Instantly share code, notes, and snippets.

@7even
Created September 14, 2010 20:43
Show Gist options
  • Select an option

  • Save 7even/579740 to your computer and use it in GitHub Desktop.

Select an option

Save 7even/579740 to your computer and use it in GitHub Desktop.
COLS = 3 # кол-во столбцов
# если не указан файл, выводим сообщение и выходим
if ARGV.count == 0
puts 'specify a file to output'
exit
end
begin
words = IO.readlines(ARGV[0]).each { |word| word.strip! }.sort
rescue Errno::ENOENT
puts 'file "' + ARGV[0] + '" not found!'
exit
end
width = words.max_by { |word| word.length }.length # максимальная длина слова, определяем для ширины столбцов
full_rows = words.length / COLS # кол-во рядов со словами во всех столбцах
last_row = words.length % COLS # кол-во слов в последнем ряду
# собираем количество слов в каждом столбце
columns = []
COLS.times do |col|
if col < last_row
columns[col] = full_rows + 1
else
columns[col] = full_rows
end
end
# собираем итоговый массив
output = []
columns.each_with_index do |col, ind|
col.times do |row|
(output[row] ||= []).push(words.shift)
end
end
# и выводим его
output.each do |row|
puts row.collect { |word| sprintf("%-#{width}s", word) }.join(' ')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment