From: Morton Goldberg Date: 2007-09-07T05:47:56+09:00 Subject: Re: Filling individual cells in a grid On Sep 6, 2007, at 11:38 AM, Joop Van den tillaart wrote: > hi thanks for your help, You're welcome. > im not sure what you meant with your comments but i will look into > them...again thanks. I'm trying to keep you from shooting yourself in the foot :) > And my goal for filling the cells is as you say...the remaining cells > just have to be filled with say 60% type 2 en the remaining 40% of > cells > with type 3. This can be done random or just first 60% type2 and the > other type 3. > > When this is completed i need to make an algorithm that starts > swapping > celltypes depending on neighbour cells and distances to other > cells...i > won't go to deep into this but it doesn't matter how the cells in the > first stage are filled...just the types 1 are on a own place because > they characterize a road which is laid in before the algorithm starts > swapping... > > So can anyone tell how to define the first 60% as type 2 and the > remaining cells with type 0 to type 3?? require 'ostruct' class Grid include Enumerable def initialize(width, height) @grid = Array.new(height) do |row| Array.new(width) do |col| OpenStruct.new(:x => col, :y => row, :grid => self) end end end def width @grid.first.size end def height @grid.size end def each @grid.each do |row| row.each do |cell| yield cell end end end def [](x, y) @grid[y][x] if @grid[y] end def print_field_values(field_name = :cell_type) each_with_index do |cell, i| print "%02d " % cell.send(field_name) puts if i % width == width - 1 end end end grid = Grid.new(20, 15) grid.each { |cell| cell.cell_type = 0 } grid.height.times { |y| grid[19,y].cell_type = 1 } grid.height.times { |y| grid[9,y].cell_type = 1 } grid.width.times { |x| grid[x,9].cell_type = 1 } grid.each do |cell| if cell.cell_type == 1 cell.distance_road = 0 cell.locked = true end end zero_cells = grid.select { |cell| cell.cell_type == 0 } n = (0.6 * zero_cells.size).round zero_cells[0..n-1].each { |cell| cell.cell_type = 2 } zero_cells[n..-1].each { |cell| cell.cell_type = 3 } grid.print_field_values Regards, Morton