How to Find a First Array of Elements

I'm a pretty basic programmer and I'm coding a 'Master-mind' style guessing game program.

Now the part I'm stuck with is that I want to go through an array and increase the pointer when I come across a specific number.

Now thats pretty easy and stuff, but what I want to do is ONLY increase the counter if the number is encountered for the first time. So, for example if there are two numbers (189, 999), I want the counter to increase only once, instead of 3 times, which is what my code is doing. I know why its doing that, but I can't really figure out a way to NOT do it (except maybe declaring an array and putting all the repeated numbers in there and only incrementing it if none of the numbers match, but that's super inefficient) Here's my code:

for (int i = 0; i < mString.length(); i++) {
        for (int j = 0; j < nString.length(); j++) {
            if (mString.charAt(i) == nString.charAt(j)) {
                correctNumbers++;
            }
        }
    }

Thanks for taking the time to read! I'd prefer it if you wouldn't give me a direct answer and just point me in the right direction so I can learn better. Thanks again!


Your question is quite unclear. I suppose 989 and 999 will return 1. Because you only deal with number, so the solution is:

  1. Create a boolean array with 9 element, from 0-9, named isChecked
  2. Initialize it with false.
  3. Whenever you found a matching number, say 9, turn the boolean element to true, so that you don't count it again (isChecked[9] = true).

Here is the code:

var isChecked = [];

function resetArray(input) {
    for (var i = 0; i < 10; i++) {
        input[i + ''] = false;
    }
}

resetArray(isChecked);

var firstNumber = '989',
    secondNumber = '999',
    correctNumbers = 0,
    fNum, sNum;

for (var i = 0; i < firstNumber.length; i++) {
    fNum = firstNumber.charAt(i);

    // Skip already checked numbers
    if (isChecked[fNum]) {
        continue;
    }

    for (var j = 0; j < secondNumber.length; j++) {
        sNum = secondNumber.charAt(j);
        if (fNum == sNum && !isChecked[sNum]) {
            correctNumbers++;
            isChecked[sNum] = true;
        }
    }
}

console.log(correctNumbers);

Tested on JSFiddle.

If you find anything unclear, feel free to ask me :)