jeudi 2 décembre 2021

How can I generate all the combos taking into account the weight of each item in Javascript? [duplicate]

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




Aucun commentaire:

Enregistrer un commentaire