A 'symmetrical' pair of arrays

I am trying to make a pair of symmetrical arrays, but am stumped as to the method to achieve them. I will show first what I am going for.

[ 0.125, 0.25, 0.5, 1.0, 1.0, 1.0, 1.0]
[ 0 , 0 , 0 , 0, 0.5, 0.75, 0.875 ]

The top array is the result of the below code, with three 1s added to it:

var number_of_changes = 4;
number_of_changes.collect{|i| 2.pow(i).reciprocal}.reverse;

The bottom array is the same as the top, if it were reversed, and the values subtracting from 1.

There are two barriers in my mind.

The first is that the array is not double the length of “number_of_changes” but double minus one.

The second issue is I have no elegant method (or even a crude one) for adding the additional “number_of_changes-1” values to the result of:

number_of_changes.collect{|i| 2.pow(i).reciprocal}.reverse;

I have only been able to generate this array so far:

[ 0.125, 0.25, 0.5, 1.0 ]

The two things I would like to do therefore are to create the longer array, and then create its symmetrical twin array that I described above.

Any help on this without be gratefully received.

i hope i understand you question correctly.

you don’t have to use any loops for this.

if you have
a = [ 0.125, 0.25, 0.5, 1.0, 1.0, 1.0, 1.0]

then by doing
1-a
you get an array of the difference to 1 of each element.
(1-a).reverse
gives you that result, but in reverse, as requested.

Hi Herman,

Thanks for your reply.

You have understood the question correctly. That part of the problem I feel more confident with. I had some simple code approximating it:

number_of_changes.collect{|i| 1-2.pow(i).reciprocal};

But I would change this to just be reversing the first array, rather than generating two arrays.

What I’m not so confident about is how to add the extra values to the original array:

var number_of_changes = 4;
number_of_changes.collect{|i| 2.pow(i).reciprocal}.reverse;

I would ideally like to do the whole process for the first array in two lines of code. What the above is missing is the addition of the extra (in this case) three 1s.

So I basically need an extra ¨number_of_changes-1¨ number of 1s on any given array generated.

Thanks again for your response!

i see. you can try
generated_array ++ 1.dup(number_of_changes-1)
to create and add an array with the right number of extra 1s

The word you are looking for is concatenation, it has an operator ++ (as Herman suggested).

Thank you Herman and Jordan,

I think I’ve got there:

var number_of_changes = 4;
var array1 = number_of_changes.collect{|i| 2.pow(i).reciprocal}.reverse ++ 1.dup(number_of_changes-1);
var array2 = 1-array1.reverse;
array2.postln;

It’s a combination of integers and floats but I don’t think that should matter.

I will add ¨concatenation¨ to my programming vocabulary :slight_smile:

Very much appreciate your help!

1 Like