Flexible algorithm to calculate possibilities of all possible scenarios












2















I've been struggling for a little while to find or figure out algorithm.



The task:
Basically, I have an array of probabilities:



var input = [0.1, 0.2, 0.3, 0.1];


Let's name these inputs accordingly to: A, B, C and D.



And I also have a variable "m", which can tell me how many of these things needs to happen in order to get the result.
For example:



var m = 2;


This variable m is telling me that the event will happen if any of those two (or more) probabilities will happen.



So in this case, for event to happen, all possible ways for event to happen is:



ABCD
ABC
ABD
BCD
AB
AC
AD
BC
BD and CD



Now I need to calculate their probabilities, which I already have algorithms to calculate AND and OR (where input is just a probabilities array).



AND:



if (input.length > 0) {
output = 1;
}
for (i = 0; i < input.length; i++) {
output = input[i] * output;
}


OR:



if (input.length > 0) {
output = input[0];
}
for (i = 1; i < input.length; i++) {
output = (output + input[i]) - (output * input[i]);
}


So I am struggling on figuring out how to loop through all possible possibilities... And to have something like:
(A and B and C and D) or (A and B and C) or (A and B and D)... and so on... I hope you get the idea.










share|improve this question























  • What do you mean by "probabilities will happen" ?

    – Alice Oualouest
    Nov 21 '18 at 17:38











  • Every probability input indicates a chance of an event to happen. For example: 0.5 probability that the coin flip will be on tails, 0.1 probability that card drawn will be ace and 0.2 probability that card human will select color red. Now I need to calculate what are the odds of happening of at least 2 events.

    – NeuTronas
    Nov 21 '18 at 17:39













  • So in this case, it is 0.5*0.1 or 0.5*0.2 or 0.1*0.5 or 0.5*0.1*0.2.

    – NeuTronas
    Nov 21 '18 at 17:42











  • Are you actually interested in all the possibilies or just the result of (A and B and C and D) or (A and B and C) or (A and B and D)... ?

    – juvian
    Nov 21 '18 at 17:47











  • Does the input sum up to 1 or not?

    – Jonas Wilms
    Nov 21 '18 at 17:49
















2















I've been struggling for a little while to find or figure out algorithm.



The task:
Basically, I have an array of probabilities:



var input = [0.1, 0.2, 0.3, 0.1];


Let's name these inputs accordingly to: A, B, C and D.



And I also have a variable "m", which can tell me how many of these things needs to happen in order to get the result.
For example:



var m = 2;


This variable m is telling me that the event will happen if any of those two (or more) probabilities will happen.



So in this case, for event to happen, all possible ways for event to happen is:



ABCD
ABC
ABD
BCD
AB
AC
AD
BC
BD and CD



Now I need to calculate their probabilities, which I already have algorithms to calculate AND and OR (where input is just a probabilities array).



AND:



if (input.length > 0) {
output = 1;
}
for (i = 0; i < input.length; i++) {
output = input[i] * output;
}


OR:



if (input.length > 0) {
output = input[0];
}
for (i = 1; i < input.length; i++) {
output = (output + input[i]) - (output * input[i]);
}


So I am struggling on figuring out how to loop through all possible possibilities... And to have something like:
(A and B and C and D) or (A and B and C) or (A and B and D)... and so on... I hope you get the idea.










share|improve this question























  • What do you mean by "probabilities will happen" ?

    – Alice Oualouest
    Nov 21 '18 at 17:38











  • Every probability input indicates a chance of an event to happen. For example: 0.5 probability that the coin flip will be on tails, 0.1 probability that card drawn will be ace and 0.2 probability that card human will select color red. Now I need to calculate what are the odds of happening of at least 2 events.

    – NeuTronas
    Nov 21 '18 at 17:39













  • So in this case, it is 0.5*0.1 or 0.5*0.2 or 0.1*0.5 or 0.5*0.1*0.2.

    – NeuTronas
    Nov 21 '18 at 17:42











  • Are you actually interested in all the possibilies or just the result of (A and B and C and D) or (A and B and C) or (A and B and D)... ?

    – juvian
    Nov 21 '18 at 17:47











  • Does the input sum up to 1 or not?

    – Jonas Wilms
    Nov 21 '18 at 17:49














2












2








2








I've been struggling for a little while to find or figure out algorithm.



The task:
Basically, I have an array of probabilities:



var input = [0.1, 0.2, 0.3, 0.1];


Let's name these inputs accordingly to: A, B, C and D.



