first commit
This commit is contained in:
37
Hjemmeopgaver/Hjemmeopgave nr. 2/RandomWalk.java
Normal file
37
Hjemmeopgaver/Hjemmeopgave nr. 2/RandomWalk.java
Normal file
@@ -0,0 +1,37 @@
|
||||
import java.util.Random;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class RandomWalk {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner console = new Scanner(System.in);
|
||||
Random random = new Random();
|
||||
System.out.print("Enter size of grid: ");
|
||||
int gridSize = 0;
|
||||
if (!console.hasNextInt()) {
|
||||
throw new IllegalArgumentException("Not a number");
|
||||
} else {
|
||||
gridSize = Math.abs(console.nextInt());
|
||||
}
|
||||
StdDraw.setXscale(-gridSize, gridSize); // Opsætning af StdDraw, sætter størelse på felt til -gridSize, gridSize i x og y.
|
||||
StdDraw.setYscale(-gridSize, gridSize);
|
||||
StdDraw.setPenRadius(2.0 / (gridSize*4));
|
||||
int x = 0;
|
||||
int y = 0;
|
||||
int numSteps = 0;
|
||||
while (
|
||||
x >= -gridSize && x <= gridSize && y >= -gridSize && y <= gridSize // Mens punktet er inde for -gridSize, gridSize i både x og y.
|
||||
) {
|
||||
int direction = random.nextInt(4); // Random værdi (0, 1, 2 eller 3). 0 = op. 1 = ned. 2 = venstre. 3 = højre.
|
||||
if (direction >= 2) {
|
||||
x += (direction == 3 ? 1 : -1); // Bevæg sig venstre eller højre
|
||||
} else {
|
||||
y += (direction == 1 ? 1 : -1); // Bevæg sig op eller ned
|
||||
}
|
||||
System.out.println("Position: (" + x + ", " + y + ")");
|
||||
numSteps++;
|
||||
StdDraw.point(x,y);
|
||||
}
|
||||
System.out.println("Total number of steps: " + numSteps);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user