Java: How do I get these two methods into one? - java

In our assignment we are only allowed to use one method. I didn't know about that and I wrote two. So I wanted to ask, if its somehow possible to integrate the function of my neighbourconditions method into the life method. I tried, but I don't know how to initialize my int neighbors. Look at the following code:
public static String[] life(String[] dish) {
String[] newGen = new String[dish.length];
//TODO: implement this function
for (int line = 0; line < dish.length; line++) { // for loop going through each line
newGen[line] = "";
for (int i = 0; i < dish[line].length(); i++) { // loops through every character in the line
String top = ""; // neighbours on the top
String middle = ""; // neighbors on the same line
String down = ""; // neighbors down
if (i == 0){
if(line == 0){
top = null;
} else {
top = dish[line-1].substring(i, i+2);
}
middle = dish[line].substring(i + 1, i +2);
if(line == dish.length -1){
down = null;
} else {
down = dish[line + 1].substring(i, i + 2);
}
} else if (i == dish[line].length() - 1){
if(line == 0){
top = null;
} else {
top = dish[line - 1].substring(i - 1, i + 1);
}
middle = dish[line].substring(i - 1, i);
if(line == dish.length - 1){
down = null;
} else {
down = dish [line + 1].substring(i - 1, i + 1);
}
} else {
if (line == 0){
top = null;
} else {
top = dish[line - 1].substring(i - 1, i + 2);
}
middle = dish[line].substring(i - 1, i) + dish[line].substring(i+1, i+2);
if (line == dish.length - 1){
down = null;
} else {
down = dish[line + 1].substring(i - 1, i + 2);
}
}
int neighbors = neighbourconditions(top, middle, down);
if (neighbors < 2 || neighbors > 3){ // neighbours < 2 or >3 neighbors -> they die
newGen[line] += "o";
} else if (neighbors == 3){
newGen[line] += "x"; // neighbours exactly 3 -> they spawn/live
} else {
newGen[line] += dish[line].charAt(i); // 2 neighbours -> stay
}
}
}
return newGen;
}
// helpmethod with three arguments and the conditions
public static int neighbourconditions(String top, String middle, String down) {
int counter = 0;
if (top != null) { // if no one's on top
for (int x = 0; x < top.length(); ++x) {
if (top.charAt(x) == 'x') {
counter++; // count if an organism's here
}
}
}
for (int x = 0; x < middle.length(); ++x) {
if (middle.charAt(x) == 'x') { // two organisms, one on each side
counter++; // count if an organism's here
}
}
if (down != null) { // if no one's down
for (int x = 0; x < down.length(); ++x) {
if (down.charAt(x) == 'x') { // each neighbour down
counter++; // count if an organism's here
}
}
}
return counter;
}

Everything you do inside the second function will have to be done in the first function. So just copy the code from function 2 into function 1:
public static String[] life(String[] dish){
String[] newGen= new String[dish.length];
//TODO: implement this functions
for(int row = 0; row < dish.length; row++){ // each row
newGen[row]= "";
for(int i = 0; i < dish[row].length(); i++){ // each char in the row
String above = ""; // neighbors above
String same = ""; // neighbors in the same row
String below = ""; // neighbors below
if(i == 0){ // all the way on the left
// no one above if on the top row
// otherwise grab the neighbors from above
above = (row == 0) ? null : dish[row - 1].substring(i, i + 2);
same = dish[row].substring(i + 1, i + 2);
// no one below if on the bottom row
// otherwise grab the neighbors from below
below = (row == dish.length - 1) ? null : dish[row + 1].substring(i, i + 2);
}else if(i == dish[row].length() - 1){//right
// no one above if on the top row
// otherwise grab the neighbors from above
above = (row == 0) ? null : dish[row - 1].substring(i - 1, i + 1);
same = dish[row].substring(i - 1, i);
// no one below if on the bottom row
// otherwise grab the neighbors from below
below = (row == dish.length - 1) ? null : dish[row + 1].substring(i - 1, i + 1);
}else{ // anywhere else
// no one above if on the top row
//otherwise grab the neighbors from above
above = (row == 0) ? null : dish[row - 1].substring(i - 1, i + 2);
same = dish[row].substring(i - 1, i) + dish[row].substring(i + 1, i + 2);
//no one below if on the bottom row
//otherwise grab the neighbors from below
below = (row == dish.length - 1) ? null : dish[row + 1].substring(i - 1, i + 2);
}
// here is the interesting part for you:
int neighbors = 0;
if(above != null){//no one above
for(char x: above.toCharArray()){ //each neighbor from above
if(x == 'x') neighbors++; //count it if someone is here
}
}
for(char x: same.toCharArray()){ //two on either side
if(x == 'x') neighbors++;//count it if someone is here
}
if(below != null){ //no one below
for(char x: below.toCharArray()){//each neighbor below
if(x == 'x') neighbors++;//count it if someone is here
}
};
//here ends the interesting part for you
if(neighbors < 2 || neighbors > 3){
newGen[row]+= "o"; // If the amount of neighbors is < 2 or >3 neighbors -> they die
}else if(neighbors == 3){
newGen[row]+= "x"; // If the amount of neighbors is exactly 3 neighbors -> they spawn/live
}else{
newGen[row]+= dish[row].charAt(i); // 2 neighbors -> stay
}
}
}
return newGen;
}

