如何在Java中获取数组的值连接四个测试?

时间:2015-04-20 05:52:01

标签: java arrays multidimensional-array

我正在为我的高级编程课做一个项目,而我似乎无法找到解决我所提出的问题的方法。我需要获得在多维数组中找到的四个连续数字的值,包括六行和七列。

本质上,提供的代码告诉我是否有连续的四个。我只需要在四个连续数字的数组中找到值的索引。

public static boolean isConsecutiveFour(int[][] values) {
int numberOfRows = values.length;
int numberOfColumns = values[0].length;

// Check rows
for (int i = 0; i < numberOfRows; i++) {
  if (isConsecutiveFour(values[i]))
    return true;
}

// Check columns
for (int j = 0; j < numberOfColumns; j++) {
  int[] column = new int[numberOfRows];
  // Get a column into an array
  for (int i = 0; i < numberOfRows; i++)
    column[i] = values[i][j];

  if (isConsecutiveFour(column))
    return true;
}

// Check major diagonal (lower part)   
for (int i = 0; i < numberOfRows - 3; i++) {
  int numberOfElementsInDiagonal 
    = Math.min(numberOfRows - i, numberOfColumns);     
  int[] diagonal = new int[numberOfElementsInDiagonal];
  for (int k = 0; k < numberOfElementsInDiagonal; k++)
    diagonal[k] = values[k + i][k];

  if (isConsecutiveFour(diagonal))
    return true;
}

// Check major diagonal (upper part)
for (int j = 1; j < numberOfColumns - 3; j++) {
  int numberOfElementsInDiagonal 
    = Math.min(numberOfColumns - j, numberOfRows);     
  int[] diagonal = new int[numberOfElementsInDiagonal];
  for (int k = 0; k < numberOfElementsInDiagonal; k++)
    diagonal[k] = values[k][k + j];

  if (isConsecutiveFour(diagonal))
    return true;
}

// Check sub-diagonal (left part)
for (int j = 3; j < numberOfColumns; j++) {
  int numberOfElementsInDiagonal 
    = Math.min(j + 1, numberOfRows);     
  int[] diagonal = new int[numberOfElementsInDiagonal];

  for (int k = 0; k < numberOfElementsInDiagonal; k++)
    diagonal[k] = values[k][j - k];

  if (isConsecutiveFour(diagonal))
    return true;
}

// Check sub-diagonal (right part)
for (int i = 1; i < numberOfRows - 3; i++) {
  int numberOfElementsInDiagonal 
    = Math.min(numberOfRows - i, numberOfColumns);     
  int[] diagonal = new int[numberOfElementsInDiagonal];

  for (int k = 0; k < numberOfElementsInDiagonal; k++)
    diagonal[k] = values[k + i][numberOfColumns - k - 1];

  if (isConsecutiveFour(diagonal))
    return true;
}

return false; 
}

public static boolean isConsecutiveFour(int[] values) {    
 for (int i = 0; i < values.length - 3; i++) {
   boolean isEqual = true;        
   for (int j = i; j < i + 3; j++) {
     if (values[j] != values[j + 1]) {
      isEqual = false;
      break;
    }
  }

  if (isEqual) return true;
  }

  return false;
  }
}

我希望有人至少帮助我,指出我正确的方向。任何帮助将不胜感激。谢谢:))

0 个答案:

没有答案