I’m struggling to simplify a piece of nested code, without success, though.
Every time I have to deal with recursion, I’m having a hard time. If anyone can help me with that, I’ll be really happy 🙂
Here’s the beast :
const solutions: Solution[] = []
for (const sol of [currentSolution]) {
const solutionsFirstPieceOnly = findSolutionsWithOneMorePiece({currentSolution: sol, pieceSet: currentPieceSet})
for (const sol1 of solutionsFirstPieceOnly) {
const solutionsSecondRank = findSolutionsWithOneMorePiece({currentSolution: sol1, pieceSet: currentPieceSet})
for (const sol2 of solutionsSecondRank) {
const solutionsThirdRank = findSolutionsWithOneMorePiece({currentSolution: sol2, pieceSet: currentPieceSet})
for (const sol3 of solutionsThirdRank) {
const solutionsFourthRank = findSolutionsWithOneMorePiece({currentSolution: sol3, pieceSet: currentPieceSet})
for (const sol4 of solutionsFourthRank) {
const solutionsFifthRank = findSolutionsWithOneMorePiece({currentSolution: sol4, pieceSet: currentPieceSet})
for (const sol5 of solutionsFifthRank) {
const solutionsSixthRank = findSolutionsWithOneMorePiece({currentSolution: sol5, pieceSet: currentPieceSet})
for (const sol6 of solutionsSixthRank) {
const solutionsSeventhRank = findSolutionsWithOneMorePiece({currentSolution: sol6, pieceSet: currentPieceSet})
for (const sol7 of solutionsSeventhRank) {
const solutionsEighthRank = findSolutionsWithOneMorePiece({currentSolution: sol7, pieceSet: currentPieceSet})
for (const sol8 of solutionsEighthRank) {
const solutionsNinethRank = findSolutionsWithOneMorePiece({currentSolution: sol8, pieceSet: currentPieceSet})
solutionsNinethRank.forEach((solution) => {if (solution.length) solutions.push(solution)})
}
}
}
}
}
}
}
}
}
console.log(solutions)
2
Answers
You could try make a function that you can use recursively. This way you should be able to achieve the same function as the code in the question.
Code is not tested, but might work, or should be able to give you an idea for an approacht
This is a good candidate for a (recursive) generator function: