2013-03-07 35 views
2

我是编程和ruby的新手。我正在研究处理特定Diophantine方程的代码(来自麻省理工学院opencourseware问题),并且只是看我能用它做些什么。Ruby和丢番图方程 - 哈希问题

该代码针对具有三个变量的特定线性方程生成三个数组和一个散列。

下面的代码:

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任何数。任何帮助?此外,尽管我是新人,但如果有更好的方式来做我做过的任何事情,如果你让我知道,我会很感激。

回答

1

这也许应该是:

yups_hash = Hash[yups.zip(yups_values)] 

有了,我不知道发生了什么应该是发生的警告,但yups_hash顾名思义它应该是一个哈希,而不是用一堆阵列数组。

一旦有一个实际的哈希输出为20:

0 0 1 

这个定义相匹配,至少。

+0

这将返回错误:'[]':奇数个散列参数(ArgumentError)。我试图对它做一个散列,将x的值与[a,b,c]配对,每个x的值都有一个解,以及每个[a,b,c]的集合,使它们一起满足x的等式。我想收集这些信息,并调用[a,b,c]的哪些变化解决x的相同值的方程。 – qrrr 2013-03-07 21:38:54

+0

@quiet_engine Ruby的哪个版本?对我来说工作得很好。 – 2013-03-07 21:54:58