Ruby 可能不是最适合的语言,但我对在终端中使用它感到很自在,所以这就是我要使用的。
我需要处理从 1 到 666666 的数字,因此我将所有包含 6 但不包含 7、8 或 9 的数字都固定出来。第一个数字是6
,下一个16
,然后26
等等。然后我需要像这样打印它(6=6) (16=6) (26=6)
,当我有像这样的范围时60
,66
我需要像这样打印(60 THRU 66=6)
(SPSS 语法)。
我有这段代码,它可以工作,但它既不美观也不高效,那么我该如何优化它呢?
(可能会出现愚蠢的代码)
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) }
正如我所说,它适用于数以百万计的数字 - 但我想要一些关于如何使更漂亮和更高效的建议。