From: Morton Goldberg Date: 2007-09-13T14:34:35+09:00 Subject: Re: Filling individual cells in a grid On Sep 12, 2007, at 5:36 PM, Morton Goldberg wrote: > I ran the script for three iterations. I'm not sure how to > interpret the results. I'm not even sure it the loop is converging. > I leave it to you to work that out. It may be working as you expect > it to, it may be that your scoring function needs adjustment, or > may be that there's a bug in my code. One thought that occurs to > me: would it be better to start out with a random distribution of > housing and green space? Well, I made some minor changes so I test for convergence, and I found that it does converge and fairly quickly at that. I reach a fixed point in on the 7th iteration. Here is the modified code and the results. Hope it's what you expected. limit = 10 limit.times do |n| swaps = 0 grid.each_with_remaining do |cell, other| next if cell.cell_type == other.cell_type cn, on = neighbors(cell), neighbors(other) before_score = score(cell.cell_type, cn) + score(other.cell_type, on) after_score = score(other.cell_type, cn) + score(cell.cell_type, on) if after_score < before_score # <-- note change from <= to < cell.cell_type, other.cell_type = other.cell_type, cell.cell_type swaps += 1 end end puts "Iteration no. #{n+1}" grid.print_field_values puts break if swaps == 0 end Iteration no. 7 02 02 02 02 02 02 02 03 02 01 02 03 02 03 02 03 02 03 02 01 02 03 03 03 03 03 02 03 02 01 02 02 02 02 02 02 02 02 02 01 02 02 02 02 02 02 02 03 02 01 03 03 03 03 03 03 03 03 03 01 03 03 03 03 03 03 02 03 02 01 02 02 02 02 02 02 02 02 02 01 02 02 02 02 02 02 02 03 02 01 03 02 03 02 03 02 03 03 03 01 03 03 03 03 03 03 02 03 02 01 03 02 03 02 03 02 02 02 02 01 02 02 02 02 02 02 02 03 02 01 02 02 03 02 03 02 03 02 03 01 03 03 03 03 03 03 02 03 02 01 03 02 03 02 03 02 03 02 02 01 02 02 02 02 02 02 02 03 02 01 02 02 03 02 03 02 02 02 02 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 02 02 02 02 02 02 03 02 02 01 02 03 02 03 02 03 02 03 02 01 03 02 03 02 03 02 03 02 03 01 02 03 02 03 02 03 02 03 02 01 02 02 03 02 03 02 03 02 02 01 02 03 02 03 02 03 02 03 02 01 03 02 03 02 03 02 03 02 03 01 02 03 02 03 02 03 02 03 02 01 02 02 03 02 03 02 03 02 02 01 02 03 02 03 02 03 02 03 02 01 Regards, Morton