Array maths question

Is this the right way to subtract 1 from the first number in an array? It seems a bit convoluted to me!

~e3 = [ 9.0, 0.80000001192093 ]
~e3.put(0, ~e3.at(0) - 1)

-> [ 8.0, 0.80000001192093 ]

I would do it like this, but it’s only slightly less verbose than your solution! :slight_smile:

~e3 = [ 9.0, 0.80000001192093 ];
~e3[0] = ~e3[0] - 1;

-> [ 8.0, 0.80000001192093 ]

Here’s a stupid way – stupid, because it’s O(n) instead of O(1) – if your array has a million numbers, it will do one real subtraction and 999,999 “minus 0” operations :laughing:

~e3 = [ 9.0, 0.80000001192093 ];
~e3 - [1].extend(~e3.size, 0);

… which I offer principally to suggest that the put approach, though ugly, is probably the best way.

hjh

I sometimes express this as something like:

~e3 = [9.0, 0.80] - [1, 0];

Of course it’s slightly less efficient and could be too verbose for e.g. a large array with only one change ---- but in many many musical cases (e.g. offsetting degrees in a chord, offsetting an array of synth values) it’s easier to read and think about things when expressed like this.

or

~e3 = [ 9.0, 0.80000001192093 ];
[ ~e3.head - 1, ~e3.tail ]

this would be a nice method to write if you need it often… maybe ~e3.decrement(5)

Ah, yes, that’s nice and readable in this case, thanks!