Created
December 4, 2016 11:29
-
-
Save kirill-fedyanin/9639662a67db1ebea313c02659161c97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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