-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGridMove.java
More file actions
72 lines (63 loc) · 2.38 KB
/
GridMove.java
File metadata and controls
72 lines (63 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Scanner;
public class GridMove {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
char[][] grid = createGrid(sc);
boolean cont = true;
while (cont){
grid = changeLoc(grid, sc);
displayGrid(grid);
}
}
//Create and return an int[][] of user specified size
//With all "Empty" spaces initialized to - and the top left space initialized to *
public static char[][] createGrid(Scanner sc){
System.out.print("What size grid do you want to make (r c)? ");
int numRows = sc.nextInt();
int numCols = sc.nextInt();
char[][] grid = new char[numRows][numCols];
for (int i = 0; i < grid.length; i++){
for (int j = 0; j < grid[0].length; j++){
grid[i][j] = '-';
}
}
grid[0][0] = '*';
return grid;
}
//Ask the user for a change in row and column, and adjust the location of * accordingly
//If an edge is reached, assume it wraps around to the other side
public static char[][] changeLoc(char[][] grid, Scanner sc){
System.out.print("How much do you want to move the row and col? ");
int numRowsToMove = sc.nextInt();
int numColsToMove = sc.nextInt();
int[] currLoc = getCurrLoc(grid);
grid[currLoc[0]][currLoc[1]] = '-';
int newRow = (currLoc[0] + numRowsToMove) % grid.length;
int newCol = (currLoc[1] + numColsToMove) % grid[0].length;
if (newRow < 0)
newRow = grid.length + newRow;
if (newCol < 0)
newCol = grid[0].length + newCol;
grid[newRow][newCol] = '*';
return grid;
}
public static int[] getCurrLoc(char[][] grid){
for (int i = 0; i < grid.length; i++){
for (int j = 0; j < grid[0].length; j++){
if (grid[i][j] == '*'){
return new int[] {i, j};
}
}
}
return new int[] {-1, -1};
}
//Displays the array representing the grid with a single space between each column
public static void displayGrid(char[][] grid){
for (char[] row : grid){
for (char curr : row){
System.out.print(curr);
}
System.out.println();
}
}
}