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任何数。任何帮助?此外,尽管我是新人,但如果有更好的方式来做我做过的任何事情,如果你让我知道,我会很感激。
这将返回错误:'[]':奇数个散列参数(ArgumentError)。我试图对它做一个散列,将x的值与[a,b,c]配对,每个x的值都有一个解,以及每个[a,b,c]的集合,使它们一起满足x的等式。我想收集这些信息,并调用[a,b,c]的哪些变化解决x的相同值的方程。 – qrrr 2013-03-07 21:38:54
@quiet_engine Ruby的哪个版本?对我来说工作得很好。 – 2013-03-07 21:54:58