And I also have a variable "m", which can tell me how many of these things needs to happen in order to get the result.
For example:



var m = 2;


This variable m is telling me that the event will happen if any of those two (or more) probabilities will happen.



So in this case, for event to happen, all possible ways for event to happen is:



ABCD
ABC
ABD
BCD
AB
AC
AD
BC
BD and CD



Now I need to calculate their probabilities, which I already have algorithms to calculate AND and OR (where input is just a probabilities array).



AND:



if (input.length > 0) {
output = 1;
}
for (i = 0; i < input.length; i++) {
output = input[i] * output;
}


OR:



if (input.length > 0) {
output = input[0];
}
for (i = 1; i < input.length; i++) {
output = (output + input[i]) - (output * input[i]);
}


So I am struggling on figuring out how to loop through all possible possibilities... And to have something like:
(A and B and C and D) or (A and B and C) or (A and B and D)... and so on... I hope you get the idea.










share|improve this question














I've been struggling for a little while to find or figure out algorithm.



The task:
Basically, I have an array of probabilities:



var input = [0.1, 0.2, 0.3, 0.1];


Let's name these inputs accordingly to: A, B, C and D.



And I also have a variable "m", which can tell me how many of these things needs to happen in order to get the result.
For example:



var m = 2;


This variable m is telling me that the event will happen if any of those two (or more) probabilities will happen.



So in this case, for event to happen, all possible ways for event to happen is:



ABCD
ABC
ABD
BCD
AB
AC
AD
BC
BD and CD



Now I need to calculate their probabilities, which I already have algorithms to calculate AND and OR (where input is just a probabilities array).



AND:



if (input.length > 0) {
output = 1;
}
for (i = 0; i < input.length; i++) {
output = input[i] * output;
}


OR:



if (input.length > 0) {
output = input[0];
}
for (i = 1; i < input.length; i++) {
output = (output + input[i]) - (output * input[i]);
}


So I am struggling on figuring out how to loop through all possible possibilities... And to have something like:
(A and B and C and D) or (A and B and C) or (A and B and D)... and so on... I hope you get the idea.







javascript algorithm






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 17:29









NeuTronasNeuTronas

1349




1349













  • What do you mean by "probabilities will happen" ?

    – Alice Oualouest
    Nov 21 '18 at 17:38











  • Every probability input indicates a chance of an event to happen. For example: 0.5 probability that the coin flip will be on tails, 0.1 probability that card drawn will be ace and 0.2 probability that card human will select color red. Now I need to calculate what are the odds of happening of at least 2 events.

    – NeuTronas
    Nov 21 '18 at 17:39













  • So in this case, it is 0.5*0.1 or 0.5*0.2 or 0.1*0.5 or 0.5*0.1*0.2.

    – NeuTronas
    Nov 21 '18 at 17:42











  • Are you actually interested in all the possibilies or just the result of (A and B and C and D) or (A and B and C) or (A and B and D)... ?

    – juvian
    Nov 21 '18 at 17:47











  • Does the input sum up to 1 or not?

    – Jonas Wilms
    Nov 21 '18 at 17:49



















  • What do you mean by "probabilities will happen" ?

    – Alice Oualouest
    Nov 21 '18 at 17:38











  • Every probability input indicates a chance of an event to happen. For example: 0.5 probability that the coin flip will be on tails, 0.1 probability that card drawn will be ace and 0.2 probability that card human will select color red. Now I need to calculate what are the odds of happening of at least 2 events.

    – NeuTronas
    Nov 21 '18 at 17:39













  • So in this case, it is 0.5*0.1 or 0.5*0.2 or 0.1*0.5 or 0.5*0.1*0.2.

    – NeuTronas
    Nov 21 '18 at 17:42











  • Are you actually interested in all the possibilies or just the result of (A and B and C and D) or (A and B and C) or (A and B and D)... ?

    – juvian
    Nov 21 '18 at 17:47











  • Does the input sum up to 1 or not?

    – Jonas Wilms
    Nov 21 '18 at 17:49

















What do you mean by "probabilities will happen" ?

– Alice Oualouest
Nov 21 '18 at 17:38





What do you mean by "probabilities will happen" ?

– Alice Oualouest
Nov 21 '18 at 17:38













Every probability input indicates a chance of an event to happen. For example: 0.5 probability that the coin flip will be on tails, 0.1 probability that card drawn will be ace and 0.2 probability that card human will select color red. Now I need to calculate what are the odds of happening of at least 2 events.

– NeuTronas
Nov 21 '18 at 17:39







