How to print a 2D array in java - java

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");
}

Related

How do I print out factors of an input using loops?

Here is my mess of a code. I have to write a program that inputs a positive integer greater than 3. Validate that the integer is in fact greater than 3. Then print all possible pairs of positive integers great than whose product is less than or equal to the number entered.
ex. If 24 is the input.
It would print:
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8....
9 = 3 x 3
12 = 3 x 4..
24 = 3 x 8...
all the way to
24 = 4 x 6
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int j = 0;
int k = 2;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
while (product < i) {
if (product == i) { j++; k = 2;
for (j = 2; product < i; k++) {
product = j * k;
System.out.println(product + " = " + j + " x " + k);
if (product == i) { j++; k = 2;
}
}
}
}
}
}
public class Factors {
public static void main(String[] args) {
// Define Variables
Scanner input = new Scanner(System.in);
int i = 0;
int product = 0;
// Ask for input/loop
while (i < 3) {
System.out.println("Please enter an integer greater than 3");
i = input.nextInt();
}
for (int j = 2; j < i / 2; j++) {
for (int k = 2; k < i / 2; k++) {
if (j <= k && j * k <= i)
System.out.println(j * k + " = " + j + "*" + k);
}
}
// while (product < i) {
// if (product == i) {
// j++;
// k = 2;
// for (j = 2; product < i; k++) {
// product = j * k;
// System.out.println(product + " = " + j + " x " + k);
// if (product == i) {
// j++;
// k = 2;
// }
// }
// }
// }
}
}

Running sum of an ArrayList with 2 possible operations

I am trying to create a program insert two possible operations (* and +) in between inputed numbers and keep track of the total. The program simply reads from left to right so therefor do not apply BEDMAS
For instance if I inputed: 1 2 3
The output would be 1 + 2 + 3 -> Sum = 6
Or output would be 1 + 2 * 3 -> Sum = 9
Or output would be 1 * 2 + 3 -> Sum = 5
Etc
I am having difficulty because my program continues to try to numbers.remove() from an empty ArrayList(numbers).
public static void calculate(ArrayList<Integer> numbers, int target){
ArrayList<Integer> temp_array = new ArrayList<Integer>(numbers);
int sum = 0;
int n = (numbers.size() - 1);
System.out.println("This is where we calcutale L");
for (int i = 0; i < Math.pow(2, n); i++) {
String bin = Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
char[] chars = bin.toCharArray();
char[] charArray = new char[n];
while(charArrayCount < Math.pow(2,n)){
for (int j = 0; j < chars.length; j++) {
charArray[j] = chars[j] == '0' ? '+' : '*';
}
for(char c : charArray){
int current = numbers.get(0);
if (c == '+'){
sum = sum + current;
}
numbers.remove(0);
System.out.println(sum);
}
numbers = temp_array;
sum = 0;
}
}
}

Cannot figure out how to get Pascal Triangle In Java

I am supposed to get this series
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
NOTE:The spaces mentioned have to be present it should have the exact same output as i have mentioned
I tried this:
class pattern_19
{
static void main()
{
int i,j;
int s=1;
System.out.println(s);
for(i=1;i<=6;i++)
{
for(j=1;j<=i;j++)
{
s=s*11;
}
System.out.println(s);
s=1;
}
}
}
MY OUTPUT:
11
121
1331
14641
161051
1771561
This did not work any help will be appreciated
Your code would not compile because your main method was not defined correctly. This is one thing but not the main reason why you were getting an unexpected output.
Your s variable represent one integer on each line.
What you'll have to do from there is split your int and print each one of the digits seperately.
Here is a correction, I used an enhanced loop and a charArray to print the digits seperately but there are other ways to achieve this of course (using a loop and integer division works also or modify the way you find s).
Solution
public static void main(String[] args) {
int i, j;
int s = 1;
System.out.println(s + " ");
for (i = 1; i <= 6; i++) {
for (j = 1; j <= i; j++) {
s = s * 11;
}
for (char c : String.valueOf(s).toCharArray()) System.out.print(c + " ");
System.out.println();
s = 1;
}
}
PS : Multiplying by 11 wont work when you'll need numbers with a length of 2. I'll edit my answer right now.
Here is the algorithm solution
public static void main(String[] args) {
int rows = 6;
int[][] triangle = new int[rows][rows];
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < i; j++) {
if (j == 0) triangle[i - 1][j] = 1;
else triangle[i - 1][j] = triangle[i - 2][j - 1] + triangle[i - 2][j];
System.out.print(triangle[i - 1][j] + " ");
}
System.out.println();
}
}
I finally also got an alternative to do the same here it goes
public class PascalTriangle {
public static void main() {
int rows = 6;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Now this one is working properly .

Is there a way to combine incrementing and decrementing for loops?

int j = 0;
for (int i = 1; i < 4; i++)
{
if ((columnIndex + i) > 6 || this.isWinningCondition(columnIndex, i, j, colSlot, isRed))
{
break;
}
else
{
pieces++;
}
}
for (int i = -1; i > -4; i--)
{
if ((columnIndex + i) < 0 || this.isWinningCondition(columnIndex, i, j, colSlot, isRed))
{
break;
}
else
{
pieces++;
}
}
Basically, it is apart of a Connect4 program that searches for three in a row on the left and right side of a specific column (in this case, it is searching for horizontal wins), hence the incrementing (for the right side) and the decrementing (for the left side) for loops. Is there a way I can combine these for loops into one, so I don't have to repeat myself?
If your MaxValue ( 4 )is always the same for both for loop, you can always do :
for( int i = 1; i < 4; ++i)
{
//verify i version 1
int i2 = i * -1;
// verify i2 version 2
}
Try the mixed for loop.
for(int i = 0, j = 4; i <= 4 && j >=0; i ++, j --)
{
System.out.println(i + " " + j);
}
Output:
0 4
1 3
2 2
3 1
4 0

Creating a random colour grid with all adjacent colours different

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] + " ");
}
}
}
}

Categories