[Newbies] Re: combining arrays.....?

Hernán Morales Durand hernan.morales at gmail.com
Sun May 9 15:04:05 UTC 2010


Hi,

#with:do: require both collections of equal size, but in your example
you have two collection of different sizes, and as nobody wrote a
solution for that case, here are some other ways to do it

| col1 col2 |
col1 := #(1 2 3 4 5). col2 := #($a $b $c).
result := OrderedCollection new.
1 to: ( col1 size min: col2 size )
	do: [: idx | result add: ( col1 at: idx ); add: ( col2 at: idx )].
result addAll: (
	col1 size > col2 size
		ifTrue: [  col1 last: col1 size - col2 size ]
		ifFalse: [ col2 last: col2 size - col1 size ] ).
result.

or

| col result collectionTwo |
result := OrderedCollection new.
collectionTwo := #($a $b $c).
#(1 2 3 4 5) doWithIndex: [: elem : idx |
	result add: elem.	
	idx > collectionTwo size
		ifFalse: [ result add: ( collectionTwo at: idx ) ] ].
result

but as Bert said, for the sake of clarity and efficency you should try
to use Streams sending #readStream or #writeStream to the collections.

Hernán

2010/5/4 Bert Freudenberg <bert at freudenbergs.de>:
> On 03.05.2010, at 19:38, noobie wrote:
>>
>>
>> I cant get the comma thing to work.....what I was trying is something like
>>
>> combine: arg
>> |Array1 i|
>> Array1 := Array new: (self size + arg size).
>>
>> i:= (self size + arg size).
>> [i>0] whileTrue:
>>
>> [
>> (i=nil) ifTrue: [Array1 at: i put:(self at i).]
>> ifFalse: [Array1 at: i put:(arg at i). i:= i+1.]
>>
>> ].
>>
>> But I cant seem to get it working??
>
> I'd use a stream, and #with:do:, much simpler:
>
>        Array streamContents: [:stream|
>                #(1 2 3) with: #(a b c) do: [:x :y |
>                        stream nextPut: x; nextPut: y]]
>
> A good rule of thumb is that whenever you find yourself muddling with indices in Squeak, there is a better way. You can do that too, but it is considered low-level and bad style because it's much easier to get wrong:
>
>        | x y result |
>        x := #(1 2 3).
>        y := #(a b c).
>        result := Array new: x size * 2.
>        1 to: x size do: [:i |
>                result at: i * 2 - 1 put: (x at: i).
>                result at: i * 2 put: (y at: i)].
>        ^result
>
>
> - Bert -
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at lists.squeakfoundation.org
> http://lists.squeakfoundation.org/mailman/listinfo/beginners
>


More information about the Beginners mailing list