Struggling with rearranging letters in a W shape using arrays. My code seemed to go down instead of reaching level 0.
Code snippet:
const row = totalLevel =>{
let array = []
for(let i =0;i<totalLevel;i++){
array.push([])
}
return array
}
const inside = (str,rows) =>{
let rowLevel = row(rows)
// console.log(rowLevel)
let level = 0
for(let i =0;i<str.length;i++){
rowLevel[level].push(str[i])
if(level<rows-1){
level++
}
else if(level === rows-1){
level--
}
}
console.log(rowLevel)
let result =''
for(let i =0;i<rowLevel.length;i++){
result+= `Level ${i}: ${rowLevel[i]} \n`
}
return result
}
Driver code:
console.log(inside('DARWINFOX', 3))
// Illustration :
// D I X
// A W N O
// R F
// expected result : DIXAWNORF
// Final result will be:
// Level 1 : D, I, X
// Level 2 : A, W, N, O
// Level 3 : R, F