我是编程和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。有什么帮助吗?另外,像我这样的新人,如果有更好的方法来做我做过的任何事情,如果你让我知道,我将不胜感激。
发布于 2013-03-08 04:20:01
它可能应该是:
yups_hash = Hash[yups.zip(yups_values)]需要注意的是,我不知道发生了什么,但是yups_hash的名称意味着它应该是一个哈希,而不是一个包含一堆数组的数组。
一旦有了实际的散列,20的输出是:
0 0 1这至少符合定义。
https://stackoverflow.com/questions/15280689
复制相似问题