Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Problem in my 2-Dimensional Array Board Game

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    1
    My Mood
    Amused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Problem in my 2-Dimensional Array Board Game

    I'm suppose to create a 10X10 board, using a 2-dimensional array with 35 random blocked squares ('b') implemented. The goal of the program is, by using recursion, I'm suppose to try to find a path from the bottom left square of the board ([9][0]) to any of the squares at the top of the board ([0][0-9]) leaving a trail of 'x's throughout my movements. Once I find a path all the way to the top, if there is an empty space in one of the top squares, then I mark the square as 'x' and return 1(True) as a result. Else, if there is a 'b' char already in the square, then I return 0(False) as a result.

    At the start of the path find game, I'm suppose to check to see if the starting square ([9][0]) has a 'b' or not. If it has a 'b' char, then it automatically returns a 0 and terminates. But if it has en empty space, I mark an 'x' and continue on. Using recursion, I am suppose to look for a path UP, DOWN, LEFT, and RIGHT. If the square already is blocked 'b', then I can't go that way. If it has an empty space, then I mark an 'x' and continue trying to find a path towards the top.

    I am suppose to display the board before I try to find a path, then after I attempt to find a path up the board, I have to display the result I got and what the board looks like after I found my result -- with a path of 'x's included throughout the board until the last spot where I was terminated.

    Here's my Class code...

    import java.util.Random;
    import java.util.Scanner;
     
    public class Board {
    	private int Row; // Row of the board game
    	private int Column; // Column of the board game
    	private char[][] boardInterface;
    	private boolean checkedStartAlready;
    	Scanner input = new Scanner(System.in);
     
    	// Make a constructor with no arguments that sets the board
    	public Board() {
    		Row = 10;
    		Column = 10;
    		checkedStartAlready = false;
    		boardInterface = new char[Row][Column]; // Initialize board
    		getBoard(); // Generate board with 35 random 'b's
    	}
     
    	// Make a method to get the board
    	public void getBoard() {
    		int placedACharB = 0;
     
    		// Make generator for random numbers
    		Random random = new Random();
    		int generator;
     
    		// Create a loop that sets the character b 35 times in random places
    		for (Row = 0; Row < 10; Row++) {
    			for (Column = 0; Column < 10; Column++) {
    				generator = random.nextInt(3);
    				if ((generator == 0) && (placedACharB < 35)) {
    					boardInterface[Row][Column] = 'b';
    					placedACharB++;
    				} else
    					boardInterface[Row][Column] = ' ';
    			}
    		}
     
    	}
     
    	public int findPath(int currentRow, int currentColumn) {
     
    		// check starting point
    		while (checkedStartAlready == false) {
    			if (checkStartPoint(currentRow, currentColumn) == false)
    				return 0;
    			else
    				checkedStartAlready = true;
    		}
     
    		// check to see if row and column are out of bounds
    		if ((currentRow < 0) || (currentRow > 9))
    			return 0;
    		else if ((currentColumn < 0) || (currentColumn > 9))
    			return 0;
     
    		// check to see if made it to the top
    		while (currentRow == 0) {
    			if (boardInterface[currentRow][currentColumn] == 'b') {
    				return 0;
    			} else {
    				boardInterface[currentRow][currentColumn] = 'x';
    				return 1;
    			}
    		}
     
    		// check to see if space has b or already has x -- if not then mark an x
    		// and continue
    		if (boardInterface[currentRow][currentColumn] == 'b')
    			return 0;
    		else if (boardInterface[currentRow][currentColumn] == 'x')
    			return 0;
    		else {
     
    			// Place new 'x' in empty space of array and continue path
    			boardInterface[currentRow][currentColumn] = 'x';
     
    			// Find next open path -- Look UP, DOWN, LEFT, RIGHT
    			return findPath(currentRow--, currentColumn)
    					+ findPath(currentRow++, currentColumn)
    					+ findPath(currentRow, currentColumn--)
    					+ findPath(currentRow, currentColumn++);
     
    		}
     
    	}
     
    	// Method to check the starting point
    	public boolean checkStartPoint(int startRow, int startColumn) {
    		if (boardInterface[startRow][startColumn] == 'b')
    			return false;
    		else {
    			boardInterface[startRow][startColumn] = 'x';
    			return true;
    		}
    	}
     
    	// Method to display the board
    	public void displayBoard() {
    		for (Row = 0; Row < 10; Row++) {
    			for (Column = 0; Column < 10; Column++) {
    				// print out character
    				System.out.print(boardInterface[Row][Column]);
    			}
    			// if column reaches the end, go to next row
    			System.out.println();
    		}
    		System.out.println();
     
    	}
     
    }

    Here's my Main code...

    public class BoardTester {
     
    	public static void main(String[] args) {
    		Board myBoard = new Board();
    		int startRow = 9;
    		int startColumn = 0;
    		int pathResult;
     
    		// Display the board
    		myBoard.displayBoard();
     
    		// Find path in the board and return result (True == 1, False == 0)
    		pathResult = myBoard.findPath(startRow, startColumn);
     
    		if (pathResult == 0)
    			System.out.println("False");
    		else
    			System.out.println("True");
     
    		// Display board after path results with marked x's INCLUDED
    		myBoard.displayBoard();
     
    	}
     
    }

    Here's an example of what my output SHOULD look like...

    bb b b
    b b  bb
     b       b
     bbb b bbb
     b bbbb
     bbbb    b
         b b
     b b b  b
     
         bb
     
    false
    bb b b
    b b  bb
    xb       b
    xbbb b bbb
    xb bbbbxxx
    xbbbbxxxxb
    xxxxxbxbxx
    xbxbxbxxbx
    xxxxxxxxxx
    xxxxxbbxxx

    But here's the type of output that I keep getting...

    b   b b   
    b b  b    
    b     bbbb
       b   bb 
    b b b  bb 
     bb  b b  
       b b   b
      b  bb   
     bb       
         b  bb
     
    false
    b   b b   
    b b  b    
    b     bbbb
       b   bb 
    b b b  bb 
     bb  b b  
       b b   b
      b  bb   
     bb       
    x    b  bb

    Can somebody explain to me what it is I'm doing wrong? Also, why aren't my 'x's being stored along the way? Also, I'm somewhat of a beginner when it comes to recursion, so please let me know if the recursion could be the problem. Thank you.


  2. #2
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Problem in my 2-Dimensional Array Board Game

    return findPath(currentRow--, currentColumn)
    + findPath(currentRow++, currentColumn)
    + findPath(currentRow, currentColumn--)
    + findPath(currentRow, currentColumn++);

    You know, that's changing the value of currentRow and currentColumn. Did you mean it to do that?



    Also, there may be a way to simplify the code, probably won't fix the problem, but when you're checking to see if it's not a b or an x and if so to put an x, if it's not a b and not an x then wouldn't it be a ' ' then? Why not just check to see if it's a ' ' or not instead of checking to see if it's neither a b nor an x?

  3. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Problem in my 2-Dimensional Array Board Game

    I thought that might be an issue but for all other rows it should skip this loop and enter the if statement below.

    The issue is that the first thing that happens is to check the starting position. If it is blank it places an X in that location. Then the if statement (mentioned above) checks if there is an X at the same location and returns 0 which ends the path search and no more X's are inserted.
    Improving the world one idiot at a time!

  4. #4
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Problem in my 2-Dimensional Array Board Game

    Well, there's also

    while(currentRow ==0)

    and it seems to be only putting an x in row 0.

  5. #5
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Problem in my 2-Dimensional Array Board Game

    Yeah that whole loop is a bit whiffy. It will execute once or not at all. Not much of a loop.
    Improving the world one idiot at a time!

  6. #6
    Junior Member
    Join Date
    Jan 2024
    Posts
    19
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem in my 2-Dimensional Array Board Game

    Your code has a few key issues:

    Recursion Logic: The recursion logic needs refinement. Your use of post-increment and post-decrement operators within recursive calls is causing unintended changes to the variables. Instead, pass incremented/decremented values as arguments without altering the original variables.

    Recursion Termination: The termination condition for recursion is not accurately defined. You're using a while loop to check currentRow == 0, which is redundant. Establish a clear base case to stop recursion when reaching the top row.

    Path Marking: Properly storing 'x's along the path is crucial. Currently, each recursive call is not maintaining its own state of the board. Ensure that each call operates on its own copy of the board to accurately mark the path.

    Displaying the Board: The display board method should update and display the board after every move to visualize the progress accurately.

    For effective resolution, I recommend revising the recursion logic to handle pathfinding and marking correctly. You may also want to explore platforms like https://www.programminghomeworkhelp.com/ for personalized assistance, where experts can offer tailored guidance to address your specific coding challenges.

  7. #7
    Member
    Join Date
    Jan 2024
    Posts
    75
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Post Re: Problem in my 2-Dimensional Array Board Game

    It seems like you're close to solving the issue. The problem lies in how you're handling the recursion and updating the current position. Let's address it step by step:

    Recursion Logic: Your recursive calls seem to be correct, but the way you update currentRow and currentColumn inside those calls is problematic. When you pass currentRow--, currentRow++, currentColumn--, and currentColumn++, you're actually decrementing or incrementing the variables before passing them to the recursive call. However, you want to pass the current values and then decrement or increment them inside the recursive call.

    Updating Position: You need to update the position after each move to ensure you're exploring the board correctly. But it seems like you're not updating the position correctly after each move.

    Let's fix these issues. Here's the revised findPath method:

    public int findPath(int currentRow, int currentColumn) {

    // check starting point
    if (!checkedStartAlready) {
    if (!checkStartPoint(currentRow, currentColumn))
    return 0;
    else
    checkedStartAlready = true;
    }

    // check to see if row and column are out of bounds
    if (currentRow < 0 || currentRow > 9 || currentColumn < 0 || currentColumn > 9)
    return 0;

    // check to see if made it to the top
    if (currentRow == 0) {
    if (boardInterface[currentRow][currentColumn] == 'b')
    return 0;
    else {
    boardInterface[currentRow][currentColumn] = 'x';
    return 1;
    }
    }

    // check to see if space has 'b' or already has 'x' -- if not then mark an 'x' and continue
    if (boardInterface[currentRow][currentColumn] == 'b' || boardInterface[currentRow][currentColumn] == 'x')
    return 0;

    // Mark the current position as 'x'
    boardInterface[currentRow][currentColumn] = 'x';

    // Find next open path -- Look UP, DOWN, LEFT, RIGHT
    int result = 0;
    result += findPath(currentRow - 1, currentColumn); // UP
    result += findPath(currentRow + 1, currentColumn); // DOWN
    result += findPath(currentRow, currentColumn - 1); // LEFT
    result += findPath(currentRow, currentColumn + 1); // RIGHT

    return result;
    }

    In this revised version, I've corrected the way the current position is updated inside the recursive calls, and I've ensured that the current position is marked as 'x' before exploring further. This should help resolve the issues you're facing with storing the 'x's and navigating the board correctly.

    In addressing these adjustments, your recursive logic should function more effectively, enabling the proper exploration of the board and the correct marking of paths with 'x's. Should you require further help with Java assignment or any programming tasks, there are numerous resources available online, such as programminghomeworkhelp.com, that offer guidance and support in mastering these concepts.

    --- Update ---

    It seems like you're looking to count the number of times certain elements in two arrays appear after shuffling them. Here's a way you could approach this:

    ```java
    import java.util.Arrays;
    import java.util.Random;

    public class Main {

    public static void main(String[] args) {

    int[] array1 = {10, 6, 8, 9, 7, 12, 7};
    int[] array2 = {7, 6, 9, 5, 2, 8, 11};

    Random rand = new Random();

    // Shuffle array1
    shuffleArray(array1, rand);

    // Shuffle array2
    shuffleArray(array2, rand);

    // Count occurrences after 6 loops
    int countArray1 = countOccurrences(array1, 6);
    int countArray2 = countOccurrences(array2, 6);

    System.out.println("After 6 loops, array1 'Won' " + countArray1 + " times and array2 'Won' " + countArray2 + " times.");
    }

    // Method to shuffle an array
    public static void shuffleArray(int[] array, Random rand) {
    for (int i = 0; i < array.length; i++) {
    int randomIndexToSwap = rand.nextInt(array.length);
    int temp = array[randomIndexToSwap];
    array[randomIndexToSwap] = array[i];
    array[i] = temp;
    }
    }

    // Method to count occurrences of a specific value after a certain number of loops
    public static int countOccurrences(int[] array, int loops) {
    int count = 0;
    for (int i = 0; i < loops; i++) {
    if (array[i] == 7) { // Change the value here to count occurrences of a different element
    count++;
    }
    }
    return count;
    }
    }
    ```

    This code shuffles both arrays using the `shuffleArray` method, then counts the occurrences of a specific element (in this case, 7) using the `countOccurrences` method after a specified number of loops. You can adjust the value to count occurrences of different elements.

    After 6 loops, array1 'Won' countArray1 times and array2 'Won' countArray2 times. If you find yourself needing further help with Java assignment or understanding concepts like array manipulation, there are various resources available online to help guide you through. Seeking guidance from online forums, tutorials, or even reaching out to programming assignment helping websites such as programminghomeworkhelp.com can provide valuable insights. Remember, practice and exploration are key components of mastering programming.

Similar Threads

  1. Java (2 dimensional array problem)
    By JoshuAtenista in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 21st, 2013, 06:38 AM
  2. Help with assignment about a board game (enum and array question)
    By Kranti1992 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 12th, 2012, 07:47 AM
  3. Problem with Two-Dimensional Array Program
    By soradogoof in forum Collections and Generics
    Replies: 26
    Last Post: February 20th, 2012, 08:17 PM
  4. help with board game assignment
    By pjay in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 19th, 2011, 12:58 PM
  5. Problem printing a two dimensional boolean array
    By sallyB in forum What's Wrong With My Code?
    Replies: 10
    Last Post: June 23rd, 2011, 03:56 PM

Tags for this Thread