昔の英文ワープロ(monospace font で,単語間に空白を挿入して右端を揃える)
昔,FORTRAN で実機を使わずにプログラムしたことがあったなぁ~
func = function(s, w) {
func2 = function(s) {
n = length(s)
len = sum(sapply(s, nchar))
spaces = w - len
left.part.spaces = spaces%/%(n - 1)
left.part.words = n - 1 - spaces%%(n - 1)
if (left.part.words == n - 1) {
left.part.words = left.part.words + 1
}
sp = paste(rep(" ", left.part.spaces+1), collapse = "")
s2 = paste(s[1:left.part.words], collapse = substr(sp, 2, nchar(sp)))
if (n > left.part.words) {
s3 = paste(s[(left.part.words + 1):n], collapse = sp)
s2 = paste(s2, s3, sep = substr(sp, 2, nchar(sp)))
}
s2
}
s = unlist(strsplit(s, " "))
repeat {
len = 0
n.words = length(s)
for (i in 1:n.words) {
len = len + nchar(s[i]) + 1
if (len == w + 1) {
cat(sprintf("%s\n", paste(s[1:i], collapse = " ")))
s = s[-(1:i)]
break
} else if (len > w + 1) {
cat(sprintf("%s\n", func2(s[1:(i - 1)])))
s = s[-(1:(i - 1))]
break
}
}
if (i == n.words) {
cat(sprintf("%s\n", paste(s, collapse = " ")))
break
}
}
}
###### テスト
s = "One child, one teacher, one book and one pen can change the world. Education is the only solution. Education first."
for (w in 20:30) {
func(s, w)
}