Skip to content

Instantly share code, notes, and snippets.

@benfb
Created December 2, 2012 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfb/4190538 to your computer and use it in GitHub Desktop.
Save benfb/4190538 to your computer and use it in GitHub Desktop.
WordSearch
import java.util.Arrays;
public class WordSearch
{
/** 2D array instance variable*/
private String[][] grid;
/** constructor used to set the number of rows and columns in the 2D array
* @param row
* @param col*/
public WordSearch(int row, int col) //initialization constructor
{
grid = new String[row][col]; //creates a new 2D array called grid made of strings with variables rows and columns
}
/** method to set an element in the 2D array
* @param s which is the value to store in the 2D array
* @param row the row to use
* @param col the column to use*/
public void setSpot(String s, int row, int col)
{
grid[row][col] = s;
}
/** methods to check for the word in the 2D array
* @param word the word to search for
* @return return true or false*/
public boolean inGrid(String s)
{
//creates a bunch of empty strings
String row = "";
String column = "";
String backward = "";
for(int i = 0; i < s.length(); i++) //for every character in the string
backward = s.charAt(i) + backward; //reverse the string!
for(int r = 0; r < grid.length; r++) //for every row in the string
{
for(int c = 0; c < grid[r].length; c++) //for every column in the string
row = row + grid[r][c]; //add the next character to the row
}
for(int r = 0; r < grid.length; r++)
{
for(int c = 0; c < grid[r].length; c++)
column = column + grid[c][r];
}
if(row.indexOf(s) != -1)
return true;
else if(row.indexOf(backward) != -1)
return true;
else if(column.indexOf(s) != -1)
return true;
else
return false;
}
/** toString method
* @return String containing all elements in the 2D array*/
public String toString()
{
String s = "";
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment