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