From: "F. Senault" Date: 2011-05-09T16:50:30+09:00 Subject: Re: Index to coordinates conversion, according the matrix shape Le 9 mai 2011 � 00:14, Paul A. a �crit : > But how can we do the opposite? I mean, a method looking like: > > index_to_coordinates([3, 3], 3) # => [0, 1] A small example from a project of mine. Maybe you'll find things of interest (the each method does that conversion, for instance). class Grid include Enumerable attr_reader :width, :height, :depth def initialize(width, height, depth) @width = width @height = height @depth = depth @tiles = Array.new(width * height * depth) end def include?(x, y, z) (0..@width).include?(x) && (0..@height).include?(y) && (0..@depth).include?(z) end def [](x, y, z) if include? x, y, z @tiles[z * @width * @height + y * @width + x] else raise "Tile out of bound : (#{x}, #{y}, #{z}) - #{self}" end end def []=(x, y, z, v) if include? x, y, z @tiles[z * @width * @height + y * @width + x] = v else raise "Tile out of bound : (#{x}, #{y}, #{z}) - #{self}" end end def each @tiles.each_with_index do |v, i| yield v, i % @width, # x (i / @width) % @height, # y i / (@height * @width) # z end end def window(x, y, z, w, h, d) z.upto(z + d - 1) do |sz| y.upto(y + h - 1) do |sy| x.upto(x + w - 1) do |sx| yield self[sx, sy, sz], sx, sy, sz end end end end end Fred -- No will to wake for this morn To see another black rose born Deathbed is slowly covered with snow (Nightwish, End of All Hope)