0

i have tried to make a function count each character in a string using recursion, for 2 days now. I tried to write some pseudo-code, but i can't really implement it.

Pseudocode:

write a function that takes text as a parameter

set a counter, for each element

set a result, using key,value for each character in element

base case: if we only have 1 string, then return the character and string

else return function-1 until the last element is hit.

var tekst = "We have to count strings";

function countStrings(tekst) {
  var count = 0
  var result = {}

  if (count > tekst.lentgh) {
    count++
    return result
  } else {
    return countStrings(tekst-1) 
  }
}
console.log(countStrings(tekst))

2 Answers 2

1

Consider using this logic:

var tekst = "We have to count strings";

function countStrings(tekst) {
    if (tekst.length == 0) {
        return 0;
    }

    return 1 + countStrings(tekst.substring(1));
}

console.log(countStrings(tekst))

The approach here is, at each step of the recursion, to return 1 plus whatever the length of the substring from the next character onwards is. That is, we recurse down the input string, one character at a time, building out the length. The base case here occurs when the input to countStrings() happens to be empty string. In this case, we just return 0, and stop the recursive calls.

Sign up to request clarification or add additional context in comments.

1 Comment

i see your code works, but this one counts the amount of string. not the amount characters and strings - but i might be able to do something with it, thanks
0

I decided to attempt this problem and this is what I came up with. Definitely a challenging problem so don't feel bad if you didn't get it:

var countStrings = function(tekst) {
    if (tekst.length === 0) return {};
  
    var obj = countStrings(tekst.slice(1));
  
    if (obj[tekst[0]]) {
        obj[tekst[0]] += 1;
    } else {
        obj[tekst[0]] = 1;
    }
  
    return obj;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.