So I have the following problem set to me: Write a program that takes an integer command-line argument N, and uses two nested for loops to print an N-by-N board that alternates between 6 colours randomly separated by spaces. The colours are denoted by letters (like 'r' for RED, 'b' for BLUE). You are not allowed to have two of the same colour next to eachother.
So, I know I probably need arrays to get around this problem. I tried several methods that all came up wrong. The following is one of my recent attempts, but I am unsure as how to now go through the grid and correct it. What the code does is make every row randomized with no colour left or right the same, but the columns are not fixed.
Note that I am a first year CS student with no programming history. I am guessing the solution to this problem isnt too complex, however, I cant see a simple solution...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
this was my solution for the problem. Quite convoluted though, but the logic behind it is straightforward. Each time you assign a new colour to your 2D array, you need only check the value of the array to the top and to the left of the position where you want to assign a new colour. You can only do this after you have assigned colours to the first row of the array however so you need to create separate conditions for the first row.
public class ColourGrid {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
char[][] clrGrid = new char[N][N];
char colours[] = {'r','b','y','w','o','g'} ;
for (int counter = 0 ; counter < N; counter++) {
for (int counter2 = 0 ; counter2 < N; counter2++) {
if (counter == 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
else if (counter != 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter == 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)][counter2-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter != 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2] || clrGrid[counter][counter2] == clrGrid[counter][(counter2)-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
}
for (int counter = 0 ; counter < N; counter++) {
System.out.println("");
for (int counter2 = 0 ; counter2 < N; counter2++) {
System.out.print(clrGrid[counter][counter2] + " ");
}
}
}
}
Related
Hello so am trying to create a 2D array of int with random number of rows and columns and a random starting and ending points using java to apply the A* algorithm on it.
When i add {S} and {E} to define the tow points and print it there are numbers outside of the 2D array printed.
`Random rand = new Random();
int min = 2, max = 10;
// a random number of rows and columns
int a = (int)(Math.random() * (max - min + 1)) + min;
// the location of the starting point.
int row_start = rand.nextInt(a);
int col_start = rand.nextInt(a);
// the location of the ending point.
int row_end = rand.nextInt(a);
int col_end = rand.nextInt(a);
int [][] M = new int [a][a];
public void create() {
//empty: 0; grass: 1; sand: 2; water: 3; wall: 4.
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
M[i][j] = rand.nextInt(5);
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
System.out.print(" " +M[i][j] + "\t");
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
}
if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
}
}
System.out.print("\n");
}
}`
the output looks like this:
1 0 4 0
2 {S} 1 2 2
4 4 {E} 0 3
2 0 3 3
the 2 and 3 shouldn't appear there.
The problem is that you always print m[i][j].
What you need is to only print m[i][j] when i and j are not S and E positions. When i and j are S and E positions, print S or E. Otherwise, print m[i][j].
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
} else if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
} else {
System.out.print(" " +M[i][j] + "\t");
}
I'm trying to create an optimal path to collect as many 1's as I can but after I execute my code, I still have an arrow pointing to nothing as there are no more places to go. How would I remove the arrow at the end of the code?
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner s1 = new Scanner(System.in);
int n = s1.nextInt();
int m = s1.nextInt();
int mat[][] = new int[n][m];
for (int i = 0; i < mat.length; i++){
for (int j = 0; j < mat[0].length; j++){
mat[i][j] = s1.nextInt();
}
}
int path[][] = new int[n][m];
for (int i = 0; i < path.length; i++){
Arrays.fill(path[i], -1);
}
int maxCoins = util(0, 0, mat, path);
System.out.println("Max coins:" + maxCoins);
int row = 0, column = 0;
System.out.print("Path:");
while(row < mat.length && column < mat[0].length){
System.out.print("(" + (row + 1) + "," + (column + 1) + ")");
System.out.print("->");
if(row < n - 1 && column < m - 1){
int down = path[row + 1][column];
int right = path[row][column + 1];
if(down > right){
row += 1;
continue;
}
else if (right > down){
column += 1;
continue;
}
else{
row += 1;
continue;
}
}
if(row + 1 < n){
row += 1;
}
else{
column += 1;
}
}
}
private static int util(int row,int column,int mat[][], int path[][]){
if(row >= mat.length || column >= mat[0].length){
return 0;
}
if(path[row][column]!= -1){
return path[row][column];
}
int right = util(row, column + 1, mat,path);
int down = util(row + 1, column, mat,path);
path[row][column]=Math.max(right, down);
if(mat[row][column] == 1){
path[row][column] += 1;
}
return path[row][column];
}
}
My current input looks like:
5 6
0 0 0 0 1 0
0 1 0 1 0 0
0 0 0 1 0 1
0 0 1 0 0 1
1 0 0 0 1 0
And output is:
Max coins:5
Path:(1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(3,5)->(3,6)->(4,6)->(5,6)->
I am just trying to remove the one at the end but unsure where to insert my code:
System.out.print("->");
Cleanest way would be using a StringJoiner.
You can use it as follows
StringJoiner joiner = new StringJoiner("->");
joiner.add("a");
joiner.add("b");
System.out.println(joiner); //prints a->b - you can use toString if you want to return a joined String
You can also define a prefix and suffix for your joined String.
Or if you are familiar with Streams, there is Collectors.joining("->") available.
Three solutions that come to mind:
Add another check inside the loop, and put your sysout -> thingy after that check.
Usually code would generate some kind of list or similar data about the results and return it. It's a lot simpler to print lists, because you know the length etc.
Another common solution is to use StringBuilder and correct it before generating the output with toString()
You could just do something like this:
if (!(row == mat.length - 1 && column == mat[0].length - 1)) {
System.out.print("->");
}
Or a little cleaner:
if (arrowIsNotAtTheEnd(mat, row, column)) {
System.out.print("->");
}
// ...
private static boolean arrowIsNotAtTheEnd(int[][] mat, int row, int column) {
return !(row == mat.length - 1 && column == mat[0].length - 1);
}
For java 8 and above, the String class already has a convenient join method.
CharSequence[] path=new CharSequence[]{
"(1,1)","(2,1)","(2,2)","(2,3)","(2,4)","(3,4)","(3,5)","(3,6)","(4,6)","(5,6)"};
String output=String.join("->",path);
System.out.println(output);
//output: (1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(3,5)->(3,6)->(4,6)->(5,6)
i cant print this pattern :
1 2 3 4 *
1 0 0 * 5
1 0 * 0 5
1 * 0 0 5
* 2 3 4 5
i tried to print but only on row :
public class Pattern {
public static void main(String[] args) {
for(int j=1;j<=5;j++)
{
if(j>4) {
System.out.print("*");
}
else {
System.out.print(j);
}
}
}
}
Let's try to consider the logic of this output:
You have an NxN matrix, with rows and columns numbered 1..N.
If you're on the secondary diagonal (i.e. row+column=N+1), print a *
Else, if you're on the borders (i.e., either the row or the column is 1 or N), print the column number
Else, print a 0
Now, you just need to convert this logic to Java:
int size = 5;
for (int i = 1; i <= size; ++i) {
for (int j = 1; j <= size; ++j) {
char ch;
if (i + j == size + 1) {
ch = '*';
} else if (i == 1 || i == size || j == 1 || j == size) {
ch = (char) ('0' + j);
} else {
ch = '0';
}
System.out.print(ch + " ");
}
System.out.println();
}
Im trying to make a multi dimensional array that contains numbers and I need to find the number neighbors (down or right) that slope by num(variable)
example :
{7,5,3},{1,5,9}
the numbers 3,5,7 are sloped by 2 and the counter is 3 ( 3 numbers )
I need to find the longest slope which means that if there slope with 3 numbers and also after that slope with 6 numbers I need to return the 6 numbers..
I tried already for about 5 hours but im completely lost , here is my code until now :
private static int longestSlope (int [][] mat, int num , int i , int j , int count , int temp,int oldi,int oldj)
{
System.out.println("oldi " +oldi);
System.out.println("oldj " +oldj);
System.out.println("temp " +temp);
System.out.println("count "+count);
System.out.println("i "+i);
System.out.println("j "+j);
if(i < mat.length-1 && j < mat[0].length-1 )
{
if(j < mat[0].length-1 && mat[i][j] - num == mat[i][j+1] )
{
if(temp == 0)
{
oldj = j;
oldi = i;
}
if(j == mat[0].length-1)
{
return longestSlope(mat,num,i,j,count,temp+1,oldi,oldj);
}
else
{
temp = longestSlope(mat,num,i,j+1,count,temp+1,oldi,oldj);
}
}
else if(i < mat.length-1 && mat[i][j] - num == mat[i+1][j])
{
if(temp == 0)
{
oldj = j;
oldi = i;
}
temp = longestSlope(mat,num,i+1,j,count,temp+1,oldi,oldj);
}
else
temp = longestSlope(mat,num,i,j+1,count,temp,oldi,oldj);
}
else if(i < mat.length-1 && j == mat[0].length-1 && temp == 0)
{
temp = longestSlope(mat,num,i+1,0,count,0,oldi,oldj);
}
else if(temp > count)
{
count = temp;
System.out.println("nihnas "+count);
return longestSlope(mat,num,oldi,oldj+1,count,0,0,0);
}
else if(temp < count)
{
longestSlope(mat,num,oldi,oldj+1,count,0,0,0);
}
return 0;
}
I'm making a simple "Whack a mole" game in Java. For simplicity I have created a 10*10 box and placed 10 moles in random boxes. I want to exit the game when the user spent his 50 inputs or found all 10 moles, but there seems to be a problem in terminating the while loop even when the user attempts specified inputs.
Is it Instance variable scope problem? Why it is not working?
public class WhackAMole {
int score = 0, molesLeft = 10, attempts;
char[][] moleGrid = new char[10][10];
int numAttempts, gridDimension;
public WhackAMole(int numAttempts, int gridDimension) {
// TODO Auto-generated constructor stub
this.numAttempts = numAttempts;
this.gridDimension = gridDimension;
}
boolean place(int x, int y) {
return (x == 2 && y == 5)
|| (x == 1 && y == 3)
|| (x == 8 && y == 4)
|| (x == 5 && y == 10)
|| (x == 6 && y == 9)
|| (x == 10 && y == 7)
|| (x == 3 && y == 7)
|| (x == 2 && y == 9)
|| (x == 4 && y == 8)
|| (x == 9 && y == 5);
}
void whack(int x, int y) {
if (place(x, y)) {
if (moleGrid[x - 1][y - 1] == 'W') {
System.out.println("Already attempted! \'try other co-ordinates\' \n");
} else {
moleGrid[x - 1][y - 1] = 'W';
this.score ++;
this.molesLeft --;
}
}
}
void printGridToUser() {
System.out.println("your score is " + score + " and " + molesLeft + " moles are left. \n");
System.out.println("input x = -1 and y = -1 to quit the game! \n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
System.out.print(" " + moleGrid[i][j] + " ");
}
System.out.println("\n");
}
}
void printGrid() {
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
this.moleGrid[i][j] = '*';
}
}
}
public static void main(String[] args) {
WhackAMole game;
System.out.println("Lets play the Whack A Mole!\n");
game = new WhackAMole(50, 100);
game.printGrid();
game.printGridToUser();
Scanner scanner = new Scanner(System.in);
while ((game.numAttempts > 0) || (game.molesLeft > 0)) {
System.out.println("Enter box co-ordinate\n");
System.out.println("x co-ordinate: \n");
int x = scanner.nextInt();
System.out.println("y co-ordinate: \n");
int y = scanner.nextInt();
if (x == -1 && y == -1) {
break;
} else if ((x < 1 || y < 1) || (x > 10 || y > 10)) {
System.out.println("please enter values of x and y greater than 0 and less than 11! \n");
} else {
game.whack(x, y);
game.numAttempts--;
game.gridDimension--;
System.out.println("you can have upto " + game.numAttempts + " out of " + game.gridDimension + " boxes \n");
game.printGridToUser();
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (game.place(i+1, j+1) && game.moleGrid[i][j] != 'W'){
game.moleGrid[i][j] = 'M';
}
}
}
game.printGridToUser();
scanner.close();
System.out.println("game over!!!\n");
}
}
Your while loop is not ending because you are using || in your while loop. The || is making your loop run until the attempts allowed i.e. 50 and the right guessing i.e. finding moles correct both are met. So even when a gamer has finished his allowed attempts and hasn't guessed all the right moles positions, the loop will not end
The simple solution would be to replace || with &&
while ((game.numAttempts > 0) && (game.molesLeft > 0))
And avoid using fixed numbers i.e. 10 in your for loops instead use
for (int i = 0; i < game.gridDimension; i++) {
for (int j = 0; j < game.gridDimension; j++) {
I hope it helps
Your loop is using an or for the test function. This means both condition mist be false in order for it to stop. In your case. How its written you must exhaust the numtries and have no moles left.
Change to use && vs ||.