Jump to content
Sign in to follow this  
Grumpy Old Man

How to avoid zero divisor when substracting from array?

Recommended Posts

Hey folks,

I need to substract arrays in descending order and got it working fine so far, until it's reaching the last value:

_array = someglobalarray;
_size = count _array;
_value1 = _array select (_size - 1);
_value2 = _array select (_size - 2);
_array resize (_size - 1);
hint str [someglobalarray];
value = (_value1 - _value2);

this is running in a loop and basically substracting the second highest value from the highest value, then deletes the highest value

once the array size is reaching 1 I'm getting a zero divisor error because there is no second highest value anymore

how can I prevent this from happening? or is there a more elegant solution to it?

---------- Post added at 12:59 ---------- Previous post was at 12:02 ----------

For now I exit the loop with an if exitwith line before the zero divisor error occurs,

would love to know if there's actually a better solution to this.

Or is this the only one?

Share this post


Link to post
Share on other sites

I'd just count the array and if there's only one thing in it return that instead, that's probably the best way of dealing with it.

Share this post


Link to post
Share on other sites

Resizing the array returns some weird results sometimes, as is the case here. I'd say subtracting the result from _value1 and _value2 from the global array is your best bet. The array will resize accordingly afterwards. You'll still have to exit before a zero diviser occurs as the array will, at one point, not have more than one value (presumably).

Share this post


Link to post
Share on other sites

A little unclear without knowing the actual outter loop and what is needed from this but

You could just use a for loop to step down through the array

_array = someglobalarray;
for "_i" from ((count _array)-1) to 1 step -1 do {
_value1 = _array select _i;
_value2 = _array select (_i - 1);
value = (_value1 - _value2);
//Do what ever with value
};

Share this post


Link to post
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
Sign in to follow this  

×