Skip to content

Instantly share code, notes, and snippets.

@kirill-fedyanin
Created December 4, 2016 11:29
Show Gist options
  • Save kirill-fedyanin/9639662a67db1ebea313c02659161c97 to your computer and use it in GitHub Desktop.
Save kirill-fedyanin/9639662a67db1ebea313c02659161c97 to your computer and use it in GitHub Desktop.
def justify(text, width)
words = text.split
rows = split_rows(words, width)
last_row = rows.pop
text = rows.map{|row| justified_row(row, width)}.join("\n")
[text, last_row.join(" ")].join("\n")
end
def justified_row(row, width)
return row.join if row.length < 2
spaces = Array.new(row.length - 1, 0)
(width - row.join("").length).times do |i|
spaces[i % spaces.length] += 1
end
row.inject("") do |row_str, word|
row_str += word + " "*(spaces.shift || 0)
end
end
def split_rows(words, width)
rows = []
row = []
words.each do |word|
if row.join(" ").length + word.length + 1 > width
rows << row
row = []
end
row << word
end
rows << row
end
string = 'В цикле проверяем, что длина текущего и следующего слова не превышает width. Если не превышает, то добавляем его в результатирующую строку. Если превышает, то добавляем новую строку в стек резальтата. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.'
puts justify_text string, 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment