Liios
Liios

Reputation: 93

ARRAYFORMULA with SUM and CHOOSE

I have a set of values, for exemple :

14 ; 17 ; 12 ; 14 ; 12 ; 8

You might recognize a set of DnD ability scores. I want to calculate the amount of creation point used for these.

So I would like to combine SUM and CHOOSE. I tried this (same as in my working LibreOffice sheet) :

=ARRAYFORMULA(SUM(CHOOSE(C9:C14 - 6; -4; -2; -1; 0; 1; 2; 3; 5; 7; 10; 13; 17)))

I expected 25 (5+13+2+5+2-2), got 5. For some reason it stops right after the first value without doing any sum.

Upvotes: 1

Views: 155

Answers (2)

Robin Gertenbach
Robin Gertenbach

Reputation: 10776

Some functions unfortunately don't work with ArrayFormulae, CHOOSE seems to be one of them.

Unfortunately Index doesn't either, VLookup does though so we have to create this monstrosity:

=ArrayFormula(SUM(VLOOKUP(
  $C$9:$C$14 - 6, 
  {1, -4;
   2, -2;
   3, -1;
   4, 0;
   5, 1;
   6, 2;
   7, 3;
   8, 5;
   9, 7;
   10, 10;
   11, 13;
   12, 17}, 2)))

If you have room somewhere to create a table that can be referenced the formula will be much simpler of course.

Another approach would be a custom function:

function abilityScoreCost(scores) {
  var costs = {
    7:  -4,
    8:  -2,
    9:  -1,
    10: 0,
    11: 1,
    12: 2,
    13: 3,
    14: 5,
    15: 7,
    16: 10,
    17: 13,
    18: 17
  }
  return scores
      .map(function (score) {
        return costs[score];
      }).reduce(function (x,y) {
        return x + y;
      });
}

that you could then call with =abilityScoreCost(C9:C14)

Upvotes: 1

AdamL
AdamL

Reputation: 24599

To be clear, +Robin Gertenbach's answer is much more intuitive than this, but this is a bit shorter:

=ArrayFormula(SUM(HLOOKUP(-4,{-4;-2;-1;0;1;2;3;5;7;10;13;17},C9:C14-6)))

Upvotes: 1

Related Questions