// 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?");
compareNum = 0;
for(i=0; i<string1.length; i++)
{
    for(j=i; j<string2.length; j++)
    {
    if (string1.charAt(i) == string2.charAt(j))
{
        compareNum++;
        break;
}
    }
};
alert("We found " + compareNum + " identical value(s).");
I've managed to build a relatively simple string comparison 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!
Well you are comparing 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?");
compareNum = 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)) compareNum++;
}
// do something with compareNum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With