The trivial answer to this question is to copy and paste the code from the method into the body of the other method. If you're using an IDE, you can use the in-built refactoring tools to inline the method (e.g. ctrl-alt-n, in intellij).
But this is the sort of behavior that makes future generations curse your name. It makes for nasty, unreadable, unmaintainable code. Don't do it. As GhostCat pointed out in comments, you should be looking to make methods smaller, not bigger.
Take a step back, and consider whether you're approaching the problem in the right way. Look for repeating patterns in the existing code, to see if you can simplify it. Or, sometimes, consider that you've just taken the wrong approach in the first place, and so you need to find an alternative approach.
As far as I can work out, all you're trying to do is to count the number of xs in the 8 cells immediately surrounding the current position.
You don't need all of this code to do that. You could simply do:
for(int row = 0; row < dish.length; row++){ // each row
for(int col = 0; col < dish[row].length(); col++){ // each char in the row
int neighbors = 0;
for (int r = Math.max(row - 1, 0); r < Math.min(row + 2, dish.length); ++r) {
for (int c = Math.max(col - 1, 0); c < Math.min(col + 2, dish[row].length()); ++c) {
// Don't count (row, col).
if (r == row && c == col) continue;
if (dish[r].charAt(c) == 'x') ++neighbors;
}
}
//here ends the interesting part for you
if(neighbors < 2 || neighbors > 3){
// etc.
Way less code, no need for an auxiliary method. Also a lot more efficient, because it avoids unnecessarily creating strings.

Related

Why won't my while loop if condition work correctly?

My checkWin method returns false until there's a winner in the Connect 4 game by putting 4 "checkers" in a row horizontally, vertically, or diagonally in my board array. Once there's a winner, the checkWin method returns true, the nearest if statement iterates, printing the winner, then terminating the entire loop (if I coded it all correctly). However, when I run the program, the while loop iterates only once, accepts one input for red, states red won, then does the same thing for yellow, then terminates.
What am I missing here?
Below is the relevant code.
Thank you.
public static void main(String[] args) {
char[][] board = new char[6][7];
boolean loop = true;
// loop to alternate players until there's a winner
while (loop) {
printData(board);
red(board);
if (checkWin(board) == true) {
printData(board);
System.out.print("Red wins!");
loop = false;
}
printData(board);
yellow(board);
if (checkWin(board) == true) {
printData(board);
System.out.print("Yellow wins!");
loop = false;
}
}
}
public static void printData(char[][] tbl) {
for (int r = 0; r < tbl.length; r++) {
for (int c = 0; c < tbl[r].length; c++) {
if (tbl[r][c] == 0) {
System.out.print("| ");
} else {
System.out.print("|" + tbl[r][c]);
}
} // end for col loop
System.out.println("|");
} // end for row loop
System.out.println("---------------");
} // end printData method
public static void red(char[][] f) {
System.out.println("Place a red checker at column (0-6)");
Scanner in = new Scanner(System.in);
int c = in.nextInt();
for (int i = 5; i >= 0; i--) {
if (f[i][c] == 0) {
f[i][c] = 'R';
break;
}
}
}
public static void yellow(char[][] f) {
System.out.println("Place a yellow checker at column (0-6)");
Scanner in = new Scanner(System.in);
int c = in.nextInt();
for (int i = 5; i >= 0; i--) {
if (f[i][c] == 0) {
f[i][c] = 'Y';
break;
}
}
}
// Method to check for a winner. Receives 2-D array as parameter. Returns
// boolean value.
public static boolean checkWin(char[][] b) {
// Create four boolean variables, one for each set of rows. Initialize
// all of them to false.
boolean foundRow = false;
boolean foundCol = false;
boolean foundMjrD = false;
boolean foundMinD = false;
// Check to see if four consecutive cells in a row match.
// check rows
for (int r = 0; r <= 5; r++) {
for (int c = 0; c <= 3; c++) {
if (b[r][c] == b[r][c + 1] && b[r][c] == b[r][c + 2] && b[r][c] == b[r][c + 3] && b[r][c] != ' ') {
foundRow = true;
break;
}
}
}
// Check to see if four columns in the same row match
// check columns
for (int r = 0; r <= 2; r++) {
for (int c = 0; c <= 6; c++) {
if (b[r][c] == b[r + 1][c] && b[r][c] == b[r + 2][c] && b[r][c] == b[r + 3][c] && b[r][c] != ' ') {
foundCol = true;
break;
}
}
}
// Check to see if four diagonals match (top left to bottom right)
// check major diagonal
for (int r = 0; r <= 2; r++) {
for (int c = 0; c <= 3; c++) {
if (b[r][c] == b[r + 1][c + 1] && b[r][c] == b[r + 2][c + 2] && b[r][c] == b[r + 3][c + 3]
&& b[r][c] != ' ') {
foundMjrD = true;
break;
}
}
}
// Check to see if four diagonals in the other direction match (top
// right to bottom left)
// check minor diagonal
for (int r = 0; r <= 2; r++) {
for (int c = 3; c <= 6; c++) {
if (b[r][c] == b[r + 1][c - 1] && b[r][c] == b[r + 2][c - 2] && b[r][c] == b[r + 3][c - 3]
&& b[r][c] != ' ') {
foundMinD = true;
break;
}
}
}
// If ONE of the booleans is true, we have a winner.
// checks boolean for a true
if (foundRow || foundCol || foundMjrD || foundMinD)
return true;
else
return false;
} // end checkWin method
By what I've analyzed by debugging your code , you have not set boolean variable to "true" after toggling it to false. After you are coming out of condition make that boolean variable "true" again.
May this help you. Happy Coding
You should take a closer look at this line:
if (b[r][c] == b[r][c + 1] && b[r][c] == b[r][c + 2] && b[r][c] == b[r][c + 3] && b[r][c] != ' ') {
You check for b[r][c] != ' ', but you never put a space in char[][] board, therefore the default value in board[?][?] is 0.

Growing Tree Algorithm in java not working seamless

I'm trying to create a dungeon generator. First, I place the rooms randomly, then I grow a maze in the empty space between them. But I got a problem, everytime I run my maze algorithm, it creates sometimes strange unreachable corridors:
Take a look at the red squares there. These corridors are unreachable for the player. How to avoid them? Here's some code:
public void createMaze(byte[][] dungeon) {
for (int y = 1; y < dungeon.length; y += 2) {
for (int x = 1; x < dungeon[0].length; x += 2) {
Vector2 pos = new Vector2(x, y);
if (dungeon[y][x] != 2 && dungeon[y][x] != 1){
growMaze(pos, dungeon);
}
}
}
}
public void growMaze(Vector2 pos, byte[][] dungeon) {
// Initialize some Lists and Vars
int lastDir = 0;
ArrayList<Vector2> cells = new ArrayList<Vector2>();
// Adding the startPosition to the cell list.
cells.add(pos);
// When the position is in the Grid
if(pos.y < dungeon.length - 2 && pos.y > 0 + 2 && pos.x < dungeon[0].length - 2 && pos.x > 0 + 2){
// And no walls or floors are around it
if(isPlaceAble(dungeon , pos)){
// Then place a corridor tile
dungeon[(int) pos.y][(int) pos.x] = 4;
}
}
// Here comes the algorithm.
while(!cells.isEmpty()){
// choose the latest cell
Vector2 choosedCell = cells.get(cells.size() - 1);
// Check again if the cell is in the grid.
if(choosedCell.y < dungeon.length - 2 && choosedCell.y > 0 + 2 && choosedCell.x < dungeon[0].length - 2 && choosedCell.x > 0 + 2){
// When that's true, then check in which directions the cell is able to move
boolean canGoNorth = dungeon[(int) (choosedCell.y + 1)][(int) choosedCell.x] == 0 && dungeon[(int) (choosedCell.y + 2)][(int) choosedCell.x] == 0;
boolean canGoSouth = dungeon[(int) (choosedCell.y - 1)][(int) choosedCell.x] == 0 && dungeon[(int) (choosedCell.y - 2)][(int) choosedCell.x] == 0;
boolean canGoEast = dungeon[(int) (choosedCell.y)][(int) choosedCell.x + 1] == 0 && dungeon[(int) (choosedCell.y)][(int) choosedCell.x + 2] == 0;
boolean canGoWest = dungeon[(int) (choosedCell.y)][(int) choosedCell.x - 1] == 0 && dungeon[(int) (choosedCell.y)][(int) choosedCell.x - 2] == 0;
// When there's no available direction, then remove the cell and break the loop...
if(!canGoNorth && !canGoSouth && !canGoEast && !canGoWest ){
cells.remove(cells.size() - 1);
break;
}
else{
// But if there's a available direction, then remove the cell from the list.
Vector2 savedCell = cells.get(cells.size() - 1);
cells.remove(cells.get(cells.size() - 1));
boolean placed = false;
// And place a new one into a new direction. This will happen as long as one is placed.
while(!placed){
// pick a random direction
int randomDirection = MathUtils.random(0,3);
int rdm = randomDirection;
// Init the length of the cells.
int length = 2;
// And now begin, if the direction and the random number fits, then dig the corridor. If no direction/number fits, then redo this until it works.
if(canGoNorth && rdm == 0 ){
int ycoord = 0;
for(int y = (int) choosedCell.y; y < choosedCell.y + length; y++){
dungeon[(int) y][(int) choosedCell.x] = 4;
}
Vector2 newCell = new Vector2(choosedCell.x, choosedCell.y + length);
cells.add(newCell);
lastDir = 0;
placed = true;
}
if(canGoSouth && rdm == 1 ){
int ycoord = 0;
for(int y = (int) choosedCell.y; y > choosedCell.y - length; y--){
dungeon[(int) y][(int) choosedCell.x] = 4;
}
Vector2 newCell = new Vector2(choosedCell.x, choosedCell.y - length);
cells.add(newCell);
lastDir = 1;
placed = true;
}
if(canGoEast && rdm == 2 ){
int xcoord = 0;
for(int x = (int) choosedCell.x; x < choosedCell.x + length; x++){
dungeon[(int) choosedCell.y][x] = 4;
}
Vector2 newCell = new Vector2(choosedCell.x + length, choosedCell.y );
cells.add(newCell);
lastDir = 2;
placed = true;
}
if(canGoWest && rdm == 3 ){
int xcoord = 0;
for(int x = (int) choosedCell.x; x > choosedCell.x - length; x--){
dungeon[(int) choosedCell.y][x] = 4;
}
Vector2 newCell = new Vector2(choosedCell.x - length, choosedCell.y );
cells.add(newCell);
lastDir = 3;
placed = true;
}
}
}
}
else{
cells.remove(cells.size() - 1);
}
}
// And finally delete dead end cells :) (Those who only got 3 Wall/Floor neighbours or 4)
killDeadEnds(dungeon);
}
So how to avoid these unreachable mazes?
You can use a union-find structure to quickly find and remove all the cells that aren't connected to rooms. See: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
You initially create a disjoint set for each corridor or room cell, and then union every pair of sets for adjacent rooms or cells. Finally, delete all the corridor cells that aren't in the same set as a room.
Union-find is also the basis for a nice maze generation algorithm, which is just Kruskal's algorithm for finding spanning trees in a graph ( https://en.wikipedia.org/wiki/Kruskal%27s_algorithm ) applied to a grid. See: http://weblog.jamisbuck.org/2011/1/3/maze-generation-kruskal-s-algorithm
You could use this algorithm to generate your maze in the first place, before applying your dead end removal. It would change the character of your maze, though, so maybe you don't want to.

Issue with Game of life code method? (User interface is complete but actual GOL methods aren't generating what they should)

I've been working on a Game of Life assignment and am nearing the stage of completion, but am struggling to figure out what I've messed up on such that the GOL rules (and Fredkin rules that the assignment requires us to implement as well) are not generating the proper result.
As I have little experience working with graphics I decided to output everything in the interactions window (using Dr.Java). (It's used to set up menu options like the scale, coordinates (you manually enter), generations, and output the final generation of whichever rule you choose to run (GOL or Fredkin).
The program nextGeneration takes a Boolean array map from the main method (where people input coordinates), and should change it to correspond to the next generation of the Game of Life. This happens by creating an entirely new 2D array, map2, which gets values loaded into it based on the number of neighbors which are turned on for each point. At the end of the program, map gets loaded into map2.(Note: this isn't original, this is required by the assignment)
The program living merely checks if a point in the map array is on or off. countNeighbors takes the 8 neighbors of a particular square, passes them each through the living method, and returns the number of neighbors which are currently on. Since countNeighbors sometimes demands either a negative number, or a number greater than the scale of the map, we implemented conditions in living to create that wraparound universe.
I think the problem(s) most likely arise in nextGeneration. I am somewhat tense about using the operand "or" (written as || ), and I think this may be where I screwed up. If you could just look through the code, and see if what I have said is true is written as true, that would be absolutely wonderful.
Below is the code for the program. It also utilizes a Keyboard.class file which I'm happy to post (however one would do that) if that helps (it's required to compile).
public class GameOfLife {
public static void main(String[] args) {
int r = 0; //rules set. Either 0 or 1, 0 for life game, 1 for Fredkin game
int i = 0; // looping variable
int j = 0; // looping variable
int b = 0; // used to read integer inputs from keyboard
int x = 0; // used during the stage where the player manually changes the board. Represents x coordinate.
int y = 0; // used during the stage where the player manually changes the board. Represents x coordinate.
int gen = 0; //number of generations to be skipped before printing out new map
int scale = 0;
boolean[][] map = new boolean[0][0];
System.out.println("Start game? y/n");
String a = Keyboard.readString();
if (a.equals("n")) {
return;
} else {
System.out.println("Do you wish to know the rules? y/n");
a = Keyboard.readString();
if (a.equals("y")) {
System.out.println("Each coordinate in the printed graph is represented by a 0 or a .");
System.out.println("0 represents a live cell, . represents a dead one.");
System.out.println("Each cell has 8 neighboring cells.");
System.out.println("There are two ways in which the game can be played.");
System.out.println("In the Life model, if a cell has 3 neighbors, if dead, it turns on.");
System.out.println("If it has 2 neighbors, it keeps its current condition.");
System.out.println("Else, it dies. Brutal.");
System.out.println("In the Fredkin Model, only non-diagnol neighbors count.");
System.out.println("If a cell has 1 or 3 neighbors, it is alive.");
System.out.println("If it has 0, 2 or 4, it dies. WAY more Brutal.");
}
System.out.println("Do you want to play by Fredkin or Life Rules? 0 for life, 1 for Fredkin");
while (i == 0) {
b = Keyboard.readInt();
if (b == 1) {
r = 1;
i = 1;
}
if (b == 0) {
r = 0;
i = 1;
}
}
while (j == 0) {
System.out.println("What scale would you like to use? Please enter an integer larger than 4");
b = Keyboard.readInt();
if (b >= 5) {
map = new boolean[b][b];
scale = b;
j = 1;
} else {
System.out.println("Come on, buddy, read the rules");
}
}
j = 0;
while (j == 0) {
System.out.println("Do you want to enter coordinates? y to continue entering coordinates, n to go to next option");
a = Keyboard.readString();
if (a.equals("y")) {
i = 0;
while (i == 0) {
System.out.println("Please enter a value for an X coordinate from 0 to " + (scale - 1));
b = Keyboard.readInt();
if (b >= 0) {
if (b < scale) {
i = 1;
x = b;
}
}
}
i = 0;
while (i == 0) {
System.out.println("Please enter a value for a Y coordinate from 0 to " + (scale - 1));
b = Keyboard.readInt();
if (b >= 0) {
if (b < scale) {
i = 1;
y = b;
}
}
}
map[y][x] = true;
printgame(map);
} else {
if (a.equals("n")) {
j = 1;
}
}
}
i = 0;
while (i == 0) {
System.out.println("How many generations would you like to skip ahead? Please enter a value greater than 0");
b = Keyboard.readInt();
if (b > 0) {
gen = b;
i = 1;
}
}
i = 0;
if (r == 0) {
for (i = 0; i <= gen; i++) {
nextGeneration(map);
}
printgame(map);
} else {
if (r == 1) {
for (i = 0; i <= gen; i++) {
FredGen(map);
}
printgame(map);
}
}
}
}
public static void printgame(boolean[][] map) {
int x = map[0].length;
int y = map[0].length;
int i = 0;
int j = 0;
char c;
String Printer = "";
for (j = 0; j < y; j++) {
for (i = 0; i < x; i++) {
if (map[j][i]) {
c = '0';
} else {
c = '.';
}
Printer = (Printer + " " + c);
}
System.out.println(Printer);
Printer = new String("");
}
}
private static void nextGeneration(boolean[][] map) {
int x = map[0].length;
int y = map[0].length;
int[][] neighborCount = new int[y][x];
boolean[][] map2 = new boolean[y][x];
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
neighborCount[j][i] = countNeighbors(j, i, map);
//this makes a new generation array
for (int j = 0; j < y; j++) {
for (int i = 0; i < x; i++) {
if (map[j][i] = true) { //assumes initial value of array is true (AKA "ALIVE")
if (neighborCount[j][i] == 3) { //check if alive AND meeting condition for life
map2[j][i] = true; //sets character array coordinate to ALIVE: "0"
} else if ((neighborCount[j][i] <= 2) || (neighborCount[j][i] > 3)) { //check if dead from isolation or overcrowding
map2[j][i] = false; //sets character array coordinate to DEAD: "."
}
}
}
}
map = map2;
}
private static int countNeighbors(int j, int i, boolean[][] map) { //counts all 8 elements living/dea of 3x3 space surrounding and including living/dead central coordinate)
return living(j - 1, j - 1, map) + living(j - 1, i, map) +
living(j - 1, i + 1, map) + living(j, i - 1, map) + living(j, i + 1, map) +
living(j + 1, i - 1, map) + living(j + 1, i, map) + living(j + 1, i + 1, map);
}
private static int living(int j, int i, boolean[][] map) {
int x = map[0].length - 1;
if (i < 0) {
i = i + x;
} else {
i = i % x;
}
if (j < 0) {
j = j + x;
} else {
j = j % x;
}
if (map[j][i] == true) {
return 1;
} else {
return 0;
}
}
private static void FredGen(boolean[][] map) {
int x = map[0].length;
int y = map[0].length;
int[][] neighborCount = new int[y][x];
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
neighborCount[j][i] = Freddysdeady(j, i, map);
//this makes a new generation array
for (int j = 0; j < y; j++)
for (int i = 0; i < x; i++)
if (map[j][i] = true) { //assumes initial value of array is true (AKA "ALIVE")
if ((neighborCount[j][i] < 1) || (neighborCount[j][i] == 2) || (neighborCount[j][i] > 3)) { //check if dead from isolation or overcrowding
map[j][i] = false; //sets chracter array coordinate to DEAD: "."
} else if ((neighborCount[j][i] == 1) || (neighborCount[j][i] == 3)) { //check if alive AND meeting condition for life
map[j][i] = true; //sets character array coordinate to ALIVE: "0"
}
}
}
private static int Freddysdeady(int j, int i, boolean[][] map) {
return living(j - 1, i, map) + living(j, i - 1, map) + living(j, i + 1, map) + living(j + 1, i, map);
}
}
There might be other problems, here are a few that I could spot by eye:
In the nextGeneration method, you handle cases where a cell should stay alive or die, but you do not have anything for when cells should be born. You should have something like this:
if(map[x][y]) {
//should this cell stay alive? if yes = live, else die
} else {
//should a cell be born in this slot? if yes = born, else nothing
}
This is a minor issue, still in nextGeneration, in if(count==3)live; else if(count <=2 || count > 3) die; is redundant, you only need if(count == 3) live; else die;
let us know, if you still have problems

Place a word in a 2d array

is there a way to place a word in a 2d array in a specific position? For example,i want to give the word, choose vertical or horizontal and the position ((3,3) or (3,4) or (5,6) etc) and the word will be placed in that position.This is my code for the array...
char [][] Board = new char [16][16];
for (int i = 1; i<Board.length; i++) {
if (i != 1) {
System.out.println("\t");
System.out.print(i-1);
}
for (int j = 1; j <Board.length; j++) {
if ((j == 8 && i == 8) ||(j ==9 && i == 9) ||(j == 10 && i == 10) ||(j == 2 && i == 2) )
{
Board[i][j] = '*';
System.out.print(Board[i][j]);
}
else {
if (i == 1) {
System.out.print("\t");
System.out.print(j-1);
}
else {
Board[i][j] = '_';
System.out.print("\t");
System.out.print(""+Board[i][j]);
}
}
(the * means that the word cant be placed there)
Is there a way to place a word in a 2d array in a specific position?
Yes you can implement that. The pseudo-code is something like this:
public void placeWordHorizontally(char[][] board, String word, int x, int y) {
for (int i = 0; i < word.length(); i++) {
if (y + i >= board[x].length) {
// fail ... edge of board
} else if (board[x][y + i]) == '*') {
// fail ... blocked.
} else {
board[x][y + i] = word.charAt(i);
}
}
}
and to do the vertical case you add i etcetera to the x position.
I won't give you the exact code because you'll learn more if you fill in the details yourself.

java grid boundary

The problem is to find the shortest path on a grid from a start point to a finish point. the grid is a 2 dimensional array filled with 0's and 1's. 1's are the path. I have a method that checks the neighbors of a given coordinate to see if its a path. The problem im having is with the boundaries of the grid. The right and bottom boundary can just be checked using the arrays length and the length of a column. But how would i check to make sure that i dont try to check a point thats to the left of the grid or above the grid?
This is my method
public static void neighbors(coordinate current, int[][] grid, Queue q)
{
int row = current.getRow();
int col = current.getCol();
if(grid[row-1][col] == 1)
{
if(grid[row][col] == -1)
{
grid[row-1][col] = grid[row][col] + 2;
}
else
{
grid[row-1][col] = grid[row][col] + 1;
}
coordinate x = new coordinate(row-1,col);
q.enqueue(x);
}
else if(grid[row+1][col] == 1)
{
if(grid[row][col] == -1)
{
grid[row+1][col] = grid[row][col] + 2;
}
else
{
grid[row+1][col] = grid[row][col] + 1;
}
coordinate x = new coordinate(row+1,col);
q.enqueue(x);
}
else if(grid[row][col-1] == 1)
{
if(grid[row][col] == -1)
{
grid[row][col-1] = grid[row][col] + 2;
}
else
{
grid[row][col-1] = grid[row][col] + 1;
}
coordinate x = new coordinate(row, col - 1);
q.enqueue(x);
}
else if(grid[row][col+1] == 1)
{
if(grid[row][col+1] == -1)
{
grid[row][col+1] = grid[row][col] + 1;
}
else
{
grid[row][col+1] = grid[row][col] + 1;
}
coordinate x = new coordinate(row, col + 1);
q.enqueue(x);
}
else
{
}
q.dequeue();
}
I assume that the leftmost and topmost indexes are 0 in your arrays, so just make sure that index-1 >= 0 before indexing into the appropriate array.

Categories

Resources