Jump to content
Sign in to follow this  

split value over array indices

Recommended Posts

Hi everyone

I have an array that grows and reduces, thats not the problem it works fine, however evey now and then I need to add/distribute a value across all indices if needed, heres the code I am trying to get working

$value = 5
$i = 0
While $i < $value
    $j = UBound($array)-1
    $array[$j-$i] = $array[$j-$i]+1
    If $i = UBound($array) Then
        $i = 0
        $i = $i+1

So for example my array could be [1,1,2,2] and I want to add 5 to it so it would be [2,2,3,4] I want the count to start at the last indice. The above codes works most of the time but I get the badly formatted error and cant work out why, any help greatly appreciated, thanks in advance

Share this post

Link to post
Share on other sites

I'd do it like this, as long as $iValue is always an int. (Otherwhise you might want to check if it's higher than 0.)

#include <array.au3>

Global $aArray[4]=[1,1,1,1]
Global $iValue = 7

While 1 ;Make the For loop start at the end again of it reaches the start of the array and there is still a value in $iValue.
    For $i = UBound($aArray)-1 To 0 Step -1 ;loop through the error from the last index to the first.
        $aArray[$i] += 1 ;increase array index
        $iValue -= 1 ;decrease distributable value
        If Not $iValue Then ExitLoop 2 ;exit the for AND While loops if $iValue has been distributed.


Share this post

Link to post
Share on other sites

Try this:

#include <Array.au3>
Dim $array[4]=[1, 1, 2, 2]
$u = UBound($array) - 1

$value = 5

$i = $u
While $value > 0
    $array[$i] += 1
    $value -= 1
    $i -= 1
    If $i < 0 Then $i = $u




Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Share this post

Link to post
Share on other sites


Interesting problem (not to mention the solutions). The distribution pattern is serial and weight is constant. What would you expect as a result given the following:

a = [2,2,2]

v = 20

If you don't mind my asking, what is the application for this?


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...