Hi everyone
I have been trying my hardest this whole day to solve this problem but I’m stuck and don’t want to find the answer on google.
I know that there will be easier and simpler solutions but I wanted to stick with the way I wanted to solve.
Please help find and correct my mistakes in this code:
function reachZeroPosition(arrTemp, arrOrig, i) {
for (var k = 0; k < arrTemp.length; k++) {
if (arrTemp.indexOf(arrOrig[i]) !== 0) {
var a = arrTemp.shift();
}
}
return arrTemp;
}
function countWords(str) {
var words = str.split(" ");
var temp = [];
var result = [];
var fResult = [];
var found;
var count = 0;
for (var j = 0; j < words.length; j++) {
temp = words.slice();
found = temp.indexOf(words[j]);
for (var i = 0; i < words.length; i++) {
if (found !== -1) {
temp = reachZeroPosition(temp, words, j);
if (count === 0) {
result[j] = temp.shift();
}
result[j + 1] = ++count;
} else {
break;
}
found = temp.indexOf(words[j]);
}
count = 0;
fResult.push(result);
}
return fResult;
}
countWords("ask a bunch get a bunch");
Here’s an explanation of what I have done:
1- Converted String to array of words.
2- Copied the array to a temp array.
3- This temp will be shortened by the function above to make the desired word at position 0.
4- I keep track of Count and store both word and count in an array.
5- temp will be updated from words for each word.
6- words is never changed that’s why I used slice to copy.
6- I push the result to a final array.
There’s an issue in the logic, I tried debugging but I got nowhere
Please help
What do you think? @KoniKodes @lasjorg @shimphillip