単語検索パズルで「ruby」、「python」、「java」を検索するプログラムがあります。私の教授は、左から右に検索するコードを教えてくれましたが、右から左、斜めに検索する方法がわかりません。他の人が同じ問題をコーディングしているのを見たことがありますが、私の教授は、彼女が行ったのと同様の方法でそれを行うことを望んでいると思います。
右から左に移動しようとしましたが、範囲外の例外が発生するか、検索が否定的に返されます。
public static void main (String[] argv)
{
char[][] puzzle = {
{'n', 'o', 'h', 't', 'y', 'p', 's'},
{'m', 'i', 'a', 'r', 'y', 'c', 'c'},
{'l', 'l', 'e', 'k', 's', 'a', 'h'},
{'r', 'u', 'b', 'y', 'v', 'm', 'e'},
{'e', 'h', 'h', 'a', 'l', 'l', 'm'},
{'p', 'c', 'j', 'n', 'i', 'c', 'e'},
{'r', 'e', 'e', 'k', 'b', 'i', 'p'}
};
String result1 = findWordLefttoRight (puzzle, "ruby");
String result2 = findWordRighttoLeft (puzzle, "python");
//String result3 = findWordBottomLefttoTopRight (puzzle, "java");
System.out.println (result1);
System.out.println (result2);
//System.out.println (result3);
}
/*Given by Professor*/
static String findWordLefttoRight (char[][] puzzle, String word)
{
// First convert the String into a char array.
char[] letters = word.toCharArray ();
// Now try every possible starting point in the puzzle array.
for (int i=0; i<puzzle.length; i++) {
for (int j=0; j<puzzle[i].length; j++) {
// Use (i,j) as the starting point.
boolean found = true;
// Try to find the given word's letters.
for (int k=0; k<letters.length; k++) {
if ( (j+k >= puzzle[i].length) || (letters[k] != puzzle[i][j+k]) ) {
// Not a match.
found = false;
break;
}
}
// If we went the whole length of the word, we found it.
if (found) {
return "String " + word + " found in row=" + i + " col=" +j;
}
}
}
return "String " + word + " not found";
}
/* My attempt at going from right to left */
static String findWordRighttoLeft (char[][] puzzle, String word)
{
// First convert the String into a char array.
char[] letters = word.toCharArray ();
// Now try every possible starting point in the puzzle array.
for (int i=puzzle.length; i>0; i--) {
for (int j=puzzle.length; j>0; j--) {
// Use (i,j) as the starting point.
boolean found = true;
// Try to find the given word's letters.
for (int k=0; k<letters.length; k++) {
if ( (j+k <= puzzle.length) || (letters[k] == puzzle[i][j+k]) ) {
// Not a match.
found = false;
break;
}
}
// If we went the whole length of the word, we found it.
if (found) {
return "String " + word + " found in row=" + i + " col=" +j;
}
}
}
return "String " + word + " not found";
}