Skip to main content
paolad5416
July 26, 2024
Question

help to create rule to calculate data based on the previous iteration

  • July 26, 2024
  • 3 replies
  • 0 views
I have this array {100, 50, 20,50,10} and a variable x = 600, I need help to create a rule that creates an array with the results that must be calculated in this way:

The first value of the array must be subtracted with the variable x, the result must be subtracted with the second value of the array, the previous result must be subtracted with the third position and so on. The results must be stored in an array.

At the moment I have this code but it does not work correctly


a!localVariables(
local!regularizaciones: {100, 50, 20,50,10},
local!initialValue: 600,


local!resultArray: {local!initialValue},

a!forEach(
items: a!forEach(
items: local!array,
expression: fv!item
),
expression: a!localVariables(
local!currentValue: fv!item,
local!lastResult: index(local!resultArray, length(local!resultArray)),
local!newResult: local!lastResult - local!currentValue,
local!resultArray: append(local!resultArray, local!newResult)
)
),


local!resultArray

)

I appreciate any help


3 replies

July 26, 2024

You can use the reduce function. See the following sample code:

a!localVariables(
  local!regularizaciones: { 100, 50, 20, 50, 10 },
  local!initialValue: 600,
  reduce(
    fn!sum,
    local!regularizaciones[1] - local!initialValue,
    ldrop(local!regularizaciones, 1) * ( - 1)
  )
)

venkatrea696188
July 26, 2024

Hello, You should mention sample output (It would help us a lot) .have a look into the code the output of this code looks like {500,450,430,380,370}

a!localVariables(
  local!regularizaciones: {100, 50, 20,50,10},
  local!initialValue: 600,
a!forEach(
  items: local!regularizaciones,
  expression: a!localVariables(
    local!subtractedarray:if(
      fv!index=1,
      local!initialValue-fv!item,
      local!initialValue-sum(index(local!regularizaciones,(enumerate(fv!index)+1),null))
    ),
    {local!subtractedarray}
  )
)

)

gayathris111098
July 30, 2024

a!localVariables(
local!regularizaciones: { 100, 50, 20, 50, 10 },
local!initialValue: 600,
/* Define the reduce function */
local!resultArray: reduce(
rule!subtractionAccumulator,
{ local!initialValue },
local!regularizaciones,

),
local!resultArray
)

/* Helper function to accumulate subtraction results */
rule!subtractionAccumulator

ri!lastResult - ri!currentValue