If you have a lot of time to spend, please look at this post and my code. It is not simple. But, I am hoping someone with experience would be kind enough to take the time to help.
I have enjoyed working on this project. But, I am a bit stumped about a small part of my code that didn’t work.
In my design and code I went through the given array and added the numbers. When I found a pair where the sum equaled the given number, I put the indexes of those numbers into a new array. I then continued going through the given array of numbers to find more pairs. During this continuation, I would check the numbers against the new array to make sure they weren’t already used. I used the “indexOf” method to do so. But, this didn’t work for the second to last test case.
I eventually found a different way to solve this issue. I replaced the numbers in the given array with “X” so they couldn’t be used again. While that worked with all the test cases and completed the project, it didn’t sit well with me. I think it is a valid solution. In some ways, I like it because it totally eliminates the possibility to reuse a number. But, it is a bit peculiar. And, I would like to find out why my use of “indexOf” didn’t work which would help me as a coder.
Here is a link to my JS that didn’t quite work. It has a couple of alert windows that will give you the final new array with all the indexes and the final sum. (The final sum code works. But, the data fed into it is not correct.)
You can see by comparing the numbers in first alert with the test case that there are indexes/numbers in the given array that are being used more than once, which results in an incorrect final set in the new array.
The problem was discovered while using the second to last test case.
I created some test cases of my own to try to figure out what was going on. You will see them in my code.
Note: The code sections that don’t work are within comments:
////////////////////////////// THIS CODE DOES NOT WORK ////////////////////////////////////
It should be pretty easy to find.
Obviously, there is code that interacts with this section. But, this is where there is a comparison made using the indexOf method which looks in the new array.
Additional Note: I use Notepad++ for my coding. So, what is in Code Pen is copied/pasted from my html file created in Notepad++.
.
Please let me know if I can provide any additional information. I think an experienced coder will be able to sort through my code. I have tried to make the code listing readable and have comments…maybe too many comments. I put a lot of my design in my code as comments.
Thanks.
Ken