Question

Hello, I am currently taking a Foundations of Programming course where we are learning the basics of Java. I am struggli...

Hello, I am currently taking a Foundations of Programming course where we are learning the basics of Java.

I am struggling with a part of a question assigned by the professor.

He gave us this code to fill in:

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

public class RobotGo {

    public static Random r = new Random(58);

    public static void main(String[] args) {

        char[][] currentBoard = createRandomObstacle(createBoard(10, 20), 100);
        displayBoard(startNavigation(currentBoard))

    }

    public static int[] getRandomCoordinate(int maxY, int maxX) {
        int[] coor = new int[2];
        int y = r.nextInt(maxY);
        int x = r.nextInt(maxX);
        coor[0] = y;
        coor[1] = x;
        return coor;
    }
    public static char[][] createBoard(int row, int col) {
        if (row < 5 || col < 5) {
            throw new IllegalArgumentException("Both x and y axes must be greater than or equal to 5.");
        }
        char[][] board = new char[row][col];
        for (int i = 0; i < col; i++) {
            board[0][i] = '#';
        }
        for (int i = 1; i < row - 1; i++) {
            board[i][0] = '#';
            for (int j = 1; j < col - 1; j++) {
                board[i][j] = ' ';
            }
            board[i][col - 1] = '#';
        }
        for (int i = 0; i < col; i++) {
            board[row - 1][i] = '#';
        }
        board[1][1] = '.';
        board[row - 2][col - 2] = 'x';
        return board;
    }
    private static char[][] createRandomObstacle(char[][] board, int num) {
        int space = 0;

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == ' ') {
                    space += 1;
                }
            }
        }
        if (num > space) {
            throw new IllegalArgumentException("Too many obstacles");
        }
        for (int i = 0; i < num; i++) {
            int[] randCoord = getRandomCoordinate(board.length, board[0].length);
            while (board[randCoord[0]][randCoord[1]] != ' ') {
                randCoord = getRandomCoordinate(board.length, board[0].length);
            }
            board[randCoord[0]][randCoord[1]] = '#';
        }
        return board;
    }

    private static void displayBoard(char[][] board){
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
               if (board[i][j] != ' ') {
                    System.out.print(board[i][j]);
                }
            }
            System.out.println("");
        }
    }
}

The question is:

Write a method called startNavigation() that takes char[][] board and return the board char[][] which has all the moves labelled. For maze solving algorithm, you should use the right-hand rule solution. In this solution, the robot solves the maze by continuously following the right wall. In order to successfully implement the righthand rule solution, you might need to implement turnRight() and turnLeft() as your helper method.

For example, consider the following boards, char[][] board:

• board = [[#, #, #, #, #], [#, ., , , #], [#, , , , #], [#, , , x, #], [#, #, #, #, #]]; calling the startNavigation(board) should return: [[#, #, #, #, #], [#, ., , , #], [#, ., , , #], [#, ., ., x, #], [#, #, #, #, #]] and calling the displayBoard(board) should print:

#####

#. #

#. #

#..x#

#####

• board = [[#, #, #, #, #], [#, ., , , #], [#, , , #, #], [#, #, , x, #], [#, #, #, #, #]] calling the startNavigation(board) should return: [[#, #, #, #, #], [#, ., , , #], [#, ., ., #, #], [#, #, ., x, #], [#, #, #, #, #]] and calling the displayBoard(board) should print:

#####

#. #

#..##

##.x#

#####

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Your examples are optimized they don't follow right hand rule, instead they use both right and left turn.

here is code that use right hand rule;

import java.util.Arrays;

import java.util.Random;

public class RobotGo {
    public static Random r = new Random(58);

    public static void main(String[] args) {
        char[][] currentBoard = createRandomObstacle(createBoard(10, 20), 0);
        displayBoard(startNavigation(currentBoard));
    }

    private static char[][] startNavigation(char[][] currentBoard) {
       boolean end = false;
       int posX = 1;
       int posY = 1;
       int dir = 1;//1 is down, 2 is right, 3 is up, 4 is left.
       long steps = 0;
       while(!end){
           switch (dir) {
           case 1:
               if(currentBoard[posX+1][posY]=='#'){
                   dir = turnRight(dir);
               }
               else{
                   posX++;
                   if(currentBoard[posX][posY]==' '){
                       currentBoard[posX][posY]='.';
                   }
                   steps++;
                   if(posX==(currentBoard.length-2) && posY==(currentBoard[0].length-2)){
                       end = true;
                   }
               }
               break;
           case 2:
               if(currentBoard[posX][posY+1]=='#'){
                   dir = turnRight(dir);
               }
               else{
                   posY++;
                   if(currentBoard[posX][posY]==' '){
                       currentBoard[posX][posY]='.';
                   }
                   steps++;
                   if(posX==(currentBoard.length-2) && posY==(currentBoard[0].length-2)){
                       end = true;
                   }
               }
               break;
           case 3:
               if(currentBoard[posX-1][posY]=='#'){
                   dir = turnRight(dir);
               }
               else{
                   posX--;
                   if(currentBoard[posX][posY]==' '){
                       currentBoard[posX][posY]='.';
                   }
                   steps++;
               }
               break;
           case 4:
               if(currentBoard[posX][posY-1]=='#'){
                   dir = turnRight(dir);
               }
               else{
                   posY--;
                   if(currentBoard[posX][posY]==' '){
                       currentBoard[posX][posY]='.';
                   }
                   steps++;
               }
               break;
           default:
               break;
           }
            if(steps>100000){
               end = true;
               System.out.println("The Robot is Stucked! try different Bord.");
           }
       }
       return currentBoard;
   }

   private static int turnLeft(int dir) {
       dir++;
       if(dir==5){
           dir = 1;
       }
       return dir;
   }

   private static int turnRight(int dir) {
       dir--;
       if(dir==0){
           dir = 4;
       }
       return dir;
   }

   public static int[] getRandomCoordinate(int maxY, int maxX) {
        int[] coor = new int[2];
        int y = r.nextInt(maxY);
        int x = r.nextInt(maxX);
        coor[0] = y;
        coor[1] = x;
        return coor;
    }
    public static char[][] createBoard(int row, int col) {
        if (row < 5 || col < 5) {
            throw new IllegalArgumentException("Both x and y axes must be greater than or equal to 5.");
        }
        char[][] board = new char[row][col];
        for (int i = 0; i < col; i++) {
            board[0][i] = '#';
        }
        for (int i = 1; i < row - 1; i++) {
            board[i][0] = '#';
            for (int j = 1; j < col - 1; j++) {
                board[i][j] = ' ';
            }
            board[i][col - 1] = '#';
        }
        for (int i = 0; i < col; i++) {
            board[row - 1][i] = '#';
        }
        board[1][1] = '.';
        board[row - 2][col - 2] = 'x';
        return board;
    }
    private static char[][] createRandomObstacle(char[][] board, int num) {
        int space = 0;

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == ' ') {
                    space += 1;
                }
            }
        }
        if (num > space) {
            throw new IllegalArgumentException("Too many obstacles");
        }
        for (int i = 0; i < num; i++) {
            int[] randCoord = getRandomCoordinate(board.length, board[0].length);
            while (board[randCoord[0]][randCoord[1]] != ' ') {
                randCoord = getRandomCoordinate(board.length, board[0].length);
            }
            board[randCoord[0]][randCoord[1]] = '#';
        }
        return board;
    }

    private static void displayBoard(char[][] board){
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
               if (board[i][j] != ' ') {
                    System.out.print(board[i][j]);
                }
            }
            System.out.println("");
        }
    }
}

