Tengo la siguiente oración de cadena como entrada
'test string of whole words'Y como salida, necesito una matriz de cadenas de diferentes combinaciones de palabras, incluido el resto de las palabras como esta
test string of whole words teststring of whole words test stringof whole words test string ofwhole words test string of wholewords teststringof whole words test stringofwhole words test string ofwholewords teststringofwhole words test stringofwholewords teststringofwholewordsIntenté escribir el siguiente código para lograr el resultado anterior, pero solo funciona para eliminar un espacio a la vez. Este código es solo una prueba mía. No es necesario actualizarlo/ampliarlo si no es así. Puedes empezar desde cero
function getSpaceIndices(str) { let spaceIndices = [] for (let i = 0; i < str.length; i++) { if (str[i] === " ") { spaceIndices.push(i) } } return spaceIndices } let str = 'test string of whole words' let strArray = str.split(" "); let combinationArray = [] // let spaceRemoveCount = 1 let spaceIndices = getSpaceIndices(str) let currentIndex = 0 while (currentIndex < spaceIndices.length) { let tempStr = str.slice(0, spaceIndices[currentIndex]) + str.slice(spaceIndices[currentIndex] + 1); combinationArray.push(tempStr); currentIndex++ } console.log(combinationArray);Ayude a lograr la matriz de salida anterior desde la cadena de entrada anterior
Debería poder hacerlo con bastante facilidad con la recursividad, solo para empezar, puede intentar lo siguiente
function getSpaceIndices(str) { let spaceIndices = [] for (let i = 0; i < str.length; i++) { if (str[i] === " ") { spaceIndices.push(i) } } return spaceIndices } let str = 'test string of whole words' let strArray = str.split(" ").filter(s => s != " "); let combinationArray = [] // let spaceRemoveCount = 1 /* let spaceIndices = getSpaceIndices(str) let currentIndex = 0 while (currentIndex < spaceIndices.length) { let tempStr = str.slice(0, spaceIndices[currentIndex]) + str.slice(spaceIndices[currentIndex] + 1); combinationArray.push(tempStr); currentIndex++ } console.log(combinationArray); */ function print(str,current, start, merge){ let s = "" if(merge){ s =current+str[start]; } else{ s = current+" "+str[start] } start++; if(start >= str.length){ console.log(s); return; } print(str,s,start,true); print(str,s,start,false); } print(strArray,"",0);