How to do a factorial?

I currently have a structure sort of like the following:

[
  {
    "factor": 1
  },
  {
    "factor": 2
  },
  {
    "factor": 2
  },
  {
    "factor": 4
  }
]

Where i’d like the total factorial: 1 * 2 * 2 * 4 = 16 added to all objects in the array:

[
  {
    "factor": 1,
    "_totalFactor": 16
  },
  {
    "factor": 2,
    "_totalFactor": 16
  },
  {
    "factor": 2,
    "_totalFactor": 16
  },
  {
    "factor": 4,
    "_totalFactor": 16
  }
]

As the array is of undefined length, i need to be able to ‘walk’ the array and multiply by the previous factor… ?

Hello @robin.speekenbrink ,
The first example that could think of is this.
Technically, you need to multiply them and afterwards to add it to the array.

Awesome, and works like a charm… Its exactly the use of the operator on an array that was hard to find in the docs :slight_smile: Great!

Thanks for the help, but i just found out I need something similar yet different:

should become:

[
  {
    "factor": 1,
   "_totalFactor": 1
  },
  {
    "factor": 2,
   "_totalFactor": 2
  },
  {
    "factor": 2,
   "_totalFactor": 4
  },
  {
    "factor": 4,
   "_totalFactor": 16
  }
]

( thus the “_totalFactor” per object is the previous _totalFactor * factor )

If adding to the orginal array an object { "factor": 5 } this would result in another object in the result: { "factor": 5, "_totalFactor": 80 } ( 5*16 )

Interesting, well broken down like this, you need to keep the “_totalFactor” last value inside a storage, and get it from there for every new element added to the array.

Hmm… sounds complicated as in PHP this would be a very simple foreach-loop:

foreach ($data as $key => &$_obj) {
    $_obj['_totalFactor'] = ($data[$key-1]['_totalFactor'] ?? 1) * $_obj['factor'];
}
unset($_obj); // to clear the reference

You suggest using a storage (i assume to do the lookup of the previous _totalFactor, but how would that work if this was run simultaneously ? I’d also have to introduce somesort of unique key, cleanup the storage afterwards etc… Seems clunkly

Mostly “everything” can also be done in Alumio.
Indeed it required more set up than a regular equivalent PHP code.
But the purpose is to achieve your scope, and from there you can optimize.
Proposed solution in Alumio.

Once you read it like you have it, it actually seems legit :slight_smile:

Awesome! :partying_face: :tada: