Writing RandomWalk Class: Objectives Write a class with appropriate methods, inc
ID: 3593259 • Letter: W
Question
Writing RandomWalk Class:
Objectives
Write a class with appropriate methods, including overloaded constructors.
Write a driver class that uses the above class.
Use static variables and methods.
Use classes from the Java standard library.
Use existing classes.
Create a list of objects using the ArrayList class.
Specification
Generate a random walk on an n by n grid that starts at [0,n-1] (bottom-left corner) and ends up at [n-1,0] (top-right corner).
At each point, there are four potential directions in which we can walk: North, East, South, and West. To avoid getting stuck, we will only walk to the North or East with equal probability. This way, we will always be making progress towards the destination (the north-east corner).
See the figure at the top of the page for a sample random walk.
Part 1: Creating the RandomWalk class
If you haven't already, create a RandomWalk class. Think about the attributes this class will have:
size of the grid,
a random number generator,
a boolean flag named done,
an ArrayList of points to represent the path of the random walk,
as well as other instance variables as you may see fit.
Use the Point class provided in the Java standard library (in the java.awt package) to represent each point on the path. For example, the start point can be represented as:
Point start = new Point(0,size-1);
You can access the coordinates of the point using:
start.x
start.y
Use an ArrayList of Point objects to store the path. The ArrayList class is part of the java.util package and provides functionality for managing a list of objects. There are several methods available in the ArrayList class (e.g. add, remove, isEmpty, contains, etc.).
You can construct an ArrayList instance for managing your Point objects as follows:
ArrayList<Point> path = new ArrayList<Point>();
Then, you can add new points to your path using the add(...) method of the ArrayList class as follows:
Point p1 = new Point(x, y);
path.add(p1);
Signatures for the methods you must implement in your RandomWalk class. Please note that while you must implement the methods below exactly as defined by their signatures, you may also implement additional methods as needed:
public RandomWalk(int gridSize)
Initializes the instance variables and the starting point of the walk, but doesn't create the walk. Creates a random number generator without a seed.
public RandomWalk(int gridSize, long seed)
Same as the above constructor except that we specify a seed for the random number generator. This is very useful for debugging and testing as the same seed will give the same random number sequence so that we can reproduce a bug! This constructor illustrates the concept of method overloading.
public void step()
Makes the walk go one more step. To add this step to your path, you will add the new Point to your ArrayList. A new step should be added to your path every time the method is called.
If the step is the final step, set the value of the done instance variable to true to signal that you are done with the random walk.
Note that we will walk North or East with equal probability (use the random number generator). If you are at one of the edges, then you may have only one direction in which you can walk. You can handle this case in multiple ways. For example, you can always pick one of North or East and then if you find you cannot go in that direction, just generate another random choice until you can move.
public void createWalk()
Creates the entire walk in one call by internally using the step() method.
public boolean isDone()
Returns the current value of the done variable. (Just returns the value of the variable. Does not actually check if the path is at the end, this happens in the step method.)
public ArrayList<Point> getPath()
Getter to get reference to the random walk path.
public String toString()
Returns the path as a nicely formatted string as shown below:
[0,4] [0,3] [1,3] [1,2] [2,2] [3,2] [3,1] [4,1] [4,0]
RANDOMWALKTEST CODE:
import java.awt.Point;
/**
* @author
*/
public class RandomWalkTest
{
private static int gridSize = 0;
private static long seed = 0;
/**
*
*/
private static void getInput()
{
}
/**
* @param args
*/
public static void main(String[] args)
{
// call getInput to process user input
// create RandomWalk object using the appropriate constructor
// create the random walk and then print it
}
}
Other code that shouldn't be modified, only used:
RANDOMWALKGUI.java
import javax.swing.JFrame;
/**
* Creates a GUI that shows a random walk one step at a time.
* @author amit
*
*/
public class RandomWalkGUI {
/**
* Verify input parameters.
* @param gridSize the size of the grid
* @param seed the seed for the random number generator
*/
private static void checkInput(int gridSize, long seed)
{
if (gridSize <= 0) {
System.err.println("Error: grid size must be positive!");
System.exit(1);
}
if (seed < 0) {
System.err.println("Error: seed must be >= 0!");
System.exit(1);
}
}
/**
* Creates the GUI frame and displays a animated grid map on it.
* @param walker the RandomWalk object used for creating the walk
* @param gridSize the size of the grid
*/
private static void createGUI(RandomWalk walker, int gridSize)
{
JFrame frame = new JFrame("RandomWalk GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridMap panel = new GridMap(walker, gridSize);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
/**
* Get input using the command line arguments and create and display the walk.
* @param args
*/
public static void main(String[] args)
{
int gridSize = 10;
long seed = 0;
if (args.length == 0) {
System.err.println("Usage: java RandomWalkGUI <gridSize> [<random seed>]");
System.exit(1);
}
if (args.length == 1) {
gridSize = Integer.parseInt(args[0]);
} else if (args.length == 2) {
gridSize = Integer.parseInt(args[0]);
seed = Long.parseLong(args[1]);
}
checkInput(gridSize, seed);
RandomWalk walker;
if (seed > 0) {
walker = new RandomWalk(gridSize, seed);
} else {
walker = new RandomWalk(gridSize);
}
createGUI(walker, gridSize);
}
}
GRIDMAP. JAVA:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
* Animates the movement of a walker on a grid. The grid is shown
* with the origin (0, 0) at the top left corner.
*
* @author amit
* @author mvail
*/
@SuppressWarnings("serial")
public class GridMap extends JPanel
{
private int displaySize = 600;
private int blockSize;
private int offset;
private int numBlocks;
private int delay = 100; // milliseconds
private RandomWalk walk;
/**
*
* @param walk
* The RandomWalk object to animate on the city map
* @param gridSize
* The size of the grid: from (0,0) to (gridSize,gridSize)
*/
public GridMap(RandomWalk walk, int gridSize)
{
this.walk = walk;
numBlocks = gridSize;
blockSize = displaySize / (numBlocks);
offset = blockSize;
setBackground(Color.white);
setPreferredSize(new Dimension(displaySize + offset, displaySize + offset));
startAnimation();
}
/*
* (non-Javadoc)
*
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
public void paintComponent(Graphics obj)
{
Graphics2D page = (Graphics2D) obj;
super.paintComponent(page);
Font font = new Font(Font.MONOSPACED, Font.PLAIN, blockSize / 3);
page.setFont(font);
page.setColor(Color.red);
drawMap(page);
if (!walk.isDone()) {
walk.step();
}
drawPath(page);
ArrayList<Point> path = walk.getPath();
page.setColor(Color.blue);
Point where = path.get(path.size()-1);
// draw the walker as a rectangle
page.fillRect(where.x * blockSize + offset - blockSize / 8,
where.y * blockSize + offset - blockSize / 8,
blockSize/4, blockSize/4);
}
/**
* Draws the grid and labels it using coordinates in terms of blocks.
* @param page
*/
private void drawMap(Graphics2D page)
{
// draw east-west lines for blocks 0 .. numBlocks - 1
for (int i = 0; i < numBlocks - 1; i++) {
page.drawString(i + "", offset / 2, i * blockSize
+ offset);
for (int j = 0; j < numBlocks; j++) {
page.drawLine(i * blockSize + offset, j * blockSize + offset,
(i + 1) * blockSize + offset, j * blockSize + offset);
}
}
page.drawString(numBlocks - 1 + "", offset / 2, (numBlocks - 1) * blockSize
+ offset);
// draw north-south lines for blocks 0 .. numBlocks - 1
for (int i = 0; i < numBlocks; i++) {
page.drawString(i + "", i * blockSize + offset, offset / 2);
for (int j = 0; j < numBlocks - 1; j++) {
page.drawLine(i * blockSize + offset, j * blockSize + offset, i
* blockSize + offset, (j + 1) * blockSize + offset);
}
}
}
/**
* Draws the path of the walk in a different color with a thicker line
* @param page
*/
private void drawPath(Graphics2D page)
{
final int PATH_THICKNESS = 3;
page.setColor(Color.blue);
page.setStroke(new BasicStroke(PATH_THICKNESS));
ArrayList<Point> path = walk.getPath();
Point prev = path.get(0);
for (Point next: path) {
page.drawLine(prev.x * blockSize + offset, prev.y * blockSize + offset,
next.x * blockSize + offset, next.y * blockSize + offset);
prev = next;
}
page.setStroke(new BasicStroke()); //back to default stroke width
}
/**
* Create an animation thread that runs periodically
*/
private void startAnimation()
{
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
repaint();
}
};
new Timer(delay, taskPerformer).start();
}
}
Explanation / Answer
package first;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;
public class RandomWalk {
Random rnd1;
boolean done=false;
ArrayList<Point> path;
int size,x,y;
public RandomWalk(int gridSize)
{
size=gridSize;
path=new ArrayList<Point>();
Point start=new Point(0, gridSize);
path.add(start);
rnd1 = new Random();
x=start.x;
y=start.y;
}
public RandomWalk(int gridSize,long seed)
{
size=gridSize;
path=new ArrayList<Point>();
Point start=new Point(0, gridSize);
path.add(start);
rnd1 = new Random(seed);
x=start.x;
y=start.y;
}
public void createWalk(){
while(!isDone())
{
step();
}
System.out.println("Path created " + x + "," + y);
}
public void step(){
int step=rnd1.nextInt(2);
if(step==0){
Point rightStep=new Point(++x, y);
if(x<=size)
{
path.add(rightStep);
System.out.println("Point added = " + rightStep.getX() + "," + rightStep.getY());
}
else
--x;
}
else{
Point topStep=new Point(x, --y);
if(y>=0)
{
path.add(topStep);
System.out.println("Point added = " + topStep.getX() + "," + topStep.getY());
}
else
++y;
}
if(x==size && y==0){
setDone(true);
}
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public ArrayList<Point> getPath() {
return path;
}
public void setPath(ArrayList<Point> path) {
this.path = path;
}
public String toString()
{
String pathString="";
for (Point point : path) {
pathString=pathString+"["+point.getX()+","+point.getY()+"],";
}
return pathString;
}
public static void main(String[] args) {
RandomWalk rw=new RandomWalk(4);
rw.createWalk();
System.out.println(rw.toString());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.