-
Notifications
You must be signed in to change notification settings - Fork 30
/
full_justify_text.rb
61 lines (54 loc) · 1.23 KB
/
full_justify_text.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def full_justify(words, max_width)
return [] if words.size<1
lines=[]
line=[]
curLen=0
words.each do |w|
if curLen==0
line<<w
curLen=w.length
elsif curLen+1+w.length<=max_width
curLen+=w.length+1
line<<w
else
lines<<addSpace(line.dup, max_width)
line.clear
line<<w
curLen=w.length
end
end
(line.size-1).times { |i| line[i]+=' ' }
line=line.join
while line.length<max_width
line+=" "
end
lines<<line
end
def addSpace(line, max_len)
if line.size==1
while line[0].size<max_len
line[0]+=" "
end
return line[0]
end
len=0
line.each { |w| len+=w.length }
spaceCount=line.size-1
longSpace=""
((max_len-len)/spaceCount).times do
longSpace+=" "
end
remain=max_len-len-(max_len-len)/spaceCount*spaceCount
(line.size-1).times { |i| line[i]+=longSpace }
i=0
remain.times { line[i]=line[i]+' ';i+=1 }
line.join
end
w=["This", "is", "an", "example", "of", "text", "justification."]
p full_justify w, 16
w=[""]
p full_justify w, 0
w=["a", "b", "c", "d", "e"]
p full_justify w, 1
p full_justify(["Listen", "to", "many,", "speak", "to", "a", "few."], 6)
p full_justify(["Here","is","an","example","of","text","justification."], 16)