Ruby中的数字运算需要优化

问题描述

| Ruby可能不是最佳的语言,但是我很愿意在终端中使用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) }
正如我说的那样,它甚至可以用于数以百万计的数字-但是我想就如何使自己更漂亮,更高效提供一些建议。     

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)