Hyphonz

Untitled

May 19th, 2024
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | Source Code | 0 0
  1. import java.util.Random;
  2.  
  3. public class AntWalk {
  4.     public static void main(String[] args) {
  5.         int gridSize = 9;
  6.         int[][] grid = new int[gridSize][gridSize];
  7.         int x = 4;
  8.         int y = 4;
  9.         int moves = 0;
  10.         String directionFallen = "";
  11.        
  12.         while (x > 0 && x < 8 && y > 0 && y < 8)  {
  13.             grid[x][y]++;
  14.            
  15.             int move = (int) (Math.random() * 4);
  16.            
  17.             if (move == 0) {
  18.                 x--;
  19.             } else if (move == 1) {
  20.                 x++;
  21.             } else if (move == 2) {
  22.                 y--;
  23.             } else if (move == 3) {
  24.                 y++;
  25.             }
  26.            
  27.             moves++;
  28.         }
  29.  
  30.         if (x == 0) {
  31.             directionFallen = "NORTH";
  32.         } else if (x == 8) {
  33.             directionFallen = "SOUTH";
  34.         } else if (y == 0) {
  35.             directionFallen = "WEST";
  36.         } else if (y == 8) {
  37.             directionFallen = "EAST";
  38.         }
  39.         displayGrid(grid, gridSize);
  40.         System.out.println("Moves: " + moves);
  41.         System.out.println("The ant fell off to the " + directionFallen);
  42.     }
  43.  
  44.     private static void displayGrid(int[][] grid, int size) {
  45.         for (int i = 0; i < size; i++) {
  46.             for (int j = 0; j < size; j++) {
  47.                 System.out.print(grid[i][j]);
  48.             }
  49.             System.out.println();
  50.         }
  51.     }
  52.    
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment