简体   繁体   English

在2D数组中查找重复

[英]Finding repeats in a 2D array

I have made a program that outputs the number of repeats in a 2D array. 我制作了一个程序,可以输出2D数组中的重复次数。 The problem is that it outputs the same number twice. 问题是它两次输出相同的数字。

For example: I input the numbers in the 2D array through Scanner: 10 10 9 28 29 9 1 28. The output I get is: 例如:我通过Scanner在2D数组中输入数字:10 10 9 28 29 9 128。得到的输出是:

Number 10 repeats 2 times.
Number 10 repeats 2 times.
Number 9  repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 9  repeats 2 times.
Number 1  repeats 1 times.
Number 28 repeats 2 times.

I want it so it skips the number if it has already found the number of repeats for it. 我想要它,因此如果它已经找到重复次数,它会跳过该次数。 The output should be: 输出应为:

Number 10 repeats 2 times.
Number 9  repeats 2 times.
Number 28 repeats 2 times.
Number 29 repeats 1 times.
Number 1  repeats 1 times.

Here is my code: 这是我的代码:

import java.util.Scanner;

public class Repeat
{
    static Scanner leopard = new Scanner(System.in);

    public static void main(String [] args)
    {
        final int ROW = 10;                     //Row size
        final int COL = 10;                     //Column size
        int [][] num = new int[ROW][COL];

        int size;

        //Get input
        size = getData(num);

        //Find repeat
        findRepeats(num, size);
    }

    public static int getData(int [][] num)
    {
        int input = 0, actualSize = 0;      //Hold input and actualSize of array

        System.out.print("Enter positive integers (-999 to stop): ");

        //Ask for input
        for(int i = 0; i < num.length && input != -999; i++)
        {
            for(int j = 0; j < num[i].length && input != -999; j++)
            {
                input = leopard.nextInt();

                //Check if end
                if(input != -999)
                {
                    num[i][j] = input;
                    actualSize++;
                }
            }
        }

        System.out.println();

        return actualSize;
    }

    public static void findRepeats(int [][] num, int size)
    {
        int findNum;
        int total = 0, row = 0, col = 0;

        for(int x = 0; x < size; x++)
        {
            //Set to number
            findNum = num[row][col];

            //Loop through whole array to find repeats
            for(int i = 0; i < num.length; i++)
            {
                for(int j = 0; j < num[i].length; j++)
                {
                    if(num[i][j] == findNum)
                        total++;
                }
            }

            //Cycle array to set next number
            if(col < num[0].length-1)
                col++;
            else
            {
                row++;      //Go to next row if no more columns
                col = 0;    //Reset column number
            }

            //Display total repeats
            System.out.println("Number " + findNum + " appears " + total + " times.");
            total = 0;
        }
    }
}

I know why it is doing it, but I cannot figure out how to check if the number has already been checked for it to skip that number and go to the next number. 我知道为什么这样做,但是我无法弄清楚如何检查该号码是否已被检查以跳过该号码并转到下一个号码。 I cannot use any classes or code that is not used in the code. 我不能使用任何未在代码中使用的类或代码。

It's counting the number two times, first time it appears in the code and second time when it appears in the code. 它是对数字进行两次计数,第一次是在代码中出现,第二次是在代码中出现。

To avoid that keep a system to check if you have already checked for that number. 为了避免这种情况,请让系统检查您是否已经检查过该号码。 I see you use check int array but you haven't used it anywhere in the code. 我看到您使用check int数组,但是您在代码中的任何地方都没有使用过它。

Do this, 做这个,

Put the number in the check list if you have already found the count of it. 如果您已经找到数量,则将其放在检查清单中。

 int count = 0;
 check[count] = findNum;
 count++;

Note: You can prefill you array with negative numbers at first in order to avoid for having numbers that user already gave you in input. 注意:您可以先用负数预填充数组,以避免输入中已经有用户给您的数字。

Next time in your for loop skip checking that number which you have already found a count for 下次在for循环中,跳过检查已找到计数的数字

for(int x = 0; x < size; x++) {
   findNum = num[row][col];
     if(check.containsNumber(findNUm)) { //sorry there is no such thing as contains for array, write another function here which checks if a number exists in the array
       //skip the your code till the end of the first for loop, or in other words then don't run the code inside the for loop at all.
     }
}

