在随机生成的二进制矩阵中查找最大数量为1的行和列

时间:2016-10-06 18:25:46

标签: java algorithm matrix

此程序的输出正常。但是有一件事我无法实现。在某些情况下,我没有一行或列数最多的1。有时我有2行或更多行/列具有相同的" HIGHEST"数量。但我的程序只返回1行/列。

我想要一个案例,如果我有超过2行/列,具有相同的最大数量1。将显示这两行。例如"最多1行的行:1,2"或者如果它是一列,它可以说"最多1行的行:1,2"。

我需要帮助。我被卡住了。

import java.util.Random; 
    import java.util.Scanner; 

    public class LargestRowColumn 
    { 
       // declare a 2 dimensional array or an array of arrays 
       private static int[][] randArray; 

       public static void main(String[] args) 
       { 
        do
        {
          // Create a scanner to get Input from user. 
          Scanner scanner = new Scanner(System.in); 
          System.out.print("\nEnter the array size n:"); 
          int rows = scanner.nextInt(); 
          int cols = rows;

          randArray = new int[rows][cols]; 

          // loop through the number of rows in thw array 
          for (int i = 0; i < randArray.length; i++) 
          { 
             // loop through the elements of the first array in the array 
             for (int j = 0; j < randArray[0].length; j++) 
             { 
                // set a random int 0-1 to the array 
                randArray[i][j] = getRandomInt(0, 1); 
                // print the number just assigned 
                System.out.print(randArray[i][j]); 
             }
             // make a linebreak each row. 
             System.out.println();
          }
          System.out.print("Row(s) with the most 1's: " + scanRow(randArray) + "\n");
          System.out.print("Columns(s) with the most 1's: " + scanColumn(randArray) + "\n"); 
        }
        while(true);   
       } 

       // quick method I made to get a random int with a min and max 
       public static int getRandomInt(int min, int max) 
       { 
          Random rand = new Random(); 
          return rand.nextInt(max-min+1)+min; 
       }


       public static int scanRow(int[][] array) 
       {
          int result = -1;
          int highest = -1;

          for (int row = 0; row < array.length; row++)// Here we are about start looping through the matrix values
          {
             int temp = 0; // Setting the first index to 0.
             for (int col = 0; col < array[row].length; col++)// 
             {
                //Assign current location to temporary variable
                temp = temp + array[row][col];
             }

             if (temp > highest)
             {
                highest = temp;
                result = row + 1;
             }
          }
          return result;
       } // end of row method

       private static int scanColumn(int[][] array) 
       {
            int result = -1;
            int highest = -1;

            // declare and initialize the variable(here you've 'created' it, to then call it on if statement)
            int col = 0;

            for (int row = 0; row < array.length; row++)
            {
                int temp = 0;
                //declare the variable in the for loop
                for (col = 0; col < array[row].length; col++) 
                {
                    //Assign current location to temp variable
                    temp = temp + array[row][col];
                }

               if (temp > highest) 
               {
                   highest = temp;
                 result = col;
               }
            }
            return result;
       }


    }

2 个答案:

答案 0 :(得分:0)

我建议采用不同的方法,首先为什么你需要再次遍历2D数组,你可以在插入它们并将它们插入数组时找出行和列中最高的1#(行数组和列数组)进位将是自定义类型,它是一个具有两个参数的类,得分(数字为1&#39; s)和索引(行数或列数),然后对数组进行排序并打印与最高分相关的索引。

如果您希望通过输入接收数组,则可以使用新循环来执行相同操作。

所以你的插入循环就像这样

       List<Wrapper> rowsList = new ArrayList<Wrapper>(rows);
        List<Wrapper> colsList = new ArrayList<Wrapper>(cols);
         for(int i=0;i<cols;i++) {
             colsList.add(new Wrapper(i,0));
         } 
      // loop through the number of rows in thw array 
      for (int i = 0; i < rows; i++) 
      { 
         int sum =0;
         // loop through the elements of the first array in the array 
         for (int j = 0; j < cols j++) 
         { 

            // set a random int 0-1 to the array 
            randArray[i][j] = getRandomInt(0, 1); 
            // print the number just assigned 
            System.out.print(randArray[i][j]); 
            sum+=randArray[i][j];//add for row
             colsList.get(j).setScore(colsList(j).getScore() +randArray[i][j]);//add for column
         }
          rowsList.add(new Wrapper(i,sum));
         // make a linebreak each row. 

      }

     Collections.sort(rowsList,new Comparator<Wrapper>() {

              @Override
              public int compare(Wrapper obj1,Wrapper obj2) {
                   if(obj1.getScore() > obj2.getScore())
                      return -1;
                    if(obj1.getScore() < obj2.getScore())
                      return 1;
                  return 0;
             }
        });
        if(rowsList.isEmpty())
           return -1;
        int max = rowsList.get(0).getScore();
         for(Wrapper obj:rowsList) {
            if(obj.getScore()< max)
              break;
             System.out.println(obj.getIndex);
          }
         //DO THE SAME FOR COLUMNS

你的包装类将是

          public class Wrapper {
                 private int index;
                 private int score;

                 public Wrapper(int index,int score) {
                       this.index = index;
                        this.score = score;
                 }

                 public int getIndex() {
                       return this.index;
                 }

                 public int getScore() {
                      return this.score;
                  }

                 public void setScore(int score) {
                       this.score = score
                  }
               }

答案 1 :(得分:0)

  

这与数组的OP使用保持一致。

您可以返回int,而不是返回int[],而不是int[]

就个人而言,我会将int[] results = new int[array[0].length]; 初始化为数组中的行数,因为如果每一行都有相同数量的1&#39;

results[0]

然后,我不会添加行,而是使用一个变量来指定要添加行的位置,即int index = 0; 等。

public static int[] scanRow(int[][] array) 
       {
          int highest = -1;
          int index = 0; //ADD HERE
          int[] results = new int[array[0].length]; //ADD HERE

            ... //Your code here

             if (temp > highest)
             {
                highest = temp;
                //CLEAR THE RESULT LIST
                for(int x = 0; x < results.length; x++){
                    results[x] = -1;
                }
                index = 0; //RESET THE INDEX
                results[index] = row + 1;
                index ++;
             } else if (temp == highest{
                highest = temp;
                results[index] = row + 1;
                index ++;
             }
          }
          return results;
       } // end of row method

然后,只需稍微调整一下如何将结果添加到数组中。

ArrayList<int>
  

就个人而言,我会使用ArrayList来处理这些类型的事情,所以我将如何使用它。

我会将方法的返回类型设为public static ArrayList<int> scanRow(int[][] array)

ArrayList<int>

然后声明我的ArrayList<int> results = new ArrayList<>();

ArrayList

并且if语句更易于处理,因为clear()add()if (temp > highest) { highest = temp; //CLEAR THE RESULT LIST results.clear(); results.add(row+1); } else if (temp == highest{ highest = temp; results.add(row + 1); } 方法。

typings
  

EDIT   别忘了相应地编辑您的打印报表。