Algorithm for controlling possibility-space within item spawning

45 Views Asked by At

I have trouble finding a good solution (and a good title) to the following problem:

Say I have a blueprint of a sphere. This sphere-blueprint contains an array of unique colors. Each sphere will take on a random color of its color array after spawning.

Now I have a Spawner, which holds a list of say 100 different sphere-blueprints it could spawn. Each of these can have differing color arrays. The Spawner now tries to spawn 10 spheres from that list.

After spawning its now time for the spheres to take on their colors. However, no sphere can take on a color another sphere has taken on before! The first sphere takes on a random color from its color array. Each subsequent sphere is are able to see the color previous spheres have taken on and are able to chose a color that hasn't been chosen by any previous sphere.

How can I make sure that I don't spawn a sphere, which could be left with no more color-choices, because all colors within its color-array have been already taken by other spheres?

I tried to prototype this using sticky notes with numbers on them, but it sure is not a trivial problem

1

There are 1 best solutions below

2
Louis Ricci On

Each of your unique "blueprint" needs to contain the following...

  • ColorArray - pre shuffle it so it's already random
  • ColorPickerIndex - 0 to size of Color Array

Once your list of "100 blueprints" is created you need to combine all of the unique colors into a GlobalColorHashSet.

Each "spawn" (instance) of a "blueprint" needs to contain the following...

  • Index - into the list of "100 blueprints"
  • Color - the chosen unique color

Example spawn blueprint method....

// list of  "100 blueprints"
var blueprints = ...
// set of all unique colors in all of the "blueprints" 
var globalColorsHashSet = ...
// list of "spawn" instances
var spawned = [];

// spawn a blueprint or throw an error
function spawnBlueprint(blueprintIndex) {
  // get the requested blueprint
  var bp = blueprints[blueprintIndex];
  // attempt to spawn the blueprint
  while(true) {
    // blueprint has exhausted its colors so throw an error
    if(bp.colorPickerIndex >= bp.colorArray.length) {
      throw "No Colors Left for this blueprint.";
    }
    // store possible spawn color
    var color = bp.colorArray[colorPickerIndex];
    // increment the color picker index
    bp.colorPickerIndex++;
    // if the color hasn't been used yet, then spawn an instance
    if(globalColorHashSet.has(color)) {
      // remove the color from the global list
      globalColorHashSet.delete(color);
      // create the instance
      var spawn = new Spawn(blueprintIndex, color);
      // save the spawn instance
      spawned.push(spawn);
      // return the spawn instance
      return spawn;
    }
    // loop - try the next color
  }
}