Home > Software engineering >  Find all possibilities of a percentage distribution (2 floating points) for do something for each ca
Find all possibilities of a percentage distribution (2 floating points) for do something for each ca

Time:01-07

Here is the problem, i need to run a function for each percentage possibility (2 floating points). So for that, i need an algorithm that identify each case for n elements.
For example:
An array of 2 elements would have the following distribution:

[1.00, 0.00]
[0.99, 0.01]
[0.98, 0.02]
[0.97, 0.03]
[...]

But in cases of more elements, this is more complexity:

[1.00, 0.00, 0.00, 0.00]

[0.99, 0.01, 0.00, 0.00]
[0.99, 0.00, 0.01, 0.00]
[0.99, 0.00, 0.00, 0.01]

[0.98, 0.02, 0.00, 0.00]
[0.98, 0.01, 0.01, 0.00]
[0.98, 0.01, 0.00, 0.01]
[0.98, 0.00, 0.02, 0.00]
[0.98, 0.00, 0.01, 0.01]
[0.98, 0.00, 0.00, 0.02]

[0.97, 0.03, 0.00, 0.00]
[0.97, 0.02, 0.01, 0.00]
[0.97, 0.02, 0.00, 0.01]
[0.97, 0.01, 0.02, 0.00]
[0.97, 0.01, 0.00, 0.02]
[0.97, 0.01, 0.01, 0.01]
[0.97, 0.00, 0.03, 0.00]
[0.97, 0.00, 0.00, 0.03]
[0.97, 0.00, 0.02, 0.01]
[0.97, 0.00, 0.01, 0.02]
[...]

Does anyone know a way to find these cases for n elements?
Its not necessary to save the array in memory, i just run a function or a part of code for each one of these cases.
This code/function could be just a print of the case.

I accept any language for response, thanks for your attention.

CodePudding user response:

A mix of itertools and filter might do the work, I don't know how slow it could get with bigger n. Try something like this (needs refinement):

import numpy as np
from itertools import combinations

n=3

percentages = list(np.arange(0,1,0.01))

result = filter(lambda e: sum(list(e))==1, combinations(percentages, n))

for row in result:
    print(row)

CodePudding user response:

The solution that i created was that:

import numpy as np

n=4

f = open("possibilities.txt", "w")
def getPossibilities(array):
  if array == None:
    array = []
  
  alreadySummed = sum(array)
  rest = round(1 - alreadySummed, 2)

  if(len(array) == n-1):
    newArr = [*array, rest]
    f.write(str(newArr)   "\n")
    return

  allRestPossibilities = np.arange(0, rest   0.01, 0.01)
  for possibility in allRestPossibilities:
    newArr = [*array, round(possibility, 2)]
    getPossibilities(newArr)

getPossibilities(None)

f.close()

Basically, for each initial possibility, the code search for the rest possibilities. And in cascade, show me all the possibilities

  •  Tags:  
  • Related