This question relates to my 2D array display, which currently looks something like this.
A B C D
1: 0 0 0 0
2: 0 0 0 0
3: 0 0 0 0
I am trying to get location (0,0) to change to the number 1 as this will be the start of my count.
However it won't change and remains as a zero, here is my code.
int[][] chessBoard = new int[3][4];
int rowhead = 1;
TextIO.put(" ");
for (int col = 0; col < chessBoard[0].length; col++)
TextIO.putf("%4s",((char) ('A' + col)));
TextIO.putln();
for (int [] row:chessBoard){
TextIO.put(rowhead++ + ":");
for (int griddisplay:row)
TextIO.putf("%4d", griddisplay);
TextIO.putln();
chessBoard [0][0] = 1;
Now this keeps my coordinates (o, o) displaying a zero, however if I change this
chessBoard [0][0] = 1;
to this
chessBoard [1][0] = 1;
Then the grid does change accordingly to
A B C D
1: 0 0 0 0
2: 1 0 0 0
3: 0 0 0 0
Where am I going wrong?
Your code works fine, I just added a few methods and altered output
public class Chessboard
{
public static void main(String[] args)
{
int[][] chessBoard = new int[3][4];
print(chessBoard);
chessBoard [0][0] = 1;
print(chessBoard);
chessBoard [1][0] = 1;
print(chessBoard);
clear(chessBoard);
print(chessBoard);
}
public static void print(int[][] chessBoard)
{
int rowhead = 1;
System.out.print("\n ");
for (int col = 0; col < chessBoard[0].length; col++)
System.out.printf("%4s",((char) ('A' + col)));
System.out.println();
for (int[] row : chessBoard)
{
System.out.print(rowhead++ + ":");
for (int griddisplay : row)
System.out.printf("%4d", griddisplay);
System.out.println();
}
System.out.println();
}
public static void clear(int[][] chessBoard)
{
for (int row = 0; row < chessBoard.length; row++)
for(int col = 0; col < chessBoard[row].length; col++)
chessBoard[row][col] = 0;
}
}
Move your chessBoard [0][0] = 1; right below the TextIO.put(rowhead++ + ":");:
int[][] chessBoard = new int[3][4];
int rowhead = 1;
TextIO.put(" ");
for (int col = 0; col < chessBoard[0].length; col++)
TextIO.putf("%4s",((char) ('A' + col)));
TextIO.putln();
for (int [] row:chessBoard) {
TextIO.put(rowhead++ + ":");
chessBoard[2][3] = 1;
for (int griddisplay : row){
TextIO.putf("%4d", griddisplay);
}
TextIO.putln();
}
and it will work propertly =).
You appear to have some formatting issues but from the gist of it:
You are constructing your chess board as an array [3][4] and by the looks of it that is 3 'rows' and 4 'columns' so your first index is your row number and second is column number.
You loop through the first 'row' to get the length (4) so are outputting 4 columns - correctly I am assuming.
You then move to printing the chessboard (though I don't see the matching curly brace }). First you loop across rows and then across columns.
For example:
for (int [] row:chessBoard) {
TextIO.put(rowhead++ + ":");
for (int griddisplay:row)
TextIO.putf("%4d", griddisplay);
TextIO.putln();
chessBoard [0][0] = 1;
}
If this is your code, the first loop starts processing the first row. It loops through the columns for the first row, THEN sets [0][0] to be 1... but you've already printed that so it won't be shown. If you replace it with [1][0], it actually sets that BEFORE printing the second row so correctly shows the value.
As a final tip, the curly braces specify the scope of the for loop. If you omit the braces, the loop only runs the statement immediately after it. A habit a lot of programmers get in to is to always explicitly use braces to avoid easy mistakes.
Related
The task is following:
a square matrix A of order M is given. Starting with the element A0,0 and moving clockwise, you should output all its elements in a spiral: the first row, the last column, the last row in reverse order, the first column in reverse order, the remaining elements of the second row and so on.
public class Pres10Task8 {
public static void main(String[] args) {
int m =4;
int [][] a=new int [m][m];
Random rand = new Random();
for(int i =0;i<a.length;i++){
for(int j =0;j<a[i].length;j++){
a[i][j]=rand.nextInt(100);
System.out.print(a[i][j]+" ");
}
System.out.println();
}
for(int k=0;k<m/2+1;k++){
for(int j = k; j<m+1-k;j++){
System.out.println(a[k][j]);
}
int j =m+1-k;
for(int i=k+1;i<m+1-k;i++){
System.out.println(a[i][j]);
}
for(int j=m-k;j>k;j--){
j =k ;
System.out.println(a[i][j]);
}
for(int i =m-k;i>k+1;i-- ){
i =m+1-k;
System.out.println(a[i][j]);
}
}
}
}
Would you be so kind to look through my code and say what is wrong with it? How should I rewrite my code in order to get the right output?
You couldn't use a variable in your loop already exist before your method :
int j = m + 1 - k;
// ^--------------------------------------Already exist
for (int i = k + 1; i < m + 1 - k; i++) {
System.out.println(a[i][j]);
}
for (int j = m - k; j > k; j--) {
// ^---------You can't declare a variable already exist,
//you can just use it or initialize it
So instead use this without int j:
for (j = m - k; j > k; j--) {
Second
System.out.println(a[i][j]);
// ^-----The i is not exist so you have to
//create it and inisialize it so you can use it
You have made many mistakes as YCF_L mentioned in the answer and also After solving few of them I was still getting other errors. You can solve this problem by a simple logic that Divide Square Matrix into smaller squares and then follow the same pattern to print each of the squares.
For Example,
Suppose I have a matrix of order 5 then we can have 3 squares here for distinct dimensions.
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
Here each number represents that to which square the element belongs.So all outer elements belongs to first square then the next layer's elements belongs to second square and so on.
Now you have made your problem easier by dividing it into smaller sub-problems which can be solved in same way. Now you need to make logic of print the elements of each of the squares.
So for this, Consider the most outer square.
1 1 1 1 1 1 2 3 4 5
1 1 Thier Printing Order 16 6
1 1 ================> 15 7
1 1 14 8
1 1 1 1 1 13 12 11 10 9
So notice that we start from the first element and move into the same row into the right direction.
Then move in same column into down direction.
Then again in the same row in left direction.
At last in the same column but in the up direction.
After printing the outer square move to the inner square and do the same for each of the squares.
Code for the same:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
int m =4;
int [][] a=new int [m][m];
Random rand = new Random();
for(int i =0;i<a.length;i++){
for(int j =0;j<a[i].length;j++){
a[i][j]=rand.nextInt(100);
System.out.print(a[i][j]+" ");
}
System.out.println();
}
int squares=m/2; //Calculating total number of squares
for(int i=0;i<squares;i++)
{
int low=i; //Set the dimension of the square
int high=m-i-1;
for(int j=low;j<=high;j++) //First Row --> (Right Direction)
System.out.println(a[low][j]);
for(int j=low+1;j<=high;j++) //Last Column --> (Down Direction)
System.out.println(a[j][high]);
for(int j=high-1;j>=low;j--) //Last Row --> (Left Direction)
System.out.println(a[high][j]);
for(int j=high-1;j>low;j--) //First Column --> (Up Direction)
System.out.println(a[j][low]);
}
if(m%2==1) //If Matrix is of odd order then print the middle element.
System.out.println(a[mid][mid]);
}
}
Why you use jagged array [][] instead of 2-dimensional [,] ???
May give a simple sample:
public void CountDiag(int size)
{
// initialize straight order
int[,] ar2 = new int[size, size];
int count = 0;
// initialize spiral way
int y = 0;
int x = 0;
int top = 0;
int bot = ar2.GetLength(0)-1;
int left = 0;
int right = ar2.GetLength(1)-1;
do
{
//topleft to right
for (; y < right; y++)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
right--;
//topright to bottom
for (; x < bot; x++)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
top++;
//botright to left
for (; y > left; y--)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
left++;
//botleft to top
for (; x > top; x--)
{
ar2[x, y] = count + 1;
count++;
}
ar2[x, y] = count + 1;
bot--;
} while (count < ar2.Length-1);
}
AND you print it out like this:
public void PrintArray(int[,] array)
{
int n = (array.GetLength(0) * array.GetLength(1) - 1).ToString().Length + 1; // for padding
for (int i = 0; i < array.GetLength(0); i++) // 0 - length rows
{
for (int j = 0; j < array.GetLength(1); j++) // 1 length columns
{
Console.Write(array[i, j].ToString().PadLeft(n, ' '));
}
Console.WriteLine();
}
Console.ReadLine();
}
I am trying to make a border around an empty matrix that is ascending and descending. I already have the top and left side which are ascending from 0 to 4, but I cannot get the right side and bottom side to go from 4 to 0. Here is the code of my for loops. I have tried about every variation to get it to work, but it either gives me an index out of bounds exception or just shows up as zeroes instead. I would greatly appreciate any feedback.
private static void fillBorder( int[][] matrix )
{
for (int r=0; r<matrix.length; ++r) // left side
{
matrix[r][0] = r;
}
for (int j=0 ; j<matrix.length; ++j) // top
{
matrix[0][j] = j;
}
for (int m=matrix.length; m>0; --m) // bottom
{
matrix[4][m] = m;
}
for (int s=matrix.length; s>0; --s) // right side
{
matrix[s][4] = s;
}
}
Here is also a picture of what the output is supposed to look like to give you a better idea of what it's supposed to be. picture of output
I think you can do this with a single for loop:
for (int i=0; i < matrix.length; ++i) {
matrix[0][i] = i;
matrix[i][0] = i;
matrix[matrix.length-1][matrix.length-1-i] = i;
matrix[matrix.length-1-i][matrix.length-1] = i;
}
This assumes that the matrix in fact is square (i.e. has the same number of rows and columns). If not, then my code would have to change, but then again so would your problem statement.
for (int r=0; r < matrix.length; ++r) {
for (int c=0; c < matrix.length; ++c) {
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
Output:
0 1 2 3 4
1 0 0 0 3
2 0 0 0 2
3 0 0 0 1
4 3 2 1 0
For your rows, you should be using matrix[0].length. The other thing is you should use the matrix dimension rather than hardcoding 4 into the code
private static void fillBorder( int[][] matrix )
{
for (int r=0; r<matrix.length; ++r) // left side
{
matrix[r][0] = r;
}
for (int j=0 ; j<matrix[0].length; ++j) // top
{
matrix[0][j] = j;
}
for (int m=matrix[0].length; m>0; --m) // bottom
{
matrix[matrix.length - 1][m] = m;
}
for (int s=matrix.length; s>0; --s) // right side
{
matrix[s][matrix[0].length - 1] = s;
}
}
I would like to first apologize if my question is worded badly. I have an exam tmmrw and the prof gave a sample final exam for us to practice with. He unfortunately isn't responding with the solutions on the forum so I am trying to provide solutions on there. I seem to be stuck on this question. I have to write a method that accepts and NxM array filled with integer values as a parameter. The method is to return an (N+1)x(M+1) array which contains the contents of the original array in the first N rows and M columns plus a count of items greater than or equal to zero in each row/column at the end of that row/column and put the value -1 in the bottom right corner. for example.
1 -2 0 returns 1 -2 0 2
3 -4 -5 3 -4 -5 1
2 0 1 -1
I seem to be able to copy the array yet I am puzzled as to how I can enter the values in the outer parts of the new array. Here is what I have so far.
public static void main(String[] args) {
int[][] arr = { { 1, -2, 0 }, { 3, -4, -5 } };
int[][] newMatrix = processing2D(arr);
printArray(newMatrix);
}
//Method where I am having problems
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length][arr[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
matrix[row][col] = arr[row][col];
}
}
// assign the corner -1 here
return matrix;
}
public static void printArray(int[][] list) {
for (int row = 0; row < list.length; row++) {
for (int col = 0; col <= list.length; col++) {
System.out.print(list[row][col] + " ");
}
System.out.println();
}
}
First off you are initializing the new array wrong it should be
int[][] matrix = new int[arr.length+1][arr[0].length+1];
You don't want it to be the same length you want it to be the length +1. Also in your for loops you want to go by the length of arr not matrix since thats what you're taking from. While putting the values into the new N+1xM+1 array, increment the value of the corresponding last element in that row and column by 1 if it is >=0.
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(arr[row][col]>=0){
matrix[row][matrix[row].length-1] = matrix[row][matrix[row].length-1] + 1;
matrix[matrix.length-1][col]= matrix[matrix.length-1][col] + 1;
}
matrix[row][col] = arr[row][col];
}
After putting all the values back into the new N+1xM+1 array you should now take the values in the n sized and m sized arrays and put them into the corresponding slot in the N+1xM+1 array. After that just put the -1 in the bottom right slow manually.
matrix[matrix.length-1][matrix[0].length-1]=-1;
In your process2D method start off by creating an array with the correct size which has 1 more row and 1 more column than the original:
int[][] matrix = new int[arr.length+1][arr[0].length+1];
Then to populate the matrix array you do like you were doing before, but you need to take care not to reference an index of the arr array that is out of bounds. Because your matrix index is bigger than arr. If you are populating the new indexes then you can just use random numbers.
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
So here is the full method process2D:
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length+1][arr[0].length+1];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
}
}
// assign the corner -1 here
return matrix;
}
I am trying to write a code that fills in the 2 main diagonals in an NxN matrix, for example:
if N=5 (which is entered through command line), we would have a 5x5 matrix filled with zeros and the diagonals would have 2s filled in, like:
2 0 0 0 2
0 2 0 2 0
0 0 2 0 0
0 2 0 2 0
2 0 0 0 2
I wrote a code for an all-zero table, but i can't figure our how to fill in the diagonals.
Looking at the case of 5x5 i would have to fill in the matrix at the following indices:
#1 (0,0) (0,n-1)
#2 (1,1) (1,n-2)
#3 (2,2) (2,n-3)
#4 (3,1) (3, n-2)
#5 (4,0) (4,n-1)
However, since N can be any number, i assume that first i have to find the middle row, after which i have to decrement the indices in the reverse order.
I am learning Java for 2 weeks only and this one is pretty hard.
My code for a zero-filled table is this:
public static void main (String[] args){
int n = Integer.parseInt(args[0]);
System.out.println(n);
int[][] table = new int[n][];
for (int i = 0; i < n; i++) {
table[i] = new int[i + 1];
for (int j = 0; j <= i; j++) {
table[i][j] = (0);
}
} System.out.print(Arrays.deepToString(table));
}
Obviously, this is very far from what i need to achieve, and i am not sure if it's entirely right. I would really appreciate some help.
Try this,
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args){
int n = 5;
System.out.println(n);
int[][] table = new int[n][];
for (int i = 0; i < n; i++) {
table[i] = new int[n];
for (int j = 0; j < n; j++) {
if(i==j || n-i == j+1){
table[i][j] = table[i][n-i-1] = 2;
}
else{
table[i][j] = 0;
}
System.out.print(table[i][j]);
}
System.out.println();
}
}
}
To fill one diagonal, we just have to count from i==0 to i==size-1 and fill in (i,i) each time.
for(int i=0; i<size; i++) {
table[i][i] = 2;
}
The other diagonal is only slightly harder:
for(int i=0; i<size; i++) {
table[i][some calculation involving i and size] = 2;
}
You should be able to work out what the calculation is.
You can do it in two loops - but you can also combine filling both diagonals into one loop.
You could also amend your nested loops that create the array, to handle the cells on the diagonals as you encounter them there.
#inside the loop
if( a condition indicating that the cell is on a diagonal) {
table[i][j] = 2;
} else {
table[i][j] = 0;
}
Write down the coordinates of the cells on the diagonals, and you should quickly see what the condition is.
I'm trying to print square by using nested for loop. It is needed square to look like sequence numbers. Actually I didn't receive square. Please see attached file to understand my goal- red border.
public class Day22022014 {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
for(int row=1; row<=n; row++){
System.out.printf("%d %n", row);
for(int col=row; col<2*n; col++){
System.out.printf("%d ", col);
}
}}}
You have a few errors there. The first printf is incorrectly outputting a number, you only need to make a new line, all numbers should be outputted inside the inner for.
Secondly, the condition col < 2 * n is wrong, you only want to go up to row + n - 1.
I suggest you go through this and try to understand, how do the indices row and col change in each iteration.
for(int row = 1; row <= n; row++){
for(int col = row; col <= (row + n - 1); col++){
System.out.printf("%d ", col);
}
System.out.println();
}