Last active
December 11, 2022 21:34
-
-
Save aarongilly/a6d920aa7676a6b7117cd4f546fed8d4 to your computer and use it in GitHub Desktop.
Dominoes Valid Train Finder
This file contains 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
/** | |
* Will find all permutations of the given set of 'dominos' that can | |
* be laid in a single line end to end to form a valid domino train. | |
*/ | |
function start() { | |
const dominos = ['05','60','54','66','40','43','21','35','03','24','32','52','11']; | |
dominos.forEach(domino=>{ | |
let remaining = dominos.filter(d=>d!=domino); | |
lookForValidTrain([domino], remaining); | |
}) | |
} | |
/** | |
* @param {string[]} startingWith | |
* @param {string[]} remainingSet | |
*/ | |
function lookForValidTrain(startingWith, remainingSet){ | |
if(remainingSet.length == 0){ | |
console.log('valid train found:' + startingWith.join(', ')); | |
}else{ | |
const last = startingWith.slice(-1)[0]; | |
remainingSet.forEach(remainingDomino=>{ | |
if(last.substring(1) === remainingDomino.substring(0,1)){ | |
const newRemaining = remainingSet.filter((remaining)=>remaining!=remainingDomino); | |
const newStarting = [...startingWith, remainingDomino]; | |
lookForValidTrain(newStarting, newRemaining); | |
} | |
//to check for matches using the other orientation | |
//the first "if" is to prevent double dominos from creating two outputs (both their orientations are the same) | |
if(remainingDomino.substring(1) !== remainingDomino.substring(0,1)){ | |
if(last.substring(1) === remainingDomino.substring(1)){ | |
const newRemaining = remainingSet.filter((remaining)=>remaining!=remainingDomino); | |
const newStarting = [...startingWith, remainingDomino.substring(1) + remainingDomino.substring(0,1)]; | |
lookForValidTrain(newStarting, newRemaining); | |
} | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment