Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class AntWalk {
- public static void main(String[] args) {
- int gridSize = 9;
- int[][] grid = new int[gridSize][gridSize];
- int x = 4;
- int y = 4;
- int moves = 0;
- String directionFallen = "";
- while (x > 0 && x < 8 && y > 0 && y < 8) {
- grid[x][y]++;
- int move = (int) (Math.random() * 4);
- if (move == 0) {
- x--;
- } else if (move == 1) {
- x++;
- } else if (move == 2) {
- y--;
- } else if (move == 3) {
- y++;
- }
- moves++;
- }
- if (x == 0) {
- directionFallen = "NORTH";
- } else if (x == 8) {
- directionFallen = "SOUTH";
- } else if (y == 0) {
- directionFallen = "WEST";
- } else if (y == 8) {
- directionFallen = "EAST";
- }
- displayGrid(grid, gridSize);
- System.out.println("Moves: " + moves);
- System.out.println("The ant fell off to the " + directionFallen);
- }
- private static void displayGrid(int[][] grid, int size) {
- for (int i = 0; i < size; i++) {
- for (int j = 0; j < size; j++) {
- System.out.print(grid[i][j]);
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment