//RandomWalk2.java //avoid re-visiting a point import java.awt.*; import javax.swing.*; public class RandomWalk2 extends JApplet { int lines; int scale; //conversion to screen pixels public void init() { String input; input = JOptionPane.showInputDialog("Enter # of steps to take"); lines = Integer.parseInt(input); input = JOptionPane.showInputDialog("Enter scale factor"); scale = Integer.parseInt(input); } public void paint( Graphics g ) { super.paint( g ); int xPrev, yPrev, xNow, yNow; int xCenter=getWidth()/2; int yCenter=getHeight()/2; double totalDist=0, avgDist=0, dist; //int scale=15; //conversion to screen pixels int [] X = new int[lines+1]; //** int [] Y = new int[lines+1]; boolean foundNew; int attempts; xPrev = xNow = xCenter; //start in center yPrev = yNow = yCenter; X[0] = xNow; //** Y[0] = yNow; g.setColor(Color.RED); g.fillRect(xPrev-3,yPrev-3,5,5); g.setColor(Color.BLACK); for (int step=1; step<=lines; step++) { foundNew = false; //** attempts = 0; do { switch ((int)(Math.random()*4)) { case 0: //up yNow = yPrev - scale; break; case 1: //down yNow = yPrev + scale; break; case 2: //left xNow = xPrev - scale; break; case 3: //left xNow = xPrev + scale; break; } if (!pairExists(X,Y,xNow,yNow,step)) //** foundNew = true; } while (!foundNew && ++attempts<30); //**avoid inf. loop if stuck if (attempts == 30) //**indicates was probably stuck //should check each 8 nbors to see if any unvisited yet... g.setColor(Color.RED); else g.setColor(Color.BLACK); g.drawLine(xPrev,yPrev,xNow,yNow); X[step] = xNow; //** Y[step] = yNow; xPrev = xNow; yPrev = yNow; int x = (xNow - xCenter) / scale; int y = (yNow - yCenter) / scale; dist = Math.sqrt(x*x+y*y); totalDist += dist; avgDist = totalDist / step; showStatus("Distance from origin: " + (int)dist + " Average distance: " + (int)avgDist); } } //** public boolean pairExists(int[] A, int[] B, int x, int y, int numPoints) { int i=0; while (i