Created
May 12, 2016 09:34
-
-
Save eedrah/6aa0a724c3acf1661103e74e78ca5517 to your computer and use it in GitHub Desktop.
Shuffler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var names = [ | |
'Bob', | |
'Sarah', | |
'Josh', | |
'Ben', | |
'Natalie', | |
'Richard' | |
]; | |
function fillInCombos (combosSoFar, remainingInput) { | |
if (remainingInput.length <= 0) { | |
return combosSoFar; | |
} | |
var inputNumber = remainingInput.pop(); | |
var newCombos = []; | |
combosSoFar.forEach(function (combo) { | |
combo.forEach(function (entry, index) { | |
if (entry === undefined) { | |
var newCombo = combo.slice(0, index).concat([inputNumber]).concat(combo.slice(index + 1)); | |
newCombos.push(newCombo); | |
} | |
}); | |
}); | |
return fillInCombos(newCombos, remainingInput); | |
} | |
function generateAllCombos (input) { | |
var undefinedArray = Array.apply(null, Array(input.length)); | |
return fillInCombos([undefinedArray], input.slice()); | |
} | |
function zip (input1, input2) { | |
if (input1.length !== input2.length) { | |
console.error('Cannot zip different lengths'); | |
return; | |
} | |
var result = []; | |
input1.forEach(function (item1, i) { | |
result.push([item1, input2[i]]); | |
}); | |
return result; | |
} | |
function generateAllValidPairings (input) { | |
var combos = generateAllCombos(input); | |
var validPairings = []; | |
combos.forEach(function (combo) { | |
var pairing = zip(input, combo); | |
var isValid = true; | |
pairing.forEach(function (pair) { | |
if(pair[0] === pair[1]) { | |
isValid = false; | |
} | |
}); | |
if (isValid) { | |
validPairings.push(pairing); | |
} | |
}); | |
return validPairings; | |
} | |
function displayPairing (pairing) { | |
var pairs = []; | |
pairing.forEach(function (pair) { | |
pairs.push(pair[0] + ' -> ' + pair[1]); | |
}); | |
return pairs.join('; '); | |
} | |
function displayAllPairings (pairings) { | |
var pairingArray = []; | |
pairings.forEach(function (pairing) { | |
pairingArray.push(displayPairing(pairing)); | |
}); | |
return pairingArray.join('\n'); | |
} | |
console.log(displayAllPairings(generateAllValidPairings(names))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment