Ruby はこれに最適な言語ではないかもしれませんが、私は自分の端末でこれを使用することに少し慣れているので、それを使用しています。
1 から 666666 までの数字を処理する必要があるため、6 を含み 7、8、9 を含まないすべての数字をピンで留めます。最初の数字は6
、次16
は 、というようになり26
ます。次に、このように印刷する必要があり(6=6) (16=6) (26=6)
、範囲がある場合は(SPSS構文)のように印刷60
する66
必要があります。(60 THRU 66=6)
私はこのコードを持っていて動作しますが、美しくも効率的でもありません。どうすれば最適化できますか?
(ばかげたコードが続くかもしれません)
class Array
def to_ranges
array = self.compact.uniq.sort
ranges = []
if !array.empty?
# Initialize the left and right endpoints of the range
left, right = array.first, nil
array.each do |obj|
# If the right endpoint is set and obj is not equal to right's successor
# then we need to create a range.
if right && obj != right.succ
ranges << Range.new(left,right)
left = obj
end
right = obj
end
ranges << Range.new(left,right) unless left == right
end
ranges
end
end
write = ""
numbers = (1..666666).to_a
# split each number in an array containing it's ciphers
numbers = numbers.map { |i| i.to_s.split(//) }
# delete the arrays that doesn't contain 6 and the ones that contains 6 but also 8, 7 and 9
numbers = numbers.delete_if { |i| !i.include?('6') }
numbers = numbers.delete_if { |i| i.include?('7') }
numbers = numbers.delete_if { |i| i.include?('8') }
numbers = numbers.delete_if { |i| i.include?('9') }
# join the ciphers back into the original numbers
numbers = numbers.map { |i| i.join }
numbers = numbers.map { |i| i = Integer(i) }
# rangify consecutive numbers
numbers = numbers.to_ranges
# edit the ranges that go from 1..1 into just 1
numbers = numbers.map do |i|
if i.first == i.last
i = i.first
else
i = i
end
end
# string stuff
numbers = numbers.map { |i| i.to_s.gsub(".."," thru ") }
numbers = numbers.map { |i| "(" + i.to_s + "=6)"}
numbers.each { |i| write << " " + i }
File.open('numbers.txt','w') { |f| f.write(write) }
私が言ったように、それは数百万の数でも機能しますが、より美しく効率的にする方法についてアドバイスをお願いします.