Skip to content

Instantly share code, notes, and snippets.

@jearle
Last active August 29, 2015 14:27
Show Gist options
  • Save jearle/3b36bc7ed8acae840953 to your computer and use it in GitHub Desktop.
Save jearle/3b36bc7ed8acae840953 to your computer and use it in GitHub Desktop.
/*
Create a function that figures out the distribution of spots per generation
where the children can add only 1 spot based on the number of spots their parent
have. The children must also have at least as many spots as their parent.
*/
var childrenPerGeneration = 3;
function coinFlip () {
return Math.round(Math.random()) === 1;
}
function getSpots (parentSpotCount) {
return Math.ceil((Math.random() * (parentSpotCount + 1)));
}
function getNumberOfChildrenThisGeneration (generation) {
return Math.pow(3, generation);
}
function getParentIndex (child) {
return Math.floor(child / childrenPerGeneration);
}
function getSpotCount (generation, parents, child) {
if (generation === 0) {
return 0;
}
var parentsSpotCount = parents[getParentIndex(child)];
if (coinFlip()) {
return parentsSpotCount;
}
return getSpots(parentsSpotCount);
}
function getGeneration (generation, parents) {
var numberOfChildrenThisGeneration = getNumberOfChildrenThisGeneration(generation);
var children = [];
for (var child = 0 ; child < numberOfChildrenThisGeneration ; child++) {
children.push(getSpotCount(generation, parents, child));
}
return children;
}
function getGenerations (numberOfGenerations) {
var parents = [];
var generations = [];
for (var generation = 0; generation < numberOfGenerations ; generation++) {
var children = getGeneration(generation, parents);
parents = children;
generations.push(children);
}
return generations;
}
// Returns an array of objects.
//
// Each index in the array is a generation.
//
// Each object in the array is a set of key
// value pairs where the key is the number
// of spots and the value is the amount of
// those spots within that generation.
function getDistributions (generations) {
return generations.map(function (generation) {
var result = {};
generation.forEach(function (spots) {
if (!result[spots]) {
result[spots] = 1;
} else {
result[spots] += 1;
}
});
return result;
});
}
var generations = getGenerations(3);
var distributions = getDistributions(generations);
console.log(generations);
console.log(distributions);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment