2016-09-17 78 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);