Every probability input indicates a chance of an event to happen. For example: 0.5 probability that the coin flip will be on tails, 0.1 probability that card drawn will be ace and 0.2 probability that card human will select color red. Now I need to calculate what are the odds of happening of at least 2 events.

– NeuTronas
Nov 21 '18 at 17:39















So in this case, it is 0.5*0.1 or 0.5*0.2 or 0.1*0.5 or 0.5*0.1*0.2.

– NeuTronas
Nov 21 '18 at 17:42





So in this case, it is 0.5*0.1 or 0.5*0.2 or 0.1*0.5 or 0.5*0.1*0.2.

– NeuTronas
Nov 21 '18 at 17:42













Are you actually interested in all the possibilies or just the result of (A and B and C and D) or (A and B and C) or (A and B and D)... ?

– juvian
Nov 21 '18 at 17:47





Are you actually interested in all the possibilies or just the result of (A and B and C and D) or (A and B and C) or (A and B and D)... ?

– juvian
Nov 21 '18 at 17:47













Does the input sum up to 1 or not?

– Jonas Wilms
Nov 21 '18 at 17:49





Does the input sum up to 1 or not?

– Jonas Wilms
Nov 21 '18 at 17:49












3 Answers
3






active

oldest

votes


















2














You could get the combinations of the wanted array with a minimum of two by using a recursive function which gerates all possible combinations.






function getC(array, min) {
function iter(i, temp) {
var t = temp.concat(array[i]);
if (i === array.length) return;
iter(i + 1, t);
iter(i + 1, temp);
if (t.length >= min) {
result.push(t);
}
}

var result = ;
iter(0, );
return result;
}

var input = [0.1, 0.2, 0.3, 0.1];
console.log(getC(input, 2).map(a => a.join(' ')));

.as-console-wrapper { max-height: 100% !important; top: 0; }








