Skip to content

Instantly share code, notes, and snippets.

@ditam
Created August 30, 2015 18:22
Show Gist options
  • Save ditam/79ba8b882bfdaab4b53f to your computer and use it in GitHub Desktop.
Save ditam/79ba8b882bfdaab4b53f to your computer and use it in GitHub Desktop.
fizzbuzz extrapolation function - sample for article at ditam.github.io
function extractPatterns(sample){
var markers = {};
sample.forEach(function(element, i){
if(isNaN( Number(element) )){
var parts = element.split(/(?=[A-Z])/);
parts.forEach(function(part){
if(!markers[part]){
markers[part] = [];
}
markers[part].push(i+1);
});
}
});
var markersArray = [];
for(key in markers){
if(markers.hasOwnProperty(key)){
markersArray.push({
marker: key,
matchingElements: markers[key]
});
}
}
return markersArray;
}
function getPredicate(divisor){
return function(element){
return !(element%divisor);
}
}
function generatePossiblePatterns(length){
var generatedPatterns = [];
for(var i=1;i<=length;i++){
var predicate = getPredicate(i);
var interval = [];
for(var j=1;j<=length;j++){interval.push(j);}
var outcome = interval.filter(function(element){
return predicate(element);
});
generatedPatterns.push(outcome);
}
return generatedPatterns;
}
function fizzBuzz(length, markers){
var range = [];
for(var i=1;i<=length;i++){ range.push(i); }
range.map(function(i){
return markers.reduce(function(output,marker){
if(i%marker.number === 0){
output+=marker.marker;
}
return output;
},'');
})
.map(function(output, index){
return output == ''? (index+1) : output;
})
.forEach(function(output){
console.log(output);
});
}
function extrapolateFizzBuzz(sampleOutputs, length){
var extractedPatterns = extractPatterns(sampleOutputs);
var generatedPatterns = generatePossiblePatterns(sampleOutputs.length);
var markers = extractedPatterns.map(function(ePattern){
return {
marker: ePattern.marker,
number: generatedPatterns.filter(function(gPattern){
return ePattern.matchingElements.every(function(element, index){
return gPattern[index] === element;
});
})[0][0]
}
});
fizzBuzz(length, markers);
}
extrapolateFizzBuzz([1,2,'Fizz',4,'Buzz'], 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment