Array manipulations questions

(Peter Fitzgibbons) #1

I have an array :

a =
[ [10, 11], [20, 21],
  [12, 13], [22, 23],
  [30, 31], [40, 41],
  [32, 33], [42, 43] ]

I want to know how to manipulate the array to get :
a.grid(1)
==> [10, 11], [12, 13]
A.grid(2)
==> [20, 21], [22, 23]
A.grid(3)
==> [30, 31], [32, 33]
A.grid(4)
==> [40, 41], [42, 43]

B = a.grid(1)
==> [10, 11], [12, 13]
B[1][1]
==> 10
B[2][2]
==> 13

A.row(1)
==> [10, 11, 20, 21]

A.col(1)
==> [10, 12, 30, 32]

Many many thanks for your examples.

Peter J. Fitzgibbons
Applications Manager
Lakewood Homes - "The American Dream Builder"(r)
Peter.Fitzgibbons@Lakewoodhomes.net
(847) 884-8800

···

-----Original Message-----
From: Peter Fitzgibbons [mailto:Peter.Fitzgibbons@lakewoodhomes.net]
Sent: Tuesday, August 16, 2005 4:16 PM
To: ruby-talk ML
Subject: Array manipulations questions

============================
What I meant to use for the source array was :

a =
[ [10, 11, 20, 21],
  [12, 13, 22, 23],
  [30, 31, 40, 41],
  [32, 33, 42, 43] ]

Thanks for your help.

Peter J. Fitzgibbons
Applications Manager
Lakewood Homes - "The American Dream Builder"(r)
Peter.Fitzgibbons@Lakewoodhomes.net
(847) 884-8800

(Pit) #2

Hi Peter,

I changed the arguments of the methods to start at 0:

a =
[ [10, 11, 20, 21],
  [12, 13, 22, 23],
  [30, 31, 40, 41],
  [32, 33, 42, 43] ]

   def a.grid( i )
     mid_row = size / 2
     mid_col = self[ 0 ].size / 2
     rows = if i < 2 then 0 ... mid_row else mid_row .. -1 end
     cols = if ( i % 2 ).zero? then 0 ... mid_col else mid_col .. -1 end
     self[ rows ].map { |elem| elem[ cols ] }
   end

a.grid(0)
==> [10, 11], [12, 13]
a.grid(1)
==> [20, 21], [22, 23]
a.grid(2)
==> [30, 31], [32, 33]
a.grid(3)
==> [40, 41], [42, 43]

b = a.grid(0)
==> [10, 11], [12, 13]
b[0][0]
==> 10
b[1][1]
==> 13

   def a.row( i )
     self[ i ]
   end

a.row(0)
==> [10, 11, 20, 21]

   def a.col( i )
     map { |elem| elem[ i ] }
   end

a.col(0)
==> [10, 12, 30, 32]

Regards,
Pit

(why the lucky stiff) #3

Let's start with the easy stuff.

Peter Fitzgibbons wrote:

A.row(1)
==> [10, 11, 20, 21]
  

a[0]
=> [10, 11, 20, 21]

def a.row i
  at i-1
end
a.row 1
=> [10, 11, 20, 21]

A.col(1)
==> [10, 12, 30, 32]

a.transpose[0]
=> [10, 12, 30, 32]

def a.col i
  transpose[i-1]
end
a.col 1
=> [10, 12, 30, 32]

As far as the `grid' method goes, do you want it to always do a 2x2 square or are you looking for some other math here?

  def a.grid i
    i -= 1
    (0..1).map do |j|
      at(((i/2)*2)+j)[(i%2)*2,2]
    end
  end

_why