Add a comment
Know the answer?
Add Answer to:
Hello, I am currently taking a Foundations of Programming course where we are learning the basics of Java. I am struggli...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner...

    Hello I am having trouble with a connectFour java program. this issue is in my findLocalWinner method, it declares a winner for horizontal wins, but not for vertical. if anyone can see what im doing wrong. public class ConnectFour { /** Number of columns on the board. */ public static final int COLUMNS = 7; /** Number of rows on the board. */ public static final int ROWS = 6; /** Character for computer player's pieces */ public static final...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • This is my code for my game called Reversi, I need to you to make the...

    This is my code for my game called Reversi, I need to you to make the Tester program that will run and complete the game. Below is my code, please add comments and Javadoc. Thank you. public class Cell { // Displays 'B' for the black disk player. public static final char BLACK = 'B'; // Displays 'W' for the white disk player. public static final char WHITE = 'W'; // Displays '*' for the possible moves available. public static...

  • Hi i need heeeeelllllp on this assignment i need to print the numbers diagonal top right...

    Hi i need heeeeelllllp on this assignment i need to print the numbers diagonal top right corner to the bottom left corner and i dont know how to do it please help me thank you dd another method to the bottom of the "TwoDimArraysMethods.java" file called "printDiagonalRL()"                                         public static void printDiagonalRL(int[][] matrix) 4. Call this method in the main file ("TwoDimArraysAsParam.java") passing it "board." e.g. TwoDimArraysMethods.printDiagonal(board); 5. Your new method should print any numbers along the diagonal from...

  • Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static...

    Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static String solve(char[][] grid) {        // TODO        /*        * 1. Construct a graph using grid        * 2. Use BFS to find shortest path from start to finish        * 3. Return the sequence of moves to get from start to finish        */               // Hardcoded solution to toyTest        return...

  • why do i get this syntax error? for example: i have these two classes: class Maze...

    why do i get this syntax error? for example: i have these two classes: class Maze { private: int row, col; cell **arr; public: Maze(int r = 0, int c = 0) { this->row = r; this->col = c; arr = new cell*[row]; for (int i = 0; i < row; i++) arr[i] = new cell[col]; } }; class cell { private: bool visited; bool up, down, right, left; int x, y; int px, py; char status; public: cell() {...

  • This is java. Goal is to create a pacman type game. I have most of the...

    This is java. Goal is to create a pacman type game. I have most of the code done just need to add in ghosts score dots etc. Attached is the assignment, and after the assignment is my current code. import java.awt.Color; import java.awt.Dimension; import java.awt.Image; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Scanner; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; public class Maze extends JFrame implements KeyListener { private static final String[] FILE = {...

  • This is my code for a TicTacToe game. However, I don't know how to write JUnit...

    This is my code for a TicTacToe game. However, I don't know how to write JUnit tests. Please help me with my JUnit Tests. I will post below what I have so far. package cs145TicTacToe; import java.util.Scanner; /** * A multiplayer Tic Tac Toe game */ public class TicTacToe {    private char currentPlayer;    private char[][] board;    private char winner;       /**    * Default constructor    * Initializes the board to be 3 by 3 and...

  • Chapter 8 Exercise 36, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY. 8.36 (Latin square)...

    Chapter 8 Exercise 36, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY. 8.36 (Latin square) A Latin square is an n-by-n array filled with n different Latin letters, each occurring exactly once in each row and once in each column. Write a program that prompts the user to enter the number n and the array of characters, as shown in the sample output, and checks if the input array is a Latin square. The characters are the first n...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT