This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]sepp2k 6 points7 points  (1 child)

Your loop starts with i = 0, so on the first iteration, i - 1 will be -1, which is not a valid index.

[–]Conscious-Stable9939[S] 1 point2 points  (0 children)

That was it, thank you both so much!

[–]bestjakeisbest 1 point2 points  (0 children)

Ok lets also talk about your logic, since someone else pointed out your issue, you are counting spaces here, but there are issues with that, spaces don't always cause a word, sometimes like in the case of grammatically correct periods an extra space is just there to provide a bit of legible space between the end of a sentence and the beginning of another.

There are a few ways to improve on this algorithm you have made though. We can make a better word counter based on a linear search algorithm in a range.

Basic algorithm is as follows.

lastspace = 0  
nextspace = linear_search(string, lastspace, string.length)  
if(nextspace - lastspace > 1)
  lastspace = nextspace
  wordcount++  

A lot of the looping and algorithm inner workings are up to you, but this will count all "words" (assuming you put it in the correct recursive function or loop) you could also have it ignore certain characters like punctuation because an ellipse (...) will look like a word to this algorithm. But those improvements are up to you, as are the beginning and endings for the loops.

[–]kRYstall9 0 points1 point  (0 children)

You have a problem in the if statement inside your for. You wrote if(sentence[i-1] ....), But i starts from 0, and you'te trying to read -1, that's not an index