Printing with two for loops - java

I'm trying to print out X and Y coordinates from two separate arrays using two for loops. Each point is either decremented or incremented. The grid space is 500x500. I should basically end up with the output displaying a line of asterisks going either up or down. The arrays are populated correctly, and the X and Y coords are decremented or incremented correctly. I can't get it to work....
The populate board method fills the b1 array with the point's x member and the b2 array with the point's y member.
populateBoard(b1,b2,point);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(i == b2[i] && j == b1[j])
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
What is my logic error in the above code? Yet when I use this it works (only for one point obviously).
if(i == b2[0] && j == b1[0])

The logic in your above code is the assumption that in the i/j-th iteration of your double loop you'll be encountering a point whose x/y value happens to be exactly equal to i/j.
The working solution is as follows
private static void populateBoard(int[] xs, int[] ys, int w, int h)
{
Set<Point> points = new HashSet<>();
for(int i=0;i<xs.length;i++)
{
int x = xs[i];
int y = ys[i];
points.add(new Point(x,y));
}
for(int i=0;i<h;i++)
{
for(int j=0;j<w;j++)
{
Point p = new Point(j,i);
if(points.contains(p))
System.out.print("■");
else
System.out.print(".");
}
System.out.print("\n");
}
}
When I run this code against a trivial example:
int[] xs = {1,4,1,4,1,2,3,4};
int[] ys = {1,1,3,3,4,4,4,4};
populateBoard(xs, ys, 6, 6);
it produces the following (correct) output:
......
.■..■.
......
.■..■.
.■■■■.
......

Try this.
boolean[][] temp = new boolean[matrix.length][matrix.length];
for (int i = 0; i < b1.length; ++i)
temp[b2[i]][b1[i]] = true;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++)
System.out.print(temp[i][j] ? "*" : " ");
System.out.println();
}

Related

Copy coordinates of one 2D array to another array

I have a 2D array freeSpace[][] that represents x, y coordinates. If the space is "not free" then I have it marked as 77, other 1.
I want to put all the elements marked as 77 into it's own array, with those particular array coordinates. I think it should be simple, but I just can't get the syntax correct.
Here is my code:
for (int v = 0; v < info.getScene().getHeight(); v++) {
for (int h = 0; h < info.getScene().getWidth(); h++) {
//System.out.print(freeSpace[h][v] != 77 ? "." : "#");
if (freeSpace[h][v] == 77) {
blockedCoordinates = new int[][]{{h, v}};
}
}
System.out.println();
}
I have already declared the blockedCoordinates[][] array.
Most of my attempts have lead to an empty array.
You are doing some error while copying your data, here is why:
// assuming following definition
int[][] blockedCoordinate = new int[][]{};
for (int v = 0; v < info.getScene().getHeight(); v++) {
for (int h = 0; h < info.getScene().getWidth(); h++) {
//System.out.print(freeSpace[h][v] != 77 ? "." : "#");
if (freeSpace[h][v] == 77) {
// Make a copy
int[][] copyBlockedCoordinate = blockedCoordinates;
// extend the array length by 1
blockedCoordinates = new int[copyBlockedCoordinate.length + 1][2];
for (int i = 0; i < copyBlockedCoordinate.length; i++) {
for (int j = 0; j < copyBlockedCoordinate[i].length; j++) {
blockedCoordiante[i][j] = copyBlockedCoordinate[i][j];
}
}
// add new array at new or last index position in blockedCoordinate array
blockedCoordinate[copyBlockedCoordinate.length] = {h, v};
}
}
// Make sure you write what you want to the console here to debug :)
System.out.println();
}

How do I read through a 2D array without searching out of bounds?

