From: "list. rb" Date: 2009-06-16T07:30:32+09:00 Subject: Re: [QUIZ] Matrix Rotator (#209) --0016e644cf4a046ffc046c6a9be8 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit I just happened to have done this in a side project I was working on.. Here's my rotate method. It accepts negative and positive numbers.. def rotate(n=1) (n%4).times {self.replace(self.reverse.transpose)} end Which supports grid.rotate(-2) for left twice, or 1 for right.. or whatever really.. Here's the Grid class: #!/usr/bin/env ruby -W0 SAMPLE_DATA = %w[ 0 0 7 0 5 0 0 0 0 0 0 0 0 6 4 0 0 1 4 0 0 0 0 0 2 0 9 0 8 9 0 0 0 4 0 3 6 0 3 0 0 4 0 9 0 0 0 2 4 0 0 8 0 6 0 0 0 9 1 0 6 0 0 0 0 0 0 0 0 0 0 0 2 0 4 0 0 0 0 0 0 ].collect {|i| i.to_i} class Array def /len a = [] self.each_with_index do |x,i| a << [] if i % len == 0 a.last << x end a end end class Grid < Array attr_accessor :set def initialize(set=SAMPLE_DATA) @set = set self.replace(set/Math.sqrt(set.size)) end def rotate(n=1) (n%4).times {self.replace(self.reverse.transpose)} end def flip(direction=:right) case direction when :right then self.replace(self.transpose.rotate(1)) when :left then self.replace(self.transpose.rotate(-1)) end end def children ## returns array of new Grids(3x3), ordered from left to right return self.collect {|i| i/3}.transpose.collect {|i| i/3}.transpose.collect {|i| i.collect {|j| Grid.new(j.flatten.compact)}} end def sum Array.new(self.flatten.compact).sum end def columns self.transpose end def rows self end def inspect self.to_s end def to_s "\n" + self.collect {|i| i.inspect}.join("\n") end end grid = Grid.new grid.rotate(1) #right cw 90deg p grid grid.rotate(-2) #left ccw 180deg p grid On Mon, Jun 15, 2009 at 3:40 PM, Todd Benson wrote: > On Mon, Jun 15, 2009 at 4:22 AM, Robert Dober > wrote: > > I should not have posted my bad, yet Todd you forget it is Ruby you > > should put the blame on ;) > > But I guess it is not that simple anyway, puuuh. > > R. > > I don't want to hijack the thread, but since my venting is off topic, > it will probably get lost in the noise anyhow. Solving a cube (of any > number of pieces) is mostly working backwards from a solved state. A > good transformation algorithm is handy. Maybe that should be another > quiz :) > > I tried a mathematical transformation for this quiz so that it could > be useful for something other than a quarter turn. Didn't work. For > those more inclined to "make it so", it's an inverse matrix in front > of a position matrix. What's funny about the extra dimension required > fascinates me. I get the math, but why do we need singularity (a > bunch of 1's) on that final dimension? > > --0016e644cf4a046ffc046c6a9be8--