Issue
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)
Solution
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.
function findSolutionsRecursive(currentSolution, pieceSet, depth, maxDepth) {
if (depth === maxDepth) {
return [currentSolution];
} else {
let solutions = [];
const nextSolutions = findSolutionsWithOneMorePiece({ currentSolution, pieceSet });
for (const nextSolution of nextSolutions) {
solutions = solutions.concat(findSolutionsRecursive(nextSolution, pieceSet, depth + 1, maxDepth));
}
return solutions;
}
}
const maxDepth = 9;
const solutions = findSolutionsRecursive(currentSolution, currentPieceSet, 0, maxDepth);
Code is not tested, but might work, or should be able to give you an idea for an approacht
Answered By - Carsten Løvbo Andersen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.