HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Testing distance between characters in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
distancebetweentestingcharactersstring

Problem

Here is another challenge from Coderbyte. I found this one challenging, although not quite as much as the previous two I've posted. Based on the feedback I received on my earlier posts, I structured this solution as a function. It is probably better than my previous solutions but still could be improved.

In particular, I am wondering if there is a way to condense my while loops, perhaps by determining the a and b indices at the same time or maybe by building a helper function? It seems like there is redundancy there. Resetting the index variable strikes me as particular clumsy or inelegant, but it had to happen somehow. I'm also not to happy with splitting the string and then joining the modified array to deal with the spaces. Any feedback on these issues or other suggestions to improve the code would be greatly appreciated.

Here's the challenge, slightly modified:


Take a str parameter and return true if there are any occurrences of
characters "a" and "b" separated by exactly 3 places (i.e. "lane
borrowed" would result in true because there is exactly three
characters between a and b). Otherwise return the string false.

(While I was posting this, I realized I had not accounted for spaces. My interpretation of the instructions is that spaces do not count as characters. I have updated my code accordingly.)

```
var str = prompt("Please enter a string: ").split("");

function test(str){
var index = 0;
var arrayA = [];
var arrayB = [];

while (index >= 0){ //removes spaces
index = str.indexOf(" ");
if (index >= 0) {
str.splice(index, 1);
}
}
str=str.join("");
index = 0;

while(str.indexOf("a",index) != -1){ //Identifies indices of "a"
arrayA.push(str.indexOf("a",index));
index = str.indexOf("a", index)+1;
}

index=0;

while(str.indexOf("b",index) != -1){//Identifies indicies of "b"
arrayB.push(str.indexOf("b",index));
index = str.indexOf("b", index)+1;
}

for(var i=0; i<arrayA.length; i++){//determines if any a's and b's

Solution

I would recommend using a regular expression. Regex is designed for solving pattern matching and string manipulation problems. Although it can look esoteric and terse it is well worth the effort to learn since it is very powerful and fairly ubiquitous. It is very likely your programming language/shell/editor of choice supports a flavor of regex.

var str = prompt("Please enter a string: ");

function test(str){ 
  return /a\w{3}b/.test(str) || /b\w{3}a/.test(str); 
}

console.log(test(str));

Code Snippets

var str = prompt("Please enter a string: ");

function test(str){ 
  return /a\w{3}b/.test(str) || /b\w{3}a/.test(str); 
}

console.log(test(str));

Context

StackExchange Code Review Q#32735, answer score: 3

Revisions (0)

No revisions yet.