I have a 2D array acting as a grid.
int grid[][] = new int[5][5];
How do I search through the grid sequentially as in (0,0), (1,0), (2,0), (3,0), (4,0) then (0,1), (1,1), (2,1) ... without getting any array out of bounds exceptions.
I'm new to programming and I just can't get my head around how to do this.
You know your lengths, now use a for loop to circle through the array.
for (int i = 0;i<5;i++){
for (int j = 0;i<5;i++){
int myInt = grid[i][j];
//do something with my int
}
}
To get the lengths at runtime you could do
int lengthX = grid.length; //length of first array
int lengthY = 0;
if ( lengthX>0){ //this avoids an IndexOutOFBoundsException if you don't know if the array is already initialized yet.
lengthY = grid[0].length; //length of "nested" array
}
and then do the for loop with lengthX and lengthY.
You will need two nested loop in order to access the two dimensions of your array:
int grid[][] = new int[5][5];
for(int i = 0; i < 5; i++ ) {
for(int j = 0; j < 5; j++ ) {
int value = grid[i][j];
}
}
Use 2 forloops like the following example:
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
System.out.println(grid[i][j]);
}
}
Also i would suggest that when initializing an array to write it like this:
int[][] grid = new int[5][5]; // note the double brackets are after int and not grid
Try this:
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.println(grid[j][i]);
}
}
This code (like the other answers) uses two for loops.
It does however add some handling of edge-cases
static int[] find(int[][] mtx, int valueToLookFor)
{
int rows = mtx.length;
if(rows == 0)
return new int[]{-1,-1};
int cols = mtx[0].length;
if(cols == 0)
return new int[]{-1, -1};
for(int r=0;r<rows;r++)
{
for(int c=0;c<cols;c++)
{
if(mtx[r][c] == valueToLookFor)
return new int[]{r,c};
}
}
return new int[]{-1,-1};
}

Where are my arrays are out of bounds?

I have looked at other questions about out of bounds error and understood them, couldn't understand the fault in this code.
Question: A JAVA program that will read a boolean matrix corresponding to a relation R and output whether R is Reflexive, Symmetric, Anti-Symmetric and/or Transitive. Input to the program will be the size n of an n x n boolean matrix followed by the matrix elements.
The program must output a reason in the case that an input relation fails to have a certain property.
Solution: I have provided the code, it throws the "java.lang.ArrayIndexOutOfBoundsException" error at main and line 65. I can't see how my arrays are out of bounds
ERROR: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at XYZ.BooleanMatrix.main(BooleanMatrix.java:65)
Code:
package XYZ;
import edu.princeton.cs.algs4.*;
public class BooleanMatrix {
// read matrix from standard input
public static boolean[][] read() {
int n = StdIn.readInt();
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (StdIn.readInt() != 0)
a[i][j] = true;
}
}
return a;
}
// print matrix to standard output
public static void print(boolean[][] a) {
int n = a.length;
StdOut.println(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j])
StdOut.print("1 ");
else
StdOut.print("0 ");
}
StdOut.println();
}
}
// random n-by-n matrix, where each entry is true with probability p
public static boolean[][] random(int n, double p) {
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = StdRandom.bernoulli(p);
}
}
return a;
}
// display the matrix using standard draw
// depending on variable which, plot true or false entries in foreground
// color
public static void show(boolean[][] a, boolean which) {
int n = a.length;
StdDraw.setXscale(0, n - 1);
StdDraw.setYscale(0, n - 1);
double r = 0.5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == which) {
StdDraw.filledSquare(j, n - i - 1, r);
}
}
}
}
// test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]); //LINE 65
double p = Double.parseDouble(args[1]);
boolean[][] a = random(n, p);
print(a);
show(a, true);
}}
I don´t know the exact working of StdDraw.setXscale(0, n - 1); but i think it creates a table with n-1 rows. so if you try to fill it with n rows there will be an out of bounds error. try using this in line 47:
StdDraw.setXscale(0, n);
StdDraw.setYscale(0, n);
As stated in the comments below your post: if you don´t enter any arguments when calling the program you´ll get an out of bounds exception because the program expects arguments in the aray and there aren´t any.
To provide arguments open command line and call /java yourcompiledjavafile arg[0] arg[1]

I have a 2D MATRIX of chars, and having trouble searching the matrix Spirally

