Question

Simulate how many steps its take a random walker starting at the center of an 10x10...

Simulate how many steps its take a random walker starting at the center of an 10x10 grid to visit every cell of the grid. If the walker tries to go outside of the grid then it doesn't move in that step.

Write a java program which simulates th steps of the random walker, and keeps hold about the grid with 2D boolean array and write out the steps when the random walker have walked all the cells.

-----------------------------------------------------------------------------------------------

I have managed to come up with this code:

-----------------------------------------------------------------------------------------------

public class SlembiEind2 {

public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int[] x = new int[n];
int[] y = new int[n];
int steps = 0;
int ctv = n*n;
boolean[][] fylki = new boolean[n][n];
  
StdDraw.setXscale(0,n-1);
StdDraw.setYscale(0,n-1);
StdDraw.clear(StdDraw.GRAY);
StdDraw.enableDoubleBuffering();
  
for(int i = 0; i < n; i++) {
x[i] = n/2;
y[i] = n/2;
StdDraw.filledSquare(x[i], y[i], 0.45);
}
fylki[n/2][n/2] = true;
ctv--;

while (ctv > 0) {

double r = Math.random();
for(int i = 0; i < n; i++) {
  
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.filledSquare(x[i], y[i], 0.45);
StdDraw.show();
StdDraw.pause(100);
if(r < 0.25){
x[i]--;
} else if(r < 0.50){
x[i]++;
} else if(r < 0.75){
y[i]--;
} else if(r < 1.00){
y[i]++;
}

if (x[i] < n && y[i] < n && x[i] >= 0 && y[i] >= 0 && !fylki[x[i]][y[i]]) {
ctv--;
fylki[x[i]][y[i]] = true;   
  
}
steps++;
StdDraw.setPenColor(StdDraw.WHITE);
System.out.println(ctv + " " + steps);
}   
}
StdOut.println("Total steps = " + steps);
}
}

-------------------------------------------------------------------------------------

But I have two problems.

The walker seems to walk outside of the array/grid.

And it keeps counting the steps when it walks outside of the grid.

Anyway you can help me fix the code so it fix these problems? The code should not count if the walke trys to go out of the grid!

-----------------------------------------------------------------------------

ctv is the cells left to visit before the walker fill the grid!

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

import java.io.*;
import java.util.*;


public class DemoWalker {
  
    public static boolean check(char data[][]){
        boolean found = true;
        int count = 0;
        for (int i = 0; i<10; i++){
           for(int j= 0; j<10; j++){
              if (data[i][j] != 'V')
                 found = false;
              else
                 count++;
           }
        }
        System.out.println(count);
        return found;
    }

    public static void main(String[] args){

        Random rand = new Random();
        char[][] grid = new char[10][10];
        int x,y;
        int opt;

        for (int i = 0; i<10; i++){
            for(int j = 0; j<10; j++){
               grid[i][j] = '.';
            }
        }
        grid[5][5] = 'V';
        x = 5;
        y = 5;
        int count = 0;
        while (!check(grid)){
           
       
               opt = rand.nextInt(4);
               if (opt == 0){
                  if ((x-1) > 0)
                      x = x-1;
                   
               }
               if (opt == 1){
                  if ((x+1) < 10)
                    x = x+1;
               }
               if (opt == 2){
                 if ((y-1) > 0)
                    y = y-1;
               }
               if (opt == 3){
                  if ((y+1) < 10)
                    y = y+1;
               }
           
            grid[x][y] = 'V';
            System.out.println("Moved to :" + x + " " +y);
        }
        count++;
        System.out.println("The number of steps : " + count);               

    }
}