share|improve this answer































    3














    Here's a simple non-recursive solution to enumerate all combinations with at least m elements.






    range = n => [...Array.from({length: n}).keys()]

    mask = xs => b => xs.filter((_, n) => b & (1 << n))

    at_least = n => xs => xs.length >= n

    //

    a = [...'ABCD']
    m = 2

    result = range(1 << a.length).map(mask(a)).filter(at_least(m))

    console.log(result.map(x => x.join('')))





    Since JS bit arithmetics is limited to 32 bits, this only works for m < 32.






    share|improve this answer


























    • nice one ... only works for up to 32 probabilities though ...

      – Jonas Wilms
      Nov 21 '18 at 18:32











    • @JonasWilms: sure, added a note about that

      – georg
      Nov 21 '18 at 19:08



















    1














    You could go over all combimations of 2 elements (AB, CD etc.) with two nested loops:



     for(let i = 0; i < input.length; i++) {
    for(let j = i + 1; j < input.length; j++) {
    // possible combination: i and j
    for(let k = j; k < input.length; k++) {
    // possible combination: i, j, k
    // and so on
    }
    }
    }


    for at least m elements that can be generalized with a nested generator that generates an array of indices ([0, 1], [0, 2], [1, 2], [0, 1, 2]):



     function* combinations(length, m = 1, start = 0) {
    // Base Case: If there is only one index left, yield that:
    if(start === length - 1) {
    yield [length - 1];
    return;
    }

    // Otherwise go over all left indices
    for(let i = start; i < length; i++) {
    // And get all further combinations, for 0 that will be [1, 2], [1] and [2]
    for(const nested of combinations(length, m - 1, i + 1)) {
    // Yield the nested path, e.g. [0, 1], [0, 1, 2] and [0, 2]
    yield [i, ...nested];
    }
    // If the minimum length is already reached yield the index itself
    if(m <= 1) yield [i];
    }
    }


    Now for every combination, we just have to multiply the probabilities and add them up:



     let result = 0;

    for(const combination of combimations(input.length, m))
    result += combination.reduce((prev, i) => prev * input[i], 1);





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417632%2fflexible-algorithm-to-calculate-possibilities-of-all-possible-scenarios%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      You could get the combinations of the wanted array with a minimum of two by using a recursive function which gerates all possible combinations.






      function getC(array, min) {
      function iter(i, temp) {
      var t = temp.concat(array[i]);
      if (i === array.length) return;
      iter(i + 1, t);
      iter(i + 1, temp);
      if (t.length >= min) {
      result.push(t);
      }
      }

      var result = ;
      iter(0, );
      return result;
      }

      var input = [0.1, 0.2, 0.3, 0.1];
      console.log(getC(input, 2).map(a => a.join(' ')));

      .as-console-wrapper { max-height: 100% !important; top: 0; }








      share|improve this answer




























        2














        You could get the combinations of the wanted array with a minimum of two by using a recursive function which gerates all possible combinations.






        function getC(array, min) {
        function iter(i, temp) {
        var t = temp.concat(array[i]);
        if (i === array.length) return;
        iter(i + 1, t);
        iter(i + 1, temp);
        if (t.length >= min) {
        result.push(t);
        }
        }

        var result = ;
        iter(0, );
        return result;
        }

        var input = [0.1, 0.2, 0.3, 0.1];
        console.log(getC(input, 2).map(a => a.join(' ')));

        .as-console-wrapper { max-height: 100% !important; top: 0; }








        share|improve this answer


























          2












          2








          2







          You could get the combinations of the wanted array with a minimum of two by using a recursive function which gerates all possible combinations.






          function getC(array, min) {
          function iter(i, temp) {
          var t = temp.concat(array[i]);
          if (i === array.length) return;
          iter(i + 1, t);
          iter(i + 1, temp);
          if (t.length >= min) {
          result.push(t);
          }
          }

          var result = ;
          iter(0, );
          return result;
          }

          var input = [0.1, 0.2, 0.3, 0.1];
          console.log(getC(input, 2).map(a => a.join(' ')));

          .as-console-wrapper { max-height: 100% !important; top: 0; }








          share|improve this answer













          You could get the combinations of the wanted array with a minimum of two by using a recursive function which gerates all possible combinations.






          function getC(array, min) {
          function iter(i, temp) {
          var t = temp.concat(array[i]);
          if (i === array.length) return;
          iter(i + 1, t);
          iter(i + 1, temp);
          if (t.length >= min) {
          result.push(t);
          }
          }

          var result = ;
          iter(0, );
          return result;
          }

          var input = [0.1, 0.2, 0.3, 0.1];
          console.log(getC(input, 2).map(a => a.join(' ')));

          .as-console-wrapper { max-height: 100% !important; top: 0; }








          function getC(array, min) {
          function iter(i, temp) {
          var t = temp.concat(array[i]);
          if (i === array.length) return;
          iter(i + 1, t);
          iter(i + 1, temp);
          if (t.length >= min) {
          result.push(t);
          }
          }

          var result = ;
          iter(0, );
          return result;
          }

          var input = [0.1, 0.2, 0.3, 0.1];
          console.log(getC(input, 2).map(a => a.join(' ')));

          .as-console-wrapper { max-height: 100% !important; top: 0; }





          function getC(array, min) {
          function iter(i, temp) {
          var t = temp.concat(array[i]);
          if (i === array.length) return;
          iter(i + 1, t);
          iter(i + 1, temp);
          if (t.length >= min) {
          result.push(t);
          }
          }

          var result = ;
          iter(0, );
          return result;
          }

          var input = [0.1, 0.2, 0.3, 0.1];
          console.log(getC(input, 2).map(a => a.join(' ')));

          .as-console-wrapper { max-height: 100% !important; top: 0; }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 17:51









          Nina ScholzNina Scholz

          185k1596168




          185k1596168

























              3














              Here's a simple non-recursive solution to enumerate all combinations with at least m elements.






              range = n => [...Array.from({length: n}).keys()]

              mask = xs => b => xs.filter((_, n) => b & (1 << n))

              at_least = n => xs => xs.length >= n

              //

              a = [...'ABCD']
              m = 2

              result = range(1 << a.length).map(mask(a)).filter(at_least(m))

              console.log(result.map(x => x.join('')))





              Since JS bit arithmetics is limited to 32 bits, this only works for m < 32.






              share|improve this answer


























              • nice one ... only works for up to 32 probabilities though ...

                – Jonas Wilms
                Nov 21 '18 at 18:32











              • @JonasWilms: sure, added a note about that

                – georg
                Nov 21 '18 at 19:08
















              3














              Here's a simple non-recursive solution to enumerate all combinations with at least m elements.






              range = n => [...Array.from({length: n}).keys()]

              mask = xs => b => xs.filter((_, n) => b & (1 << n))

              at_least = n => xs => xs.length >= n

              //

              a = [...'ABCD']
              m = 2

              result = range(1 << a.length).map(mask(a)).filter(at_least(m))

              console.log(result.map(x => x.join('')))





              Since JS bit arithmetics is limited to 32 bits, this only works for m < 32.






              share|improve this answer


























              • nice one ... only works for up to 32 probabilities though ...

                – Jonas Wilms
                Nov 21 '18 at 18:32











              • @JonasWilms: sure, added a note about that

                – georg
                Nov 21 '18 at 19:08














              3












              3








              3







              Here's a simple non-recursive solution to enumerate all combinations with at least m elements.






              range = n => [...Array.from({length: n}).keys()]

              mask = xs => b => xs.filter((_, n) => b & (1 << n))

              at_least = n => xs => xs.length >= n

              //

              a = [...'ABCD']
              m = 2

              result = range(1 << a.length).map(mask(a)).filter(at_least(m))

              console.log(result.map(x => x.join('')))





              Since JS bit arithmetics is limited to 32 bits, this only works for m < 32.






              share|improve this answer















              Here's a simple non-recursive solution to enumerate all combinations with at least m elements.






              range = n => [...Array.from({length: n}).keys()]

              mask = xs => b => xs.filter((_, n) => b & (1 << n))

              at_least = n => xs => xs.length >= n

              //

              a = [...'ABCD']
              m = 2

              result = range(1 << a.length).map(mask(a)).filter(at_least(m))

              console.log(result.map(x => x.join('')))





              Since JS bit arithmetics is limited to 32 bits, this only works for m < 32.






              range = n => [...Array.from({length: n}).keys()]

              mask = xs => b => xs.filter((_, n) => b & (1 << n))

              at_least = n => xs => xs.length >= n

              //

              a = [...'ABCD']
              m = 2

              result = range(1 << a.length).map(mask(a)).filter(at_least(m))

              console.log(result.map(x => x.join('')))





              range = n => [...Array.from({length: n}).keys()]

              mask = xs => b => xs.filter((_, n) => b & (1 << n))

              at_least = n => xs => xs.length >= n

              //

              a = [...'ABCD']
              m = 2

              result = range(1 << a.length).map(mask(a)).filter(at_least(m))

              console.log(result.map(x => x.join('')))






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 21 '18 at 21:15

























              answered Nov 21 '18 at 18:26









              georggeorg

              149k35201299




              149k35201299













              • nice one ... only works for up to 32 probabilities though ...

                – Jonas Wilms
                Nov 21 '18 at 18:32











              • @JonasWilms: sure, added a note about that

                – georg
                Nov 21 '18 at 19:08



















              • nice one ... only works for up to 32 probabilities though ...

                – Jonas Wilms
                Nov 21 '18 at 18:32











              • @JonasWilms: sure, added a note about that

                – georg
                Nov 21 '18 at 19:08

















              nice one ... only works for up to 32 probabilities though ...

              – Jonas Wilms
              Nov 21 '18 at 18:32





              nice one ... only works for up to 32 probabilities though ...

              – Jonas Wilms
              Nov 21 '18 at 18:32













              @JonasWilms: sure, added a note about that

              – georg
              Nov 21 '18 at 19:08





              @JonasWilms: sure, added a note about that

              – georg
              Nov 21 '18 at 19:08











              1














              You could go over all combimations of 2 elements (AB, CD etc.) with two nested loops:



               for(let i = 0; i < input.length; i++) {
              for(let j = i + 1; j < input.length; j++) {
              // possible combination: i and j
              for(let k = j; k < input.length; k++) {
              // possible combination: i, j, k
              // and so on
              }
              }
              }


              for at least m elements that can be generalized with a nested generator that generates an array of indices ([0, 1], [0, 2], [1, 2], [0, 1, 2]):



               function* combinations(length, m = 1, start = 0) {
              // Base Case: If there is only one index left, yield that:
              if(start === length - 1) {
              yield [length - 1];
              return;
              }

              // Otherwise go over all left indices
              for(let i = start; i < length; i++) {
              // And get all further combinations, for 0 that will be [1, 2], [1] and [2]
              for(const nested of combinations(length, m - 1, i + 1)) {
              // Yield the nested path, e.g. [0, 1], [0, 1, 2] and [0, 2]
              yield [i, ...nested];
              }
              // If the minimum length is already reached yield the index itself
              if(m <= 1) yield [i];
              }
              }


              Now for every combination, we just have to multiply the probabilities and add them up:



               let result = 0;

              for(const combination of combimations(input.length, m))
              result += combination.reduce((prev, i) => prev * input[i], 1);





              share|improve this answer






























                1














                You could go over all combimations of 2 elements (AB, CD etc.) with two nested loops:



                 for(let i = 0; i < input.length; i++) {
                for(let j = i + 1; j < input.length; j++) {
                // possible combination: i and j
                for(let k = j; k < input.length; k++) {
                // possible combination: i, j, k
                // and so on
                }
                }
                }


                for at least m elements that can be generalized with a nested generator that generates an array of indices ([0, 1], [0, 2], [1, 2], [0, 1, 2]):



                 function* combinations(length, m = 1, start = 0) {
                // Base Case: If there is only one index left, yield that:
                if(start === length - 1) {
                yield [length - 1];
                return;
                }

                // Otherwise go over all left indices
                for(let i = start; i < length; i++) {
                // And get all further combinations, for 0 that will be [1, 2], [1] and [2]
                for(const nested of combinations(length, m - 1, i + 1)) {
                // Yield the nested path, e.g. [0, 1], [0, 1, 2] and [0, 2]
                yield [i, ...nested];
                }
                // If the minimum length is already reached yield the index itself
                if(m <= 1) yield [i];
                }
                }


                Now for every combination, we just have to multiply the probabilities and add them up:



                 let result = 0;

                for(const combination of combimations(input.length, m))
                result += combination.reduce((prev, i) => prev * input[i], 1);





                share|improve this answer




























                  1












                  1








                  1







                  You could go over all combimations of 2 elements (AB, CD etc.) with two nested loops:



                   for(let i = 0; i < input.length; i++) {
                  for(let j = i + 1; j < input.length; j++) {
                  // possible combination: i and j
                  for(let k = j; k < input.length; k++) {
                  // possible combination: i, j, k
                  // and so on
                  }
                  }
                  }


                  for at least m elements that can be generalized with a nested generator that generates an array of indices ([0, 1], [0, 2], [1, 2], [0, 1, 2]):



                   function* combinations(length, m = 1, start = 0) {
                  // Base Case: If there is only one index left, yield that:
                  if(start === length - 1) {
                  yield [length - 1];
                  return;
                  }

                  // Otherwise go over all left indices
                  for(let i = start; i < length; i++) {
                  // And get all further combinations, for 0 that will be [1, 2], [1] and [2]
                  for(const nested of combinations(length, m - 1, i + 1)) {
                  // Yield the nested path, e.g. [0, 1], [0, 1, 2] and [0, 2]
                  yield [i, ...nested];
                  }
                  // If the minimum length is already reached yield the index itself
                  if(m <= 1) yield [i];
                  }
                  }


                  Now for every combination, we just have to multiply the probabilities and add them up:



                   let result = 0;

                  for(const combination of combimations(input.length, m))
                  result += combination.reduce((prev, i) => prev * input[i], 1);





                  share|improve this answer















                  You could go over all combimations of 2 elements (AB, CD etc.) with two nested loops:



                   for(let i = 0; i < input.length; i++) {
                  for(let j = i + 1; j < input.length; j++) {
                  // possible combination: i and j
                  for(let k = j; k < input.length; k++) {
                  // possible combination: i, j, k
                  // and so on
                  }
                  }
                  }


                  for at least m elements that can be generalized with a nested generator that generates an array of indices ([0, 1], [0, 2], [1, 2], [0, 1, 2]):



                   function* combinations(length, m = 1, start = 0) {
                  // Base Case: If there is only one index left, yield that:
                  if(start === length - 1) {
                  yield [length - 1];
                  return;
                  }

                  // Otherwise go over all left indices
                  for(let i = start; i < length; i++) {
                  // And get all further combinations, for 0 that will be [1, 2], [1] and [2]
                  for(const nested of combinations(length, m - 1, i + 1)) {
                  // Yield the nested path, e.g. [0, 1], [0, 1, 2] and [0, 2]
                  yield [i, ...nested];
                  }
                  // If the minimum length is already reached yield the index itself
                  if(m <= 1) yield [i];
                  }
                  }


                  Now for every combination, we just have to multiply the probabilities and add them up:



                   let result = 0;

                  for(const combination of combimations(input.length, m))
                  result += combination.reduce((prev, i) => prev * input[i], 1);






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 21 '18 at 18:21

























                  answered Nov 21 '18 at 17:47









                  Jonas WilmsJonas Wilms

                  58.4k43151




                  58.4k43151






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417632%2fflexible-algorithm-to-calculate-possibilities-of-all-possible-scenarios%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      'app-layout' is not a known element: how to share Component with different Modules

                      android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                      WPF add header to Image with URL pettitions [duplicate]