Skip to main content
May 12, 2021
Solved

adding numbers present in array without using sum function

  • May 12, 2021
  • 7 replies
  • 0 views

can some one tell me on how to create an expression rule to add an array of numbers without suing sum function

    Best answer by csteward

    Agree, sum() function should be your go-to for "summing" an array.  

    But if you are looking to unnecessarily complicate your code, how about a recursive function to add an array of numbers.

    Note with recursive rules, you must save them prior to testing.

    /* 
    rule!chris_add_recur(
      array: List of Integer
      index: Integer
      total: Integer
    )
    */
    
    a!localVariables(
      local!index: if(rule!APN_isEmpty(ri!index),1,ri!index),
      local!total: if(rule!APN_isEmpty(ri!total),0,ri!total),
      
      if(
        local!index>count(ri!array),
        ri!total,
        rule!chris_add_recur(
          array: ri!array,
          index: local!index+1,
          total: index(ri!array,local!index)+local!total
        )
      )
    )

    Call this rule with only the array input as:

    rule!chris_add_recur(
      array: {1,2,3,4}
    )

    7 replies

    stefanhelzle0001
    Brainy
    May 12, 2021

    For what purpose? What is wrong with sum()?

    csteward
    cstewardAnswer
    May 12, 2021

    Agree, sum() function should be your go-to for "summing" an array.  

    But if you are looking to unnecessarily complicate your code, how about a recursive function to add an array of numbers.

    Note with recursive rules, you must save them prior to testing.

    /* 
    rule!chris_add_recur(
      array: List of Integer
      index: Integer
      total: Integer
    )
    */
    
    a!localVariables(
      local!index: if(rule!APN_isEmpty(ri!index),1,ri!index),
      local!total: if(rule!APN_isEmpty(ri!total),0,ri!total),
      
      if(
        local!index>count(ri!array),
        ri!total,
        rule!chris_add_recur(
          array: ri!array,
          index: local!index+1,
          total: index(ri!array,local!index)+local!total
        )
      )
    )

    Call this rule with only the array input as:

    rule!chris_add_recur(
      array: {1,2,3,4}
    )

    May 25, 2021

    thank you for your answer actually i also agree with sum() but i had this question in my interview 

    vamsik0002
    May 25, 2021

    you can use reduce() function