[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Extracting sub elements in array

WKC CCC

2/13/2007 5:20:00 PM

Is there a fast way to return a subsection of an array object as there
is the minor function for a Matrix?

For example
testArray = [[1,2,3,4,5],
[7,8,9,10,11]]

How can the elements [[4,5],[10,11]] be extracted?

Thanks,

--
Posted via http://www.ruby-....

4 Answers

Tim Pease

2/13/2007 5:26:00 PM

0

On 2/13/07, WKC CCC <wai-kee.chung@uk.bnpparibas.com> wrote:
> Is there a fast way to return a subsection of an array object as there
> is the minor function for a Matrix?
>
> For example
> testArray = [[1,2,3,4,5],
> [7,8,9,10,11]]
>
> How can the elements [[4,5],[10,11]] be extracted?
>
> Thanks,
>

testArray.map {|x| x[-2..-1]}

I don't know if it is "fast", but it was certainly quick to write ;)

Blessings,
TwP

Paul Duncan

2/13/2007 6:05:00 PM

0

* WKC CCC (wai-kee.chung@uk.bnpparibas.com) wrote:
> Is there a fast way to return a subsection of an array object as there
> is the minor function for a Matrix?
>
> For example
> testArray = [[1,2,3,4,5],
> [7,8,9,10,11]]
>
> How can the elements [[4,5],[10,11]] be extracted?

Use the built-in matrix class:

require 'matrix'

m = Matrix.rows (1..5).to_a, (7..11).to_a

# extract the subsection at rows 0..1 and cols 3..4
m.minor(0..1, 3..4) #=> Matrix[[4, 5], [10, 11]]

See the matrix documentation for additional documentation:

http://ruby-doc.org/stdlib/libdoc/matrix/rdoc/...

--
Paul Duncan <pabs@pablotron.org> pabs in #ruby-lang (OPN IRC)
http://www.pabl... OpenPGP Key ID: 0x82C29562

WKC CCC

2/13/2007 6:24:00 PM

0

Thanks,

I've created the following function as an extention to class Array:

def Section(startRow,nRows,startCol,nCols)
part = self[startRow..startRow+nRows-1]
part = part.map{|x| x[startCol..startCol + nCols-1]}
return part
end

testArray=[[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14],
[15,16,17,18]]

calling testArray.Section(2,2,2,2)

will return [[13,14],[17,18]]

which is essentially what the minor function but on an Array

--
Posted via http://www.ruby-....

Tim Pease

2/13/2007 7:27:00 PM

0

On 2/13/07, WKC CCC <wai-kee.chung@uk.bnpparibas.com> wrote:
> Thanks,
>
> I've created the following function as an extention to class Array:
>
> def Section(startRow,nRows,startCol,nCols)
> part = self[startRow..startRow+nRows-1]
> part = part.map{|x| x[startCol..startCol + nCols-1]}
> return part
> end
>
> testArray=[[1,2,3,4,5],
> [6,7,8,9,10],
> [11,12,13,14],
> [15,16,17,18]]
>
> calling testArray.Section(2,2,2,2)
>
> will return [[13,14],[17,18]]
>

def section( rows, cols )
self.slice(rows).map! {|c| c.slice(cols)}
end

testArray = [
[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20]
]

testArray.section( 2...4, 2...4 )

[[13, 14],
[18, 19]]


Blessings,
TwP