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 returntrue
if there are any occurrences of characters "a" and "b" separated by exactly 3 places (i.e. "lane borrowed" would result intrue
because there is exactly three characters between a and b). Otherwise return the stringfalse
.
(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 are 3 characters apart
for(var j=0; j<arrayB.length; j++){
if (Math.abs(arrayA[i]-arrayB[j]) === 3){
return true;
}
}
}
return false;
}
console.log(test(str));
Here's a revised version:
function ABCheck(str) {
str = str.split("");
for (var i = 0; i<str.length; i++){
if (str[i] === " "){
str.splice(i,1);
console.log(str);
}
}
for (var i = 0; i< str.length; i++){
if (str[i] === "a" && (str[i-3] === "b" || str[i+3] === "b")){
return true;
}
}
return false;
}