//const numBeats = Math.ceil(Math.random()*9); //let resultString = ''; //const instructionPosibilities = [ 'n', 'p', 'm', 'b' ] //for(let i = 1; i <= numBeats; i++){ //const instructionIndex = Math.floor(Math.random()*instructionPosibilities.length); //resultString += instructionPosibilities[instructionIndex] + ' '; //} //console.log(resultString); //5: 3+2, 2+3 //6: 2+2+2, 3+3 //7: 2+2+3, 2+3+2, 3+2+2 //8: 2+3+3, 3+2+3, 3+3+2 //9: 3+3+3, 2+2+2+3, 2+2+3+2, 2+3+2+2, 3+2+2+2 const breakDown = (node)=>{ if(node.value < 4){ return node } //2 path node.twoPath = {}; node.twoPath.left = { value: 2 } node.twoPath.right = breakDown({value:node.value-2}) //3 path if(node.value > 4){ node.threePath = {} node.threePath.left = { value: 3 } node.threePath.right = breakDown({value:node.value-3}) } return node; } const tree = breakDown({value:9}); console.dir(tree, {depth:null}); const getLeaves = (node)=>{ if(node.twoPath === undefined){ return node.value; } let twoPathResult = []; const twoPathLeftValue = getLeaves(node.twoPath.left);//2 const twoPathRightValue = getLeaves(node.twoPath.right);//[2,2] if(Number.isInteger(twoPathRightValue)){ twoPathResult[0] = twoPathLeftValue; twoPathResult[1] = twoPathRightValue; } else { if(Number.isInteger(twoPathRightValue[0])){ twoPathRightValue.unshift(twoPathLeftValue); } else { twoPathRightValue[0].unshift(twoPathLeftValue) twoPathRightValue[1].unshift(twoPathLeftValue); } twoPathResult = twoPathRightValue; } let threePathResult = []; if(node.threePath !== undefined){ const threePathLeftValue = getLeaves(node.threePath.left); const threePathRightValue = getLeaves(node.threePath.right); if(Number.isInteger(threePathRightValue)){ threePathResult[0] = threePathLeftValue; threePathResult[1] = threePathRightValue; } else { threePathResult[0] = threePathLeftValue; threePathResult = threePathResult.concat(threePathRightValue); } } if(threePathResult.length === 0){ return twoPathResult; } else { if(Number.isInteger(twoPathResult[0])){ return [twoPathResult, threePathResult] } else { twoPathResult.push(threePathResult) return twoPathResult; } } } const leaves = getLeaves(tree); console.dir(leaves, {depth:null});