0

重複の可能性:
GameLogic、x in a row game

checkPositionRow の説明:

****checkPositionRow public static boolean checkPositionRow(char[][] a, int row, int col, int l) 指定されたセルが、同じ文字を含むセルの水平連続シーケンスの一部であるかどうかを確認します。セルのシーケンスは長さ l である必要があります。

パラメーター:

  • a- char 型の 2 次元矩形配列。

  • row- 問題のセルの行

  • col- 問題のセルの列

  • l- シーケンスの必要な長さ 戻り値: true - セルが長さ 1 以上の水平シーケンスの一部である場合。false - それ以外の場合****

このゲームを動作させることができません。ゲームが 5 つ以上連続している場合に true を返す必要があります。これが私の試みです(これは機能しません。常にtrueを返すだけですが、シーケンスが5未満の場合はfalseを返す必要があります):

public static boolean checkPositionRow(char[][] a, int row, int col, int l){
  int counter = 1;

  for (int i=0; i<a.length; i++) {
    if(a[row][i] == a[row][i+1]) {
      counter++;

      if(counter >= 5){
        return true;
      }                  
    }
  }

  return false;
}

私は何を間違っていますか?ヘルプ!

4

1 に答える 1

0
if(a[row][i] == a[row][i+1]){
    ...
}else{
  //reset counter
  counter = 1;
}

そうでなけれi<a.lengthば、範囲外の例外を与えることができます。正しい長さにi<a.length -1a[row][i+1]a[row].length

if(counter >= l){
  //l = required length
  return true;
}  

しばらく書き直す

public static boolean checkPositionRow(char[][] grid, int row, int col, int requiredLength) {
  int counter = 0;
  int index = 0;
  char[] charRow = grid[row];
  char charToLookFor = grid[row][col];
  while (index < charRow.length && counter < requiredLength) {
    if (charToLookFor == charRow[index]) {
      counter++;
    } else {
      counter = 0;
    }
    index++;
  }
  return counter == requiredLength;
}

長さ行が必要な長さ以上かどうかを確認できます

  public static boolean checkPositionRow(char[][] grid, int row, int col, int requiredLength) {
    int counter = 0;
    char[] charRow = grid[row];
    if (charRow.length >= requiredLength) {
      int index = 0;
      char charToLookFor = grid[row][col];
      while (index < charRow.length && counter < requiredLength) {
        if (charToLookFor == charRow[index]) {
          counter++;
        } else {
          counter = 0;
        }
        index++;
      }
    }
    return counter == requiredLength;
  }
于 2012-12-06T11:54:50.353 に答える