简体   繁体   中英

Finding repeats in a 2D array

I have made a program that outputs the number of repeats in a 2D array. 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:

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.

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

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:

Make another temporary 2D array with two columns (or just two separate arrays, personally I prefer this one). 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. If it is, just increment the value (count) in the second temporary array for one (+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).

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.

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 . 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. It Goes like this:

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

  // Put elements to the map

  arrayRepeat.put(Number, Repeated);

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