From: Robert Klemme Date: 2011-03-23T21:11:02+09:00 Subject: Re: Counting values in an array, storing in a hash then making an array of hashes? On Mon, Mar 21, 2011 at 9:33 PM, Jen wrote: > Hello, > > Apologies but i've run in to another problem while attempting to make a > sudoku solver that uses basic genetic programming. > > This time I'm trying to count how many times each number occures in each > board (boards stored in @offspring) then store the results in a hash. > > I think each hash is being overwritten because the keys are the same, so I'm > attempting to store an array of hashes. > > I think I'm close, but my logic is still a bit off, as the length of my > array of hashes is 1 but I expect it to be 4, with each element containing a > hash. 4 is the size of the test population I am using, so there are 4 boards > in @offspring. > > I could have probably done the same thing with an array, but I confused > myself thinking about it :( > > My code so far: > > def fitness_check > hashes = Array.new > count = Hash.new 0 > #Adds another loop to ensure all elements of offspring are checked > separetly. > i = 0 > #loop through every row of offspring (first to fourth element) > @offspring[i.to_i].each do |r| > #loop through every column of every row > r.each do |c| > #Count the numbers in each column > count[c] += 1 > hashes[i] = count > end > end > > #Need to stop the values in count getting overwritten by the next element in > @offspring > puts hashes.inspect > puts hashes.length > end > > Thanks in advance for any suggestions. I'm not 100% positive that this is what you want, but it looks suspiciously like what 7stud posted so here we go: def fitness_check # loop to ensure all elements of offspring are checked separetly. hashes = @offspring.map do |board| Hash.new(0).tap do |count| # loop through every row of offspring (first to fourth element) board.each do |r| # loop through every column of every row r.each do |c| # Count the numbers in each column count[c] += 1 end end count end end # debug output puts hashes.length p hashes end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/