This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
I'm working on a challenge in CodeWars and am coming into an error that I can't figure out.
The goal of the exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string.
I decided to check if the first element reference is or is not equal to the last element reference. If it is equal, it is only used once, if it is not, there is a duplicate. Here is my code:
---------------------------
function duplicateEncode(word){
var array = word.toLowerCase().split("");
for (i=0; i<array.length; i ) {
var indexValue = array[i];
if (array.indexOf(indexValue) !== array.lastIndexOf(indexValue)) {
array[i] = ")";
} else {
array[i] = "(";
}
}
return array.join("");
}
-------------------------------
The sample tests are:
-------------------------------
Test.assertEquals(duplicateEncode("din"),"(((");
Test.assertEquals(duplicateEncode("recede"),"()()()");
Test.assertEquals(duplicateEncode("Success"),")())())","should ignore case");
Test.assertEquals(duplicateEncode("(( @"),"))((");
---------------------------------
When run, I get the following error:
------------------------------
Test Results:
Test Passed: Value == '((('
Expected: '()()()', instead got: '()()((
'should ignore case - Expected: ')())())', instead got: ')()(()('
Expected: '))((', instead got: ')((('
-------------------------------
So the final duplicate variable is showing the same first and last index. To clarify with an example, Test #2 inputs the string 'recede'. The r, e(#1), c, e(#2), and d all translate properly to their respective parentheses. The last e - #3 aka array[5] - is false on the if statement, thus the parenthesis is '(' instead of ')'.
Now the maddening part - I've iterated through the code in my console and get the same result. HOWEVER, if I skip the first 5 iterations, and jump right to the final e - array[5] - the if statement comes up true and the proper parenthesis is put in.
If someone could help educate me on why this is happening, where I'm going wrong, and/or what I can do to fix it, I would really appreciate it.
Also, this is literally my first time sharing code and asking for help in my learning to program journey, so hopefully I was clear. Happy to clarify anything to help get to the bottom of this.
Thanks for reading!
Subreddit
Post Details
- Posted
- 4 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnprogra...