简体   繁体   English

如何查找元素数组的第一个实例

[英]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. 我是一个非常基本的程序员,我正在编写一个'Master-mind'式猜谜游戏程序。

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. 所以,例如,如果有两个数字(189,999),我希望计数器只增加一次,而不是3次,这就是我的代码所做的。 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. 这种方法很好,可以通过使用整数的HashSet来提高效率。 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. 每当你遇到一个共同的数字时,你在集合上做一个contains来检查该数字(在HashSets中获取的是恒定时间复杂 - O(1),即超快),如果它已经存在,你跳过它。 If not, you add it into the set, and increment your correctNumbers . 如果没有, addadd到集合中,并递增您的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 你可以尝试制作另一个1D阵列

 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 . 我想989999将返回1 Because you only deal with number, so the solution is: 因为你只处理数字,所以解决方案是:

  1. Create a boolean array with 9 element, from 0-9, named isChecked 创建一个包含9个元素的布尔数组,从0到9,命名为isChecked
  2. Initialize it with false . 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 ). 每当你找到一个匹配的数字,比如说9时,将布尔元素转为true ,这样就不再计算它了( 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 . JSFiddle上测试

If you find anything unclear, feel free to ask me :) 如果您发现任何不清楚的地方,请随时问我:)

Why not just use the new stream api? 为什么不使用新的流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. Arrays.stream(mString) - >创建所有字符串的流。
  • flatMapToInt -> create single concatenated stream from many IntStreams flatMapToInt - >从许多IntStream创建单个连接流
  • s -> s.chars() -> Used above to create streams of characters (as ints) s -> s.chars() - >上面用于创建字符流(作为整数)
  • distinct -> remove all duplicates, so each character is counted only once distinct - >删除所有重复项,因此每个字符只计算一次
  • count -> count the (unique) characters count - >计算(唯一)字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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