Here is a slightly modified challenge from Coderbyte:
Determine if a given string is an acceptable. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.
For whatever reason, I have struggled mightily with this challenge. I tried to use a regular expression in my Booleans, I tried cascading if statements, I tried a while statement surrounding if statements, I tried to structure my code as a function. After hours of failure, I finally resorted to the following:
var str = prompt("Please enter a test string: ").split(""); answer = "true"; if (((str[0] != "+") && (str[0] != "=")) || ((str[str.length-1] != "+") && (str[str.length-1] != "="))){ answer = "false"; } for (var i = 1; i < str.length-1; i++){ if (((str[i] != "+") && (str[i] != "=")) && (str [i-1] != "+" || str [i+1] != "+")){ answer = "false"; } } console.log(answer);
I think it works, but of all the possible solutions to this problem, I am guessing that it is toward the bottom in terms of efficiency and elegance. I'd really appreciate some guidance on how this could be improved.
Below is one of my "solutions" that did not work. Among other things, the Booleans are not evaluating correctly. I must be using the regular expressions incorrectly.
var str = prompt("Please enter a test string: ").split(""); answer = "true"; if ((str[0] === /[a-z]/gi) || (str[str.length-1] === /[a-z]/gi)){ answer = "false"; } for (var i = 1; i < str.length-1; i++){ if (str[i] === /[a-z]/gi && (str [i-1] != "+" || str [i+1] != "+")){ answer = "false"; } } console.log(answer);
+
symbol" — does that mean immediately surrounded, or would+ab+
be acceptable? Is it acceptable for+
symbols to be shared, like+a+b+
?\$\endgroup\$