Is this a good solution for finding name?


#1

I finished the exercise but if there's two matching letter it will push both so they said find a solution for it and i remember on ruby there is split method i didn't know there is one too in js so cool.
but i wonder if this is a good solution?

myName = prompt("Please enter name to find");
var text = "Jasmin, Jcan , Joe , Joey , Pamela , Pan"
var hits = []
found = false;

for(var i=0; i<text.length; i++){
hits = text.split(" ");
if ( hits[i] === myName){
found = true;
console.log("Your name is found in the list!");
}
}

if (found === false){
console.log("No match found check for spelling error or try again next year.");
}


#2

Thank you for sharing your thought!

But I have a question, if there is no space between myName and a comma, then ( hit[i] === myName) will not detect myName, right?

For example,if myName is Joe, and the text variable is:
"Jasmin, Jcan, Joe, Joey, Pamela, Pan"

After running the code, I will not able to find Joe, right?

Even I just discover this problem, your way is still much better than mine, though.

Thanks for sharing again!


#3

It is kind of elegant but it is slightly problematic, what I would suggest is that you run a linear search through and if you find the first letter you do a nested for loop searching for the remaining letters in the name, then if at any point it does not match you can break out of the nested loop and resume searching at the exact letter that broke your nested loop (regardless of success/failure this should happen) (i.e. “ABCDEFGHIJKLMNOP” and I’m searching for “FGHIJZ” so I loop up till “F” and I find the letters “G”,“H”,“I” and “J”, but I cannot find Z and thus I stop the search and continue from “K” to find the next “F”. This keeps the search in linear time and is harder to code but it’s quite exact I suppose in getting what you might want. Cheers! It’s quite a great attempt if you’re new to this stuff :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.