 # Counting values in an array, storing in a hash then making an array of hashes?

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.

Jen.

totals = Hash.new(0)

arr = [1, 1, 2, 2, 3, 3, 1, 3]

arr.each do |val|
totals[val] += 1
end

p totals

–output:–
{1=>3, 2=>2, 3=>3}

totals = []

arr = [
[1, 2, 3],
[1, 2, 3, 3, 2, 1],
[1, 2, 3, 1, 2, 3, 1, 2, 3]
]

arr.each do |sub_arr|
curr_totals = Hash.new(0)

sub_arr.each do |val|
curr_totals[val] += 1
end

totals << curr_totals
end

p totals

–output:–
[{1=>1, 2=>1, 3=>1}, {1=>2, 2=>2, 3=>2}, {1=>3, 2=>3, 3=>3}]

boards = [
[
[1,1,1],
[1,1,1],
[1,1,1]
],

[
[2,2,2],
[2,2,2],
[2,2,2]
]
]

board_totals = []

boards.each do |this_board|
this_boards_totals = Hash.new(0)

this_board.each do |row|
row.each do |val|
this_boards_totals[val] += 1
end
end

board_totals << this_boards_totals
end

p board_totals

–output:–
[{1=>9}, {2=>9}]

On Mon, Mar 21, 2011 at 9:33 PM, Jen [email protected] wrote:

def fitness_check
count[c] += 1
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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs