[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Extracting and inserting a "column" from/into an array

Extracting and inserting a "column" from/into an array

Chauk-Mean P.

6/16/2009 3:35:00 PM

Hi,

For image processing, I have to do the following operations :

1/ I have an array and I want to extract every 4 element into another
array :

# r=red, g=green, b=blue, a=alpha
img_data = [ "r1", "g1", "b1", "a1", "r2, "g2", "b2", "a2" ]

=> [ "a1", "a2" ] # the array of every four elements i.e. alpha data

It's like extracting the fourth column of a matrix of n rows and 4
columns.

2/ Conversely, I have an array and I need to add elements at every 3
elements

img_data = [ "r1", "g1", "b1", "r2, "g2", "b2" ]
alpha_data = [ "a1", "a2" ] # the elements to add

=> [ "r1", "g1", "b1", "a1", "r2, "g2", "b2", "a2" ]

It's like inserting a column to a matrix of n rows and 3 columns.

I'm wondering if there is an easy or seamless way to do these
operations.
Thanks in advance for any tips.

Cheers.

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

6/16/2009 5:50:00 PM

Array is an Enumerable so when you require 'enumerator' you get a bunch
of cool ways of slicing it up.

> 1/ I have an array and I want to extract every 4 element into another
> array :
>
> # r=red, g=green, b=blue, a=alpha
> img_data = [ "r1", "g1", "b1", "a1", "r2, "g2", "b2", "a2" ]
>
> => [ "a1", "a2" ] # the array of every four elements i.e. alpha data

result = img_data.enum_slice(4).map {|arr| arr[3]}

>
> It's like extracting the fourth column of a matrix of n rows and 4
> columns.
>
> 2/ Conversely, I have an array and I need to add elements at every 3
> elements
>
> img_data = [ "r1", "g1", "b1", "r2, "g2", "b2" ]
> alpha_data = [ "a1", "a2" ] # the elements to add
>
> => [ "r1", "g1", "b1", "a1", "r2, "g2", "b2", "a2" ]

result = img_data.enum_slice(3).zip(alpha_data).flatten

m.

Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Extracting and inserting a "column" from/into an array

Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te

Il servizio è completamente GRATUITO!