entrada [1,8,9]
salida [[1],[1,8],[1,8,9],[8],[8,9],[9]]
Parece una matriz de subconjuntos, pero me gustaría obtener este resultado con dos punteros. digamos izquierdaP=0, derechaP=0; y luego, al usar for loop, la P derecha aumentará hasta el final de la matriz hasta que no haya más elementos y luego la P izquierda se moverá en 1 ...
1 -> [1], [1,8],[1,8,9]
8 -> [8],[8,9]
9 -> [9]
function solution(arr) { let totalArr = []; let leftP = 0; for(let rightP=0; rightP<arr.length; rightP++) { totalArr.push(arr[rightP]); // this is where i'm kinda stuck while() } }Puede lograr esto fácilmente usando solo 2 bucles for como lo está haciendo:
i está aquí leftP y j está aquí rightP
const arr = [1, 8, 9]; const result = []; for (let i = 0; i < arr.length; ++i) { let temp = [arr[i]]; result.push([...temp]); for (let j = i + 1; j < arr.length; ++j) { temp.push(arr[j]); result.push([...temp]); } temp = []; } console.log(result); /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }¡Simplemente corte la matriz usando los dos punteros!
Solución de trabajo a continuación:
const arr = [1, 8, 9]; const solution = (arr) => { const resArr = []; for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j <= arr.length; j++) { resArr.push(arr.slice(i, j)); } } return resArr; }; console.log(solution(arr));Simplemente traduciría su lógica en código, teniendo en cuenta que necesitaría dos bucles anidados.
function solution(arr) { let totalArr = []; for (let left = 0; left < arr.length; left++) { totalArr.push([]); for (let right = left + 1; right <= arr.length; right++) { totalArr[left].push(arr.slice(left, right)); } } return totalArr; } console.log(JSON.stringify(solution([1, 8, 9]))); .as-console-wrapper { max-height: 100% !important; top: auto; } (tenga en cuenta que esto los agrupa según la left , para que la matriz sea plana):
function solution(arr) { let totalArr = []; for (let left = 0; left < arr.length; left++) { for (let right = left + 1; right <= arr.length; right++) { totalArr.push(arr.slice(left, right)); } } return totalArr; } console.log(JSON.stringify(solution([1, 8, 9]))); .as-console-wrapper { max-height: 100% !important; top: auto; }