简体   繁体   中英

How to find first instance of element array

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!

(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)

That approach is a good one, and can be made efficient by using a HashSet of Integers. Everytime you encounter a common digit, you do a contains on the set to check for that digit (gets in HashSets are of constant-time complexitiy - O(1), ie super quick), and if it's present in there already, you skip it. If not, you add it into the set, and increment your correctNumbers .

I believe this would help

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

You could try making another 1D array of

 int size =  nstring.length() * mstring.length();
 bool[] array = new bool[size];`

and then have that store a boolean flag of whether that cell has been updated before.

you would find the unique index of the cell by using

 bool flag = false
 flag = array[(i % mString.length()) + j)];
 if(flag == true){
   <don't increment>
 }else{
    <increment>
  array[(i % mString.length()) + j)] = true;
 }

you could also do this using a 2d array that basically would act as a mirror of your existing table:

 bool[][] array = new bool[mstring.length()][nString.length()];

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 :)

Why not just use the new stream api? Then it's just that:

Arrays.stream(mString).flatMapToInt(s -> s.chars()).distinct().count();

I'll explain:

  • Arrays.stream(mString) -> Create stream of all strings.
  • flatMapToInt -> create single concatenated stream from many IntStreams
  • s -> s.chars() -> Used above to create streams of characters (as ints)
  • distinct -> remove all duplicates, so each character is counted only once
  • count -> count the (unique) characters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM