rubyhashdiophantine

Ruby and Diophantine equations--hash issues


I'm new to programming and ruby. I'm working on code that deals with a specific Diophantine equation (from an MIT opencourseware problem), and just kind of seeing what I can do with it.

The code produces three arrays and a hash of two of them for a particular linear equation with three variables.

Here's the code:

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)

What I'm trying to do now is access the individual hash pairings to make sure they are lining up right, but

puts yups_hash[] 

returns nil for any number. Any help? Also, being new as I am, if there are better ways to do anything I've done, I'd appreciate it if you let me know.


Solution

  • It should probably be:

    yups_hash = Hash[yups.zip(yups_values)]
    

    With the caveat that I don't know what's supposed be happening, but the yups_hash name implies it should be a hash, not an array with a bunch of arrays in it.

    Once there's an actual hash the output for 20 is:

    0 0 1
    

    This matches the definition, at least.