2

我是编程和红宝石的新手。我正在编写处理特定丢番图方程的代码(来自 MIT 开放课件问题),并且只是想看看我能用它做什么。

该代码为具有三个变量的特定线性方程生成三个数组和其中两个的散列。

这是代码:

def diophantine_solutions(x)
  #For all x > 1, finds values for a, b, c such that 6a + 9b + 20c = x,
  #Creates array of solvable x, unsolvable x, 
  #Creates hash of solvable x with possible values of a, b, c

  nopes=(1..x).to_a #will contain sums with no solutions at the end
  yups=[] #has solvalbes
  yups_values=[] #solutions for a, b, c
  yups_hash={} #sums with the solutions

  while x>0
    for a in (0..x/6):
      for b in (0..x/9):
        for c in (0..x/20):
          total=6*a + 9*b + 20*c
          if total==x
            yups<< x
            yups_values<< [a, b, c]
          end          
        end
      end
    end
    x=x-1
  end

  yups_hash=[yups.zip(yups_values)]
  yups=yups.uniq
  nopes=nopes-yups
  puts yups_hash[20]
end

diophantine_solutions(20)

我现在要做的是访问各个哈希配对以确保它们正确排列,但是

puts yups_hash[] 

对任何数字返回 nil。有什么帮助吗?另外,像我这样的新手,如果有更好的方法来做我所做的任何事情,如果你让我知道,我将不胜感激。

4

1 回答 1

1

应该是:

yups_hash = Hash[yups.zip(yups_values)]

需要注意的是,我不知道会发生什么,但顾名思义,它应该是一个哈希,而不是一个包含一堆数组的数组yups_hash

一旦有一个实际的哈希值,20 的输出是:

0 0 1

这至少符合定义。

于 2013-03-07T20:20:00.853 回答