I start from the left-bottom and proceeding in clockwise direction till no chars are left. here is my code.
import java.io.*;
import java.util.*;
public class Solution {
static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
char[][] matrix = new char[n][m];
char[] temp = new char[n*m];
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
matrix[r][col] = sc.next().charAt(col);
}
}
int k=0, l = 0;
while(k < n && l < m){
if(l<m){
for(int i = n-1;i>=k;i--){
temp[count] = matrix[i][l];
count++;
}
l++;
}
for(int i = l;i<m;i++){
temp[count] = matrix[k][i];
count++;
}
k++;
for(int i = k;i<n;i++){
temp[count] = matrix[i][m-1];
count++;
}
m--;
if(k < n){
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
}
n--;
}
}
String code = String.valueOf(temp);
String[] dec = code.split("#");
//System.out.println(dec);
int count2 = dec.length;
System.out.println(count2);
}
}
So can anyone point out where I am going wrong? I start at left bottom, climb up, go right , then go down, go left and continue till no elements left.
There are two issues: incorrect input and missing counter increment.
Incorrect input:
for(int r=0;r<n;r++){
for(int col=0;col<m;col++){
// The following reads a new line each time a new character is needed
matrix[r][col] = sc.next().charAt(col);
}
}
This could be fixed either by lifting sc.next() from the inner loop:
for (int r = 0; r < n; r++) {
String line = sc.next();
for (int col = 0; col < m; col++) {
matrix[r][col] = line.charAt(col);
}
}
Or (preferable) removing inner loop completely:
for (int r = 0; r < n; r++) {
matrix[r] = sc.next().toCharArray();
}
Missing increment (lower part of the spiral):
for(int i = m-1;i>=l;i--){
temp[count] = matrix[n-1][i];
// Counter increment is missing. Add
// counter++;
}
In general, is is better to use StringBuilder for gradual construction of the string. In you case it will look as following:
StringBuilder temp = new StringBuilder();
<...>
temp.append(matrix[n-1][i]);
<...>
String code = temp.toString();
In this code you don't have to estimate possible string size nor manually track current insert position.
starting left bottom in the matrix is
matrix[0][m];
going up the hill will be made by decreasing m to a point where you already had a char inserted.
i would use 4 for loops inside a while loop like is presented:
while (usedRow < (int)0.5*n && usedCol < (int)0.5*m)
{
//usedRow and usedCol start with the value of 0 and will be raised
// by the end of the loop
int i, j;
for (i = m - usedCol; i<=(m-usedCol); i++)
{
matrix[usedRow][m-i] = sc.next().charAt(0);
}
for (j = usedRow; j <= (n-usedRow); j++)
{
matrix[n + j][usedCol] = sc.next.charAt(0);
}
for (i = usedCol; i <= (m-usedCol); i++)
{
matrix [n - usedRow][m+i] = sc.next().chatAt(0);
}
for ( j = n - usedRow; j <= (n - usedRow); j++)
{
matrix[n - j][m - usedCol] = sc.next().charAt(0);
}
usedRow++;
usedCol++;
}
this way you go clockwise and keep the loop within the rows and cols that are not in use.
hope that it helped you in a way.

Raising a matrix to the power method JAVA

I am having a really hard time creating a method to raise a matrix to the power. I tried using this
public static int powerMethod(int matrix, int power) {
int temp = matrix ;
for (int i = power; i == 1; i--)
temp = temp * matrix ;
return temp ;
but the return is WAYYY off. Only the first (1,1) matrix element is on point.
I tried using that method in a main like so
// Multiplying matrices
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
for (l = 0; l < row; l++)
{
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
// Solving Power of matrix
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
Where "power", "row", and "column" is an int that the user enters.
Any ideas how I can do this??
Thanks!!!
You have a lot of issues here.
First, your matrix squaring algorithm has a (common) error. You have:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
for (l = 0; l < row; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
However, you need to store the result in a temporary second matrix, because when you do matrix[i][j] = sum, it replaces the value at that position with the output, then later results end up being incorrect. Also I suggest initializing sum to 0 first, since it appears you declare it outside of this loop, and initializing it first protects you against any arbitrary value sum may have before going into the loop. Furthermore, it is not immediately clear what you mean by row and column -- make sure you are iterating over the entire matrix. E.g.:
int temp[][] = new int[matrix.length];
for (i = 0; i < matrix.length; i++) {
temp[i] = new int[matrix[i].length];
for (j = 0; j < matrix[i].length; j++) {
sum = 0 ;
for (l = 0; l < matrix.length; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
temp[i][j] = sum ;
}
}
// the result is now in 'temp', you could do this if you wanted:
matrix = temp;
Note that matrix.length and matrix[i].length are fairly interchangeable above if the matrix is square (which it must be, in order to be multiplied by itself).
Secondly, your multiplication squares a matrix. This means if you repeatedly apply it, you keep squaring the matrix every time, which means you will only be able to compute powers that are themselves powers of two.
Your third issue is your final bit doesn't make much sense:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
It's not immediately clear what you are trying to do here. The final part seems to be trying to raise individual elements to a certain power. But this is not the same as raising a matrix to a power.
What you need to do is define a proper matrix multiplication method that can multiply two arbitrary matrices, e.g.:
int[][] multiplyMatrices (int[][] a, int[][] b) {
// compute and return a x b, similar to your existing multiplication
// algorithm, and of course taking into account the comments about
// the 'temp' output matrix above
}
Then computing a power becomes straightforward:
int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; ++ n)
result = multiplyMatrices(result, a);
return result;
}
Why not just use Math.pow?
import java.lang.Math;
Then you just have to do
matrixFinal[power][i][j] = (int) Math.pow(matrix[i][j],power); //might have to cast this to an int

Categories

Resources