// Write a program to check whether or not two arrays are identical in size, and hold identical values
string1 = prompt("String 1?");
string2 = prompt("String 2?");
pareNum = 0;
for(i=0; i<string1.length; i++)
{
for(j=i; j<string2.length; j++)
{
if (string1.charAt(i) == string2.charAt(j))
{
pareNum++;
break;
}
}
};
alert("We found " + pareNum + " identical value(s).");
I've managed to build a relatively simple string parison program but now the problem I have is the result it outputs.
For example if I type in "Jeansy" and "Jeansy" - I get the response of "We found 6 identical values."
Whereas if I type in "Molanza" and "Molanza" - I get the reply of "We found 9 identical values."
Surely it should only be 7?
Or does the 'a' get counted twice? Is there anyway I can negate this?
Btw I'm taking into account all strings.
Thanks in advance!
// Write a program to check whether or not two arrays are identical in size, and hold identical values
string1 = prompt("String 1?");
string2 = prompt("String 2?");
pareNum = 0;
for(i=0; i<string1.length; i++)
{
for(j=i; j<string2.length; j++)
{
if (string1.charAt(i) == string2.charAt(j))
{
pareNum++;
break;
}
}
};
alert("We found " + pareNum + " identical value(s).");
I've managed to build a relatively simple string parison program but now the problem I have is the result it outputs.
For example if I type in "Jeansy" and "Jeansy" - I get the response of "We found 6 identical values."
Whereas if I type in "Molanza" and "Molanza" - I get the reply of "We found 9 identical values."
Surely it should only be 7?
Or does the 'a' get counted twice? Is there anyway I can negate this?
Btw I'm taking into account all strings.
Thanks in advance!
Share Improve this question edited Oct 30, 2011 at 0:09 methuselah asked Oct 29, 2011 at 23:13 methuselahmethuselah 13.2k52 gold badges176 silver badges332 bronze badges 02 Answers
Reset to default 9Well you are paring every letter in string1 with every letter in string2. If there are duplicate letters you'll get duplicate results.
Try this:
string1 = prompt("String 1?");
string2 = prompt("String 2?");
pareNum = 0; // why are you using the Number contructor? Unneeded.
l = Math.min(string1.length, string2.length);
for( i=0; i<l; i++) {
if( string1.charAt(i) == string2.charAt(i)) pareNum++;
}
// do something with pareNum.
You're looping over each character in string 1 and paring it to each character in string 2--but you're looping over string 2 for every character in string 1.
The indices for each string should be the same; you don't need two loops.
How you handle strings whose lengths are different depends on your requirements.