2016-09-17 7 views
-2

2次元配列のすべての行に共通の値を見つけようとしています。 その値のために、すべての行に存在する最小限の(> 0)繰り返し数を探したいと思います。例えば2次元配列の項目数を数えようとしています

、文字列の2次元アレイと協力:すべての行に存在する

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

のみ値が「A」です。ある行の出現回数の最小値は1であるため、答えは1 Aとなります。

ここに私のコードです:私は重複(またはトリプレットなど)の行の各列を検索しようとしている、特定の行の数を決定し、他の行と比較して、量。また、より洗練されたアプローチがありますか?何らかの理由でそれが機能していません(コレクションを2D文字列の配列です):

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

まあ、i0であることがAと評価さそう、その後、プログラムはすべてのそれらのループを通過してlowestCountが設定されている場合最初にあなたがcollections[0][i].toString()を取ります1。その後、最初のforループはBに移動し、lowestCountはどこにも保存されずにリセットされます。 lowestCountを配列またはリストに保存し、最初のforループの最後(2つのforループの後)にlowestCountをその配列に追加すれば、すべての文字の数が最小になります。あなたがそれを保存したくない場合は、ただSystem.out.println("Lowest count of letter: "+current+" is: "+lowestCount);することができます。最も低いカウントを持つ行を決定したい場合は、配列内に保存することもできます(すべての文字に対して最小のカウントを持つ行)。if文が(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); 
のように行うことができます
関連する問題