0

I have been struggling for several days with the following algorithm I need.

What I need to generate are the totality of combos taking into account the weight in their generation.

// Generate composition depending on weight.
// The weight is a value from 1 to 100, representing the importance in the generation.
// ex.: A layer with 1% should only display 1% of the total generated.

const layers = [
    [
    { id: 1, weight: 1 },   // Shows 1 time
    { id: 2, weight: 9 },   // Shows 9 times
    { id: 3, weight: 15 },  // Shows 15 times
    { id: 4, weight: 25 },  // Shows 25 times
    { id: 5, weight: 50 },  // Shows 50 times
  ],
  [
    { id: "a", weight: 50 },    // Shows 50 times
    { id: "b", weight: 25 },    // Shows 25 times
    { id: "c", weight: 15 },    // Shows 15 times
    { id: "d", weight: 9 },     // Shows 9 times
    { id: "e", weight: 1 },     // Shows 1 times
  ], 
    [
    { id: "_", weight: 15 },    // Shows 15 times
    { id: "-", weight: 25 },    // Shows 25 times
    { id: ".", weight: 50 },    // Shows 50 times
    { id: ",", weight: 9 },     // Shows 9 times
  ]
  // ... There could be more collections
]

const combTotal = layers[0].length * layers[1].length * layers[2].length // => 100


// Expect result:
 
[ 
  [5, "d", "."], 
  [2, "a", "_"],
  [4, "a", ","],
  // ...
]

Generating the whole composition without weights is simple, but the calculation to take into account the weight is costing me more than it should.

If someone could show me some reference to unlock me, it would be great.

Best regards

jpaask
  • 1
  • Are the weights probabilities of those elements occurring in relation to their peers in one group? – user1984 Dec 02 '21 at 10:00
  • Please see the linked question's answers and the answers to the other questions shown by [this search](/search?q=%5Bjs%5D+weighted). More about on-site searching [here](/help/searching). You can also search with your favorite search engine by adding `site:stackoverflow.com` to the query. – T.J. Crowder Dec 02 '21 at 10:00

0 Answers0