2017-04-18 13 views
0

私は正しく、次のN×Nアレイを評価するスコア関数を書かれている:NxN配列のスコア関数を書くよりエレガントな方法はありますか?

int state1[][] = { 
      {0, 1, 0}, 
      {1, 0, 0}, 
      {0, 1, 0} }; // score = 0 

    int state2[][] = { 
      {0, 1, 1}, 
      {1, 0, 0}, 
      {1, 1, 0} }; // score = 2 

    int state3[][] = { 
      {1, 1, 0}, 
      {1, 1, 1}, 
      {1, 0, 0} }; // score = 5 

には、以下のスコア関数を記述する(単純)よりエレガントな方法はありますか?

public static int score(int[][] s) { 
    int count = 0; 
    int hold = 0; 
    int length = s.length; 
    int end = length - 1; 
    for (int col = 0; col < length; col++) { 
     for (int row = 0; row < length; row++) { 
      hold = s[row][col]; 
      if (row == 0 && hold == 1 && s[row + 1][col] == 1) { 
       count++; 
      } 
      else if (row == end && hold == 1 && s[row - 1][col] == 1) { 
       count++; 
      } 
      else if (row != 0 && row != end && hold == 1 && (s[row + 1][col] == 1 || s[row - 1][col] == 1)) { 
       count++; 
      } 
     } 
    } 
    return count; 
} 

「1」のすぐ上または下に「1」があるかどうかによってスコアリングが異なることを付け加えておきます。言い換えれば、行1に「1」が含まれている場合、行0または行2の同じ列に「1」がある場合にスコアが増加します。

+0

は、関数が何をするのか説明して? – Justas

+1

codereview.stackexchange.comは、作業コードを改善するための助けを求めるより良い場所です。 – GER

答えて

0

これは同じことを行うと思われます。テストする:

if (hold == 1) { 
    boolean hasOneAbove = row > 0 && s[row - 1][col] == 1; 
    boolean hasOneBelow = row < end && s[row + 1][col] == 1; 
    if (hasOneAbove || hasOneBelow) count++; 
} 
+0

Yepper、このコードスニペットはif-else-ifブロックの代わりに機能します。当然のことながら、それは私のラウンドアバウトコードに比べて論理的に直接的です。同様の戦略をより簡単に特定できるように、もっと練習が必要です。 – TheWink

0

これは、同じことを行う必要があります。

public static int score(int[][] s) { 
    int count = 0; 
    final int end = s.length - 1; 
    for (int col = 0; col <= end; col++) 
     for (int row = 0; row <= end; row++) 
      if (s[row][col] == 1) 
       if ((row != end && s[row + 1][col] == 1) || (row != 0 && s[row - 1][col] == 1)) 
        count++; 
    return count; 
} 
関連する問題