2016-09-17 81 views
-2

我正在尝试查找二维数组中所有行都通用的可比较值。 对于这个值,我想找到所有行中存在的最小(> 0)重复次数。尝试计算二维数组中的项目数

例如,字符串的2D阵列工作时:

{ 
{A, C, B}, 
{A, A, B}, 
{C, D, A} 
} 

存在于所有行的唯一值是“A”。一行中出现的最小数目是1,所以答案将是1 A

这里是我的代码:我想在一行中搜索重复项(或三胞胎等),确定给定行的计数并将其与其他行进行比较以确定最低的行数量。另外,也许有一个更优雅的方法?出于某种原因,它不工作(Collections是一个二维字符串数组):

public class CommonElements { 
    ArrayList<String> commonCollections = new ArrayList<String>(); 

    private int comparisons = 0; 
    int i, j, k; 
    int count, lowestCount; 
    String previousString = ""; 
    int row[]; 
    String current; 

    public Comparable[] findCommonElements(Comparable[][] collections) { 

     Arrays.sort(collections[0]); 

     row = new int[collections[0].length]; 

     for (i = 0; i < collections[0].length; i++) { // first row column selection 
      current = collections[0][i].toString(); 
      lowestCount = 1; 
      for (j = 0; j < collections.length; j++) { // row 
       count = 0; 
       for (k = 0; k < collections[0].length; k++) { // column 
        if (current.equals(collections[j][k].toString())) { // if contains same string as first row column selected 
         count++; 
         System.out.print(count + "\n"); 
        } 
       } 
       if (lowestCount < count) { 
        lowestCount = count; 
       } 
      } 
     } 

     System.out.print(lowestCount); 

     return collections[0]; 
    } 

    public int getComparisons() { 
     return comparisons; 
    } 


} 

回答

0

哦,首先你需要collections[0][i].toString()i0,使计算结果为A,然后程序遍历所有这些循环和lowestCount设置到1。然后,您的第一个for循环移动到BlowestCount被重置,但不保存在任何地方。您应该将您的lowestCount保存在数组或列表中,并且在第一个for循环的末尾(在其他2个for循环之后)将lowestCount添加到该数组中,并且每个字母的计数最低。如果你不想保存它,你可以只需System.out.println("Lowest count of letter: "+current+" is: "+lowestCount);。如果要确定计数最低的行,还可以将其保存在数组中(每个字母计数最低的行),如果该语句通过(if(lowestCount < count)),则将其设置为该行。

我不确定我是否正确理解了你,但肯定有更好的方法来解决这个问题。

0

你可以这样做

int[][] arr = new int[5][2]; 
    int count =0; 
    for(int[] i : arr){ 
     count = count + i.length; 
    } 
    System.out.println(count);