I need to print out the following data using a multi-dimensional array:
5 4 3 2 1
10 9 8 7 6
15 14 13 12 11
20 19 18 17 16
25 24 23 22 21
The programming language that I am using is Java. This is what I have so far:
public class Problem3 {
public static void main(String[] args) {
int[][] prob3 = new int[5][5];
for(int row = 0; row < prob3.length; row++){
System.out.println();
for(int col = 0; col < prob3[row].length; col++){
prob3[row][col] = row * 5 + col + 1;
System.out.print(prob3[row][col] + " ");
}
}
}
}
When I print this to the screen I get this:
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
I am not sure how to manipulate the numbers so they display how I want them. I really want to understand how this works. Let me know if I am doing this completely wrong. Thanks for the help in advance.
If you want iterate through the columns backward, you have to set you start value of the column-loop to the last index, check whether it's still bigger or equal to 0 and decrease col every iteration.
Like that:
int[][] prob3 = new int[5][5];
for (int row = 0; row < prob3.length; row++) {
System.out.println();
for (int col = prob3[row].length - 1; col >= 0; col--) {
prob3[row][col] = row * 5 + col + 1;
System.out.print(prob3[row][col] + " ");
}
}
Related
I'm trying to create a game like "fifteen" but instead of sliding tiles into one empty space, the empty space is removed and you have to choose individual 2x2 grids to rotate in order to get all the numbers in the correct order.
I'm stuck as to how to create a subarray from the original and have it so that the rotation of the subarray is applied to the original array.
For example:
01 02 03 04 05
06 07 09 14 10
11 12 08 13 15
16 17 18 19 20
21 22 23 24 25
in order to solve the game, you would need to choose the number 9 and and rotate {09, 14} {08, 13}
clockwise.
I'm relatively new to programming and java so any help would be greatly appreciated!
Assuming you have a two dimensional array (an array of columns) then your first index is the x coordinate and the second index the y coordinate in your grid. The x and y parameter present the position where the user has clicked on. However, this method will throw an exception if you choose a position at the border.
private static int[][] rotate2x2SubArray(int[][] grid, final int x, final int y) {
final int topLeft = grid[x][y];
final int topRight = grid[x + 1][y];
final int bottomRight = grid[x + 1][y + 1];
final int bottomLeft = grid[x][y + 1];
//topRight's new value is topLeft's old value
grid[x + 1][y] = topLeft;
//bottomRight's new value is topRight's old value
grid[x + 1][y + 1] = topRight;
//bottomLeft's new value is bottomRight's old value
grid[x][y + 1] = bottomRight;
//topLeft's new value is bottomLeft's old value
grid[x][y] = bottomLeft;
return grid;
}
This is just my approach. There a probably a hundred ways which might be faster/slower or more flexible(rotate a variable size).
Here's a proof of concept. This is the original 5 x 5 array.
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
This is the array after the 8 has been rotated counter-clockwise.
1 2 3 4 5
6 7 9 14 10
11 12 8 13 15
16 17 18 19 20
21 22 23 24 25
This is the array after the 16 has been rotated clockwise.
1 2 3 4 5
6 7 9 14 10
11 12 8 13 15
21 16 18 19 20
22 17 23 24 25
Here's the runnable code. I didn't check for the row or column being less than the last row or column. All I did was create the method to rotate the 2 x 2 subarray.
public class RotateSubArray {
public static void main(String[] args) {
RotateSubArray rotate = new RotateSubArray();
int[][] array = rotate.createArray();
System.out.println(rotate.printArray(array));
array = rotate.rotateSubArray(array, 1, 2, false);
System.out.println(rotate.printArray(array));
array = rotate.rotateSubArray(array, 3, 0, true);
System.out.println(rotate.printArray(array));
}
public int[][] createArray() {
int[][] output = new int[5][5];
int count = 1;
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < output[i].length; j++) {
output[i][j] = count++;
}
}
return output;
}
public String printArray(int[][] output) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < output.length; i++) {
for (int j = 0; j < output[i].length; j++) {
builder.append(String.format("%3d", output[i][j]));
}
builder.append(System.lineSeparator());
}
return builder.toString();
}
public int[][] rotateSubArray(int[][] array, int row, int column,
boolean clockwise) {
int temp = array[row][column];
int nextRow = row + 1;
int nextColumn = column + 1;
if (clockwise) {
array[row][column] = array[nextRow][column];
array[nextRow][column] = array[nextRow][nextColumn];
array[nextRow][nextColumn] = array[row][nextColumn];
array[row][nextColumn] = temp;
} else {
array[row][column] = array[row][nextColumn];
array[row][nextColumn] = array[nextRow][nextColumn];
array[nextRow][nextColumn] = array[nextRow][column];
array[nextRow][column] = temp;
}
return array;
}
}
I am supposed to create a program that prints out the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Here's my current code:
int n = 1,
cols = 4,
rows = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
System.out.print(n+" ");
n++;
}
System.out.println();
}
But the output is as below:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Can someone please help to figure out the solution for this one? I've tried many ways but just can't get the output right. Thanks anyway.
Java can only print in lines and not in columns. So the first line you need to print is:
1 5 9 13
In other words, every successive number is 4 greater than the number preceding it. So start your outer loop with the first number of the first row, i.e. 1 (one). Now each row contains 4 numbers, so your inner loop needs to iterate four times. See the below code:
int rows = 4;
int cols = 4;
for (int row = 1; row <= rows; row++) {
for (int col = 0; col < cols; col++) {
int number = row + (col * cols);
System.out.print(number + "\t");
}
System.out.println();
}
Running the above code produces the following:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Change inner loop to go from 0 to cols-1 rather than 1 to cols, and make it print outer loop variable + (inner loop variable * 4).
This will surely work:
for(int row=1, num; row<=4; row++)
{
num = row;
for(int col=1; col<=4; col++, num+=4)
{
System.out.print(num + " ");
}
System.out.println();
}
So the instructions are to create a matrix 10x10 and randomize values between 1~20 for each index
Then ask the user to enter 6 numbers between 1~20, and use those numbers to create
another 2x3 Matrix.
Then the program has to check if the 10x10 matrix contains the 2x3 matrix from the user.
Also i'm not allowed to use functions.
Example for input:
Enter the1 number in the matrix: 17
Enter the2 number in the matrix: 17
Enter the3 number in the matrix: 17
Enter the4 number in the matrix: 5
Enter the5 number in the matrix: 13
Enter the6 number in the matrix: 14
Output:
The random matrix:
14 14 3 18 2 10 19 10 3 3
2 17 15 16 5 17 7 17 15 10
13 1 3 9 5 4 11 9 1 8
17 14 13 9 8 1 18 3 17 18
12 17 5 14 13 4 16 14 13 4
8 12 8 19 6 5 3 3 14 18
16 16 17 9 9 10 17 3 8 5
13 8 6 17 6 17 17 7 19 5
5 14 6 15 11 11 13 17 17 17
17 13 13 18 11 4 15 5 13 14
The matrix you entered:
17 17 17
5 13 14
The random matrix contains the users matrix.
My Code so far =
int[][] big = new int[10][10];
int[][] small =new int [][] {{the1,the2,the3},{the4,the5,the6}};
for(int i = 0; i < big.length; i++ )
{
for(int j = 0; j < big[i].length; j++)
{
big[i][j]= (int)((Math.random()*20)+1);
}
}
for(int i =0; i < big.length; i++)
{
for(int j = 0; j < big.length; j++)
{
Boolean isEqual=true;
for(int k = 0; k < 2 && isEqual; k++)
{
for(int m = 0; m < 3; m++)
{
if (big[i+k][j+m]!=small[k][m])
{
isEqual=false;
break;
}
}
}
}
}
My general idea was basically running through the indexes of the big matrix while checking for equal numbers, and if one found, the routine continues, otherwise it breaks, and going to the next index in the big matrix.
Your general idea is correct and should work for the described scenario. The only issue you are having is your break statement doesent work as you think.
According to nested loop, if you put break statement in inner loop, compiler will jump out from inner loop and continue the outer loop again. If you need to jump out from the outer loop using break statement given inside inner loop you can use a labelled loop, i.e give your loop a name and use it with the break statement.
In your code above you shold not only breake the inner most loop but also the one above:
public static void main(String[] args) {
int[][] big = new int[10][10];
int[][] small = new int[][]{{12, 13, 14}, {13, 14, 15}};
for (int i = 0; i < big.length; i++) {
for (int j = 0; j < big[i].length; j++) {
big[i][j]= (int)((Math.random()*20)+1);
}
}
// just added this loop to print the random array so you can check the output
for(int[] row : big){
System.out.println(Arrays.toString(row));
}
for(int i = 0; i<big.length-1; i++){
for(int j = 0; j<big[0].length-2; j++){
boolean isEqual = true;
LoopIwannaBreak:for(int k = 0; k<small.length; k++){
for(int m = 0; m<small[0].length; m++){
if(big[i+k][j+m] != small[k][m]){
isEqual = false;
break LoopIwannaBreak;
}
}
}
// added this to tell at which index the match was found
if(isEqual){
System.out.println("found at big["+i+"]["+j+"]");
}
}
}
}
I am trying to shift elements in a 2D array (specifically a square matrix) so that the result is a "staircase" pattern:
Original:
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
Objective:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
I've managed to write a program that can perform the task in a 1D array for the first line of the matrix (see below), but I can't seem to translate the code so that it functions in a 2D array.
How do I get my code to function in a 2D array in Java?
And, for later, how would I go about incrementing the change so that, as the row increases (from upper to lower levels of the matrix), the number of shifts also increases?
public class StaircaseMatrix
{
public static void main(String[] args)
{
int[] num = {1,2,3,4,5};
shiftRight(num);
System.out.println("After shifting the array is:");
for (int x = 0; x < num.length; x++)
System.out.print(num[x] + " ");
}
public static void shiftRight(int[] list)
{
int last = list[list.length - 1];
for (int j = list.length - 1; j > 0; j--) {
list[j] = list[j - 1];
}
list[0] = last;
}
}
You call shiftRight() 0 times for array2D[0], 1 time for array2D[1], 2 times for array2D[2], and so on, using a for loop.
I'm new to Java. I'm trying to make a triangular multiplication table that looks somewhat like this:
Enter # of rows 7
1 2 3 4 5 6 7
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Each row/column has to be numbered, and I have no idea how to do this. My code is seemingly waaay off, as I get an infinite loop that doesn't contain the correct values. Below you will find my code.
public class Prog166g
{
public static void main(String args[])
{
int userInput, num = 1, c, d;
Scanner in = new Scanner(System.in);
System.out.print("Enter # of rows "); // user will enter number that will define output's parameters
userInput = in.nextInt();
boolean quit = true;
while(quit)
{
if (userInput > 9)
{
break;
}
else
{
for ( c = 1 ; c <= userInput ; c++ )
{ System.out.println(userInput*c);
for (d = 1; d <= c; d++) // nested loop required to format numbers and "triangle" shape
{
System.out.print(EasyFormat.format(num,5,0));
}
}
}
}
quit = false;
}
}
EasyFormat refers to an external file that's supposed to format the chart correctly, so ignore that. If someone could please point me in the right direction as far as fixing my existing code and adding code to number the columns and rows, that would be greatly appreciated!
Two nested for loops will do the trick:
for (int i = 1; i < 8; i++) {
System.out.printf("%d\t", i);
}
System.out.println();
for (int i = 1; i < 8; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%d\t", i * j);
}
System.out.println();
}
OUTPUT
1 2 3 4 5 6 7
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49