chchrist
chchrist

Reputation: 19822

How to generate this sequence programmatically

How can i generate dynamically this array.

var posX:Array = [0,-20,20,-40,0,40,-60,-20,20,60,-80,-40,0,40,80,-100,-60,-20,20,60,100]

The numbers in the array refer to the x position of the object. I use it to place objects in triangular formation.

     0
   -20 20
  -40 0 40
-60 -20 20 60 etc

Thank you in advance

Upvotes: 0

Views: 212

Answers (4)

Amarghosh
Amarghosh

Reputation: 59461

var d:Number = 20;
var a:Array = [];
for(var i:Number = 0; i < 6; i++)
{
    for(var j:Number = 0; j <= i; j++)
    {
        a.push(d * (2 * j - i));
    }
}
trace(a.join());    

The first number of each row is the negative of the zero-based-row-index times d : which is - i * d
Each subsequent number in a row exceeds the previous one by 2*d. Hence subsequent numbers = first-element + 2 * d * zero-based-index-within-the-row

Which is = - i * d + 2 * d * j = d * (2 * j - i)

Upvotes: 1

Peter
Peter

Reputation: 48988

The Code for each row in f# :

let StepN n = 
    let n = -(n*20)
    [
    for x in [n..40..-n] do
        yield x
    ]   

Upvotes: 0

yu_sha
yu_sha

Reputation: 4400

I don't know actionscript but pseudocode is like this:

for (row=0; ; row++)
{
   maxVal=20*row;
   for (val=-maxVal;val<=maxVal;val+=40)
    posX.append(val);
}

Upvotes: 0

Kamil Szot
Kamil Szot

Reputation: 17817

This code outputs subsequent elements of your array for ten row of your triangular formation:

var x:int;
var y:int;
for (y = 0; y < 10; y++) {
    for (x = 0; x < y + 1; x++) {
        trace(20 * ( -y + 2 * x));
    }
}

Upvotes: 0

Related Questions