Add a comment
Know the answer?
Add Answer to:
Simulate how many steps its take a random walker starting at the center of an 10x10...
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
  • I have the following java-program, that creates a random walk starting at (0,0) and continuing until...

    I have the following java-program, that creates a random walk starting at (0,0) and continuing until x or y is greater than abs(n). First: I get an error, when I try closing the Scanner by inserting "reader.close(); " in line 28. It says "Unreachable code". How can I fix that? Second: Is it possible to create a different colour for the StdDraw.point when it reaches a point on one of the edges "n+1" or "n-1" ? 1 import java.util.*; 3...

  • How do I take a random char element from an existing array and assign it to...

    How do I take a random char element from an existing array and assign it to a new array? I have this code with a testing method but my code only returns an empty array instead of the chars expected. public static char[] generateHiddenCode(Random rand, int numPositions, char[] symbols) { char[] arrCode = new char[numPositions]; for (int i=0; i<arrCode.length; ++i) { arrCode[i] = (char) rand.nextInt(symbols.length); } return arrCode; } Test:    private static void testGenerateHiddenCode() { boolean error = false;...

  • Please make this code workable and straight. this code does produce a proper output but just...

    Please make this code workable and straight. this code does produce a proper output but just not in proper format. please solve this. thank you. import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; public class MyMaze { private int dimensionX, dimensionY; // dimension of maze private int gridDimensionX, gridDimensionY; // dimension of output grid private char[][] grid; // output grid private Cell[][] cells; // 2d array of Cells private Random random = new Random(); // The random object public MyMaze(int...

  • (Intro to Java help?) Define a class named RandomWalker. A RandomWalker object should keep track of...

    (Intro to Java help?) Define a class named RandomWalker. A RandomWalker object should keep track of its (x, y) location. All walkers start at the coordinates (0, 0). When a walker is asked to move, it randomly moves either left, right, up or down. Each of these four moves should occur with equal probability. The resulting behavior is known as a "random walk." (A 2-dimensional random walk example is pictured at right.) Each RandomWalker object should have the following public...

  • Java code for percolation, code compiles correctly but when it takes values for Input10.txt , the...

    Java code for percolation, code compiles correctly but when it takes values for Input10.txt , the code is suppose to comeback that the system percolates but instead it comes back with the exception. Photos below show the exception. I belive there may be an issue with my logic in the for loop for when to throw the exception. also, i have put the values of Input10.txt at the bottom to try and use to see the exception. The exception i...

  • package homework; import java.util.Arrays; import stdlib.*; /** CSC300Homework4 version 1.0 * *    * * Find...

    package homework; import java.util.Arrays; import stdlib.*; /** CSC300Homework4 version 1.0 * *    * * Find the 3 Sections marked TODO: * * TODO #1: SumOddsRecursive * TODO #2: ReverseArray * TODO #3: MergeArrays * * You must not add static variables. You MAY add static functions. * * It is okay to add functions, such as * * <pre> * public static double sumOfOddsHelper (double[] list, int i) { * </pre> * * but it is NOT okay to...

  • (a)How many times does the code snippet given below display "Hello"? int x = 1; while...

    (a)How many times does the code snippet given below display "Hello"? int x = 1; while (x != 15) {    System.out.println ("Hello");    x++; } (b)What is the output of the following code fragment? int i = 1; int sum = 0; while (i <= 5) {    sum = sum + i;    i++; } System.out.println("The value of sum is " + sum); Quie 2 What is the output of the following snipped code? public class Test {...

  • Cache performance The starting code would have: struct position { int x; int y; } int...

    Cache performance The starting code would have: struct position { int x; int y; } int N; struct position grid[N][N]; int totalX=0; int totalY=0; int i, j; //For X loop for( i = 0; i < N; i ++){ for( j = 0; j < N; j++){ totalX += grid[i][j].x; } } //For Y loop for( j = 0; j < N; j++){ for( i = 0; i < N; i++){ totalY += grid[i][j].y; } } Part I: This part...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public...

    Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public class Project2 { //Creating an random class object static Random r = new Random(); public static void main(String[] args) {    char compAns,userAns,ans; int cntUser=0,cntComp=0; /* * Creating an Scanner class object which is used to get the inputs * entered by the user */ Scanner sc = new Scanner(System.in);       System.out.println("*************************************"); System.out.println("Prime Number Guessing Game"); System.out.println("Y = Yes , N = No...

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