Frankly speaking I think you have just started to learn coding. 坦白地说,我认为您刚刚开始学习编码。 Good luck! 祝好运! with that but this code can be improved a lot better. 这样,但是可以将代码改进得更好。 A piece of advice never create a situation where you have to use 3 nested for loops. 一条建议绝不会造成必须使用3个嵌套的for循环的情况。

I hope that you understood my solution and you know how to do it. 希望您了解我的解决方案,并且知道如何做。

Since you cannot use anything other than this, lets say, basic elements of Java consider this: 既然不能使用除此以外的任何东西,可以说,Java的基本元素应考虑到这一点:

Make another temporary 2D array with two columns (or just two separate arrays, personally I prefer this one). 用两列制作另一个临时的2D数组(或者只是两个单独的数组,我个人更喜欢这个)。 On the start of the algorithm the new arrays are empty. 在算法开始时,新数组为空。

When you take a number (any number) from the source 2D structure, first check if it is present in the first temporary array. 当您从源2D结构中获取一个数字(任意数字)时,请首先检查该数字是否在第一个临时数组中。 If it is, just increment the value (count) in the second temporary array for one (+1). 如果是这样,只需将第二个临时数组中的值(计数)增加一(+1)即可。 If it is not present in the first tmp array, add it to it and increase the count (+1) in the second at the same index as the newly added number in the first (which should be the last item of the array, basically). 如果它不在第一个tmp数组中,则将其添加到其中,并在第二个计数中增加计数(+1),其索引与第一个tmp数组中新添加的数字相同(基本上应该是数组的最后一项) )。

This way you are building pairs of numbers in two arrays. 这样,您可以在两个数组中构建数字对。 The first array holds all your distinct values found in the 2D array, and the second one the number of appearances of the respective number from the first. 第一个数组保存您在2D数组中找到的所有不同值,第二个数组保存第一个数组中各个数字的出现次数。

At the and of the algorithm just iterate the both arrays in parallel and you should have your school task finished. 在算法的和处,只需并行地迭代两个数组,您就应该完成学习任务。 I could (and anyone) code this out but we are not really doing you a favor since this is a very typical school assignment. 我可以(和任何人)对此进行编码,但由于这是一项非常典型的学校任务,因此我们并没有真正帮到您。

All answers gives you some insight about the problem. 所有答案使您对问题有一些了解。 I try to stick to your code, and add a little trick of swap . 我尝试坚持您的代码,并添加一些swap技巧。 With this code you don't need to check if the number is already outputted or not. 使用此代码,您无需检查数字是否已经输出。 I appreciate your comments, structured approach of coding, and ask a question as clear as possible. 感谢您的评论,结构化的编码方法,并提出一个尽可能清晰的问题。

public static void findRepeats(int [][] num, int size)
{
    int findNum;
    int total = 1, row = 0, col = 0;
    int [] check = new int[size];
    while(row < num.length && col < num[0].length)
    {
        //Set to number
        findNum = num[row][col];
      //Cycle array to set next number
        if(col < num[0].length-1)
            col++;
        else
        {
            row++;      //Go to next row if no more columns
            col = 0;    //Reset column number
        }
        //Loop through whole array to find repeats
        for(int i = row; i < num.length; i++)
        {
            for(int j = col; j < num[i].length; j++)
            {
                if(num[i][j] == findNum) {
                    total++;
                     //Cycle array to set next number
                      if(col < num[0].length-1)
                          col++;
                      else
                      {
                           row++;      //Go to next row if no more columns
                           col = 0;    //Reset column number
                      }
                      if(row < num.length - 1 && col < num[0].length -1)
                         num[i][j] = num[row][col];
                }
            }
        }


        //Display total repeats
        System.out.println("Number " + findNum + " appears " + total + " times.");
        total = 1;
    }
}

you can use a HashMap to store the result. 您可以使用HashMap来存储结果。 It Goes like this: 它是这样的:

  // Create a hash map
  HashMap arrayRepeat = new HashMap();

  // Put elements to the map

  arrayRepeat.put(Number, Repeated);

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

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