Filling a two dimensional array with integers java - java

I wanted to write a function which should fill a two dimensional array like this:
1 -- 3 -- 5 -- 7 -- 9
3 -- 5 -- 7 -- 9 -- 11
5 -- 7 -- 9 -- 11 -- 13
7 -- 9 -- 11 -- 13 -- 15
9 -- 11 -- 13 -- 15 -- 17
Here's it what I could come up with ... by all my logic it should work, but obviously I made some mistake:
public class Array {
public static void TwoDimFill(int[] [] array, int start, int inc){
array[0] [0] = start;
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){enter code here
array[i][j+1] = array[i][j] + inc;
}
array [i+1][0] = array[0][i+1];
}
}
public static void main(String[] args){
int[] [] b = new int[5] [5];
TwoDimFill(b, 1, 2);
for (int x = 0; x < b.length; x++){
for (int y = 0; y<b[x].length; y++){
TextIO.put(b[x][y]+"\t");
}
TextIO.putln();
}
}
By the way: This TextIO.class is something we use for printing, compareable to system.out ...
Edit: Answered! Thank you a lot guys, you're great!

i+1 and j+1 will be out of bounds because you loop until < length. Change it to < length -1.
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length -1; j++){
array[i][j+1] = array[i][j] + inc;
}
if (i < array.length -1)
array [i+1][0] = array[0][i+1];
}
EDIT: As pointed out on comments, the last output line was incorrect. Variable i can be looped until < length, but it must be verified for the last line that the index won't get out of bounds. Corrected the code above.

There is an excess number of operations you are doing. There is a much cleaner, simpler and faster solution. Sometimes a different approach can solve the problem better.
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
array[i][j]=((i+j)<<1)+1;

You need to check if the index is out of bounds before executing the last line in your loop, as well as only making your inner loop iterate up to length-1 (since indexes for arrays in Java start at 0 and end at 1 less than their length):
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array[i].length - 1; j++) {
array[i][j + 1] = array[i][j] + inc;
}
if(i + 1 < array.length) {
array[i + 1][0] = array[0][i + 1];
}
}
This produces:
1 3 5 7 9
3 5 7 9 11
5 7 9 11 13
7 9 11 13 15
9 11 13 15 17
Note that simply clipping the outer loop to array.length-1 doesn't work (since in this case you still want the first part of the loop to execute), you'd end up with the following:
1 3 5 7 9
3 5 7 9 11
5 7 9 11 13
7 9 11 13 15
9 0 0 0 0
Bolding is mine, note the last line is obviously incorrect.

This is wrong because of array[i][j+1]. If j is the last position j+1 doesn't exist. You can try this:
public static void TwoDimFill(int[] [] array, int start, int inc){
int aux = 0;
for(int i = 0; i < array.length; i++) {
aux = start;
for(int j = 0; j < array[i].length; j++) {
array[i][j] = aux;
aux += inc;
}
start += inc;
}
}

You can do this really simply, use the following
public class TestClass {
public static void main(String args[]) {
int[][] temp = new int[5][5];
int[][] output = fill2dim(temp,1,2);
for (int i = 0; i < output.length; i++) {
System.out.println(java.util.Arrays.toString(output[i]));
}
}
public static int[][] fill2dim(int[][] arr, int start, int inc) {
int[][] output = new int[arr.length][arr[0].length];
for (int i = 0;i<arr.length;i++) {
for (int j = i;j<arr[0].length;j++) {
output[i][j] = (i+j)*inc+start;
output[j][i] = (i+j)*inc+start;
}
}
return output;
}
}
You can remove some loops by just considering the upper triangular matrix, since the lower triangular matrix will be a reflection of the upper triangle about the diagonal

Related

Why is the result only 81 when I try to use array

Thanks for reading my question:
public class Gugudan_array {
public static void main(String[] args) {
for(int i = 2; i<10; i++) {
for(int j = 1; j<10; j++) {
System.out.println(i * j);
}
System.out.println();
}
}
}
In the multiplication table above, result comes correctly from 2-9, however:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int h = 0; h < result.length; h++) {
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
In this code with array, the result comes out only 81.
What have I done wrong?
Thank you!
I'll first explain why your code doesn't work, and then go over a correct solution:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int h = 0; h < result.length; h++) {
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
The main problem lies in this chunk of code:
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[h] = (i * j);
}
}
Here, you are constantly overwriting the value of result[h], so that once the loop ends and both i = 9, and j = 9, the code will execute result[h] = 9 * 9 and then continue on to the next h.
My solution:
public class Gugudan_array {
public static void main(String[] args) {
int[] result = new int[10];
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[i - 2] = (i * j);
}
}
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
}
Output:
18
27
36
45
54
63
72
81
0
0
First, notice how I completely got rid of the h loop. That is because we can make the index in terms of i. When we determine the first number, when i = 2, we want to store that number in the 0th index of our array. Similarly, when we get our second number, when i = 3, we want to store the result in the 1st index of our array.
To summarize, whenever we calculate a result, we will want to store it in the i - 2th index of our array.
Better Solution using 2D arrays:
int[][] result = new int[8][9];
for(int i = 2; i < 10; i++) {
for(int j = 1; j<10; j++) {
result[i - 2][j - 1] = (i * j);
}
}
for(int a = 0; a < result.length; a++) {
for(int b = 0; b < result[a].length; b++){
System.out.print(result[a][b] + " ");
}
System.out.println();
}
Output:
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
Note: If you want the output to match your original code, change System.out.print(result[a][b] + " "); to System.out.println(result[a][b])
It would make the most sense to store a multiplication table in a 2D array.
This code works by mapping i * j to the [i - 2][j - 1]'th element of the 2D array, so that 2 * 1, will end up in result[0][0]
I hope this made sense! Please let me know if you need any further help or clarification!
You have to increase h variable after all iteration. Here is whole code:
public static void main(String[] args) {
int[] result = new int[10];
for (int h = 0; h < result.length; h++) {
for (int i = 2; i < 10; i++) {
for (int j = 1; j < 10; j++) {
result[h] = (i * j);
if (h < 9) {
h++;
}
}
}
}
for (int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
}
The issue is that your current setup with 3 nested loops, the outer loop runs 10 times, the middle loop runs 8 times for each other loop, and the inner loop runs 9 times for each middle loop, which gives a total of 10x8x9=720 times... but I suspect you just want 72 results like you show in your first example, so we need to remove the outer loop first for(int h = 0; h < result.length; h++) {.
Now the issue is that we need to store all 72 results but your current array only fits 10 results int[] result = new int[10];, we can solve this with a bigger array:
int[] result = new int[8 * 9]; //72 spaces
Here is a working solution with a long array and a counter that keeps track of where to store the value, note the code comments for extra details:
//Your loops calculate 8 * 9 results, so you need an array with 72 spaces
int[] result = new int[72];
//Use a variable to track the array location
int counter = 0;
//Youn only need two loops
for(int i = 2; i < 10; i++) {
for(int j = 1; j< 10; j++) {
//Save the result in the correct location
result[counter] = (i * j);
//Incriment the counter
counter++;
}
}
//Print the stored results
for(int a = 0; a < result.length; a++) {
System.out.println(result[a]);
}
Some further important reading from the official Java guide on Arrays:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
A better solution would be to use a 2D array.

How to alternate the order of elements in every other column in a 2D Array

An empty 2D array a should be filled with the following values:
1 8 9 16 17
2 7 10 15 18
3 6 11 14 19
4 5 12 13 20
I've been having a lot of trouble with figuring out how to reverse the order of a column. This is the closest I've gotten:
int [][] a = new int[4][5];
int count = 1;
for(int c = 0; c < a[0].length; c++) {
for(int r = 0; r < a.length; r++) {
a[r][c] = count;
count++;
if(r% 2 == 0 && c % 2 != 0) {
count = 20;
a[r][c] = 20;
count--;
}
}
}
You should define a variable that defines the direction you want to move at each iteration, i've named it sign. if sign is positive, column will be filled in a downward manner, otherwise it would move in the opposite direction.
int [][] a = new int[4][5];
int count = 1;
int sign = 1;
for(int j = 0 ; j < 5 ; j++){
if(sign==1)
for(int i = 0 ; i < 4 ; i++){
a[i][j]=count;
count++;
}
else
for(int i = 3 ; i >=0 ; i--){
a[i][j]=count;
count++;
}
sign *= -1;
}
If we want to print the array we'll have :
for(int i = 0 ; i < 4; i++){
for(int j = 0 ; j < 5; j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
Resulting output would be :
1 8 9 16 17
2 7 10 15 18
3 6 11 14 19
4 5 12 13 20
you are on the right track, just reverse the row when inserting even numbered columns.
public static void main(String []args){
int count =1;
int columnCount =5;
int rowCount = 4;
int [][] a = new int[rowCount][columnCount];
for (int column = 0; column<columnCount; column ++ ) {
for (int row = 0; row <rowCount; row ++) {
if(column%2==0){
a[row][column] = count;
}else {
a[rowCount-row-1][column] =count;
}
count ++ ;
}
}
//validate results
for (int row = 0; row <rowCount; row ++) {
for (int column = 0; column<columnCount; column ++ ) {
System.out.print (a[row][column] +" ");
}
System.out.println();
}
}
this will give you the following results
$java -Xmx128M -Xms16M HelloWorld
1 8 9 16 17
2 7 10 15 18
3 6 11 14 19
4 5 12 13 20

How to understand Loops and Array in java

I am quite confused in array loops that do have nested ones to print the Two Dimensional array. /it contains a loop without curly braces and second one has just opposite way of representing the braces for loops ...
Since i am learning I have just typed the code and got output.
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++)
System.out.print(twod[i][j] + " ");
System.out.println();
}
}
}
The result it generates is
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Try this :
public class TwoDimensional {
private int i, j, k = 0;
int[][] twod = new int[4][5];
public void DoubleT() {
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
}
To properly use the braces always think about the purpose of the loops you have, when do you want them to finish and when do you want them to continue.
In your case, you'll need nested loops for different tasks so you have to properly delimit each one of those tasks.
Fill the the 2D array:
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
twod[i][j] = k;
k++;
}
}
Print the 2D array values:
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++){
System.out.print(twod[i][j] + " ");
}
System.out.println();
}
Notice that, either for filling or printing the array, your first loop (iterator i) is responsible for the line. It'll stop at I = 3, line number 3. So you'll be in line 0 until you finish the values of all the columns on that line ( [0][0],[0][1],[0][2],[0][4] ) and you just want to go to the second line when your first line is totally filled or printed, and so on. On the print case, you'll need to change the line before the 'i' increments (new line number) and after you have all `'j' values.
To summarize, you'll just want to increment the line ('i') or go to the next line (println()), when your columns ('j') are finished.

Struggling with nested for loops

Alright so, I'm new to nested for loops adn I'm having a bit of an issue on understanding them. I've read many guides, but I still don't fully understand.
Alright the prompt:
Write nested for loops that produce the following output:
000111222333444555666777888999
000111222333444555666777888999
000111222333444555666777888999
What I have so far
for(int num2 = 0; num2 <= 9; num2++) {
for(int num1 = 0; num1 <= 2; num1++) {
System.out.println(num2 + " " + num2 + " " + num2);
}
}
And the output is
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1
1 1 1
2 2 2
2 2 2
2 2 2
3 3 3
3 3 3
3 3 3
4 4 4
4 4 4
4 4 4
5 5 5
5 5 5
5 5 5
6 6 6
6 6 6
6 6 6
7 7 7
7 7 7
7 7 7
8 8 8
8 8 8
8 8 8
9 9 9
9 9 9
9 9 9
What am I doing wrong?
You got 3 copies of each number.
the outer loop:
for (int i = 0; i < 10; i++) {
chooses which number you want to print so that is fine.
The inner loop however is comparing j against the chosen number. You want 3 copies, not a variable number of copies. This change will make 3 copies:
for (int j = 0; j < 3; j++) {
You also don't need this:
System.out.println(i);
EDIT: I just noticed you need 3 of these outputs.
add an outer loop:
for (int x = 0; x < 3; x++) {
and a blank space
System.out.println(" ");
So the final result should be:
for (int x = 0; x < 3; j++) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(i);
}
}
System.out.println(" ");
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(j + "" + j + "" + j);
}
System.out.println();
}
In the program provided by you the following events take place:-
In first loop variable i is initiated, condition for loop is checked and then it moves to the second loop if condition is true.
Now second loop iterates over the value of j until the condition is false and then control returns to the first loop.
Try to follow the working of loop and you can see yourself where were you wrong.
Try this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 3; k++) {
System.out.print(j);
}
}
System.out.println("");
}
loop 1: You want the sequence 3 times, each occurrence on its own line.
loop 2: You want the sequence to have digits 0 through 9 ascendingly.
loop 3: You want the sequence to have each digit in succession 3 times.
for (int k = 0; k<3, k++){
for (int i = 0; i< 10; i++) {
for (int j = 0; j < 3;j++) {
System.out.println(i);
}
}
System.out.println("")};
}
}
for(int k=0;k<3;k++) {
for (int i = 0; i< 10; i++) {
for (int j = 0; j < 3;j++) {
System.out.println(i);
}
}
}
Although I am by far most inexperienced guy here, I think this should give exact output you're looking for.

Nested For Loop Pattern

I've been struggling with this for loop pattern in Java(with spaces on both sides)
0
000
00000
0000000
00000
000
0
Heres what I have been doing:
for (int i = 1; i <= 5; i++) {
for (int s = 5; s > i; s--) {
System.out.print(" ");
}
for (int j = 1; j < i; j++) {
System.out.print("0");
}
for (int j = 1; j < i; j++) {
System.out.print("0");
}
System.out.println("");
}
for (int i = 1; i <= 5; i++) {
for (int s = 1; s < i; s++) {
System.out.print(" ");
}
for (int j = 5; j > i; j--) {
System.out.print("0");
}
for (int j = 5; j > i; j--) {
System.out.print("0");
}
System.out.println("");
}
As you can probably tell, I've been able to figure out how to print this pattern using an odd number of 0's in each row, but I can't for the life of me figure out how to do it with odd numbers. Thanks.
Sometimes it helps to parameterize the problem a bit; then you can write it down on paper and see if there are any patterns. For example, in your desired output:
0
000
00000
0000000
00000
000
0
First, let's pick a convenient way to describe a row. Let's say a row i is s spaces followed by z zeros, and the whole pattern can be rows rows long. Now write it out. When rows is 7:
i s z
0 3 1
1 2 3
2 1 5
3 0 7
4 1 5
5 2 3
6 3 1
How about if rows is, say, 5:
i s z
0 2 1
1 1 3
2 0 5
3 1 3
4 2 1
What about even numbers? We have to pick how we want it to look, how about:
00
0000
000000
000000
0000
00
So, when rows is 6:
i s z
0 2 2
1 1 4
2 0 6
3 0 6
4 1 4
5 2 2
Ok, so now, let's look for patterns! z is easy: We can see, both from the numbers and visually that z is a function of s and rows:
z = rows - (2 * s);
That is, we know the total width is equal to the height (rows), and we know there are the same number of spaces before and after the zeroes.
So now it boils down to figuring out s from i and rows. Well, after a bit of head scratching and experimenting, we can see that when i < rows / 2:
s = (rows - 1) / 2 - i;
And when i >= rows / 2:
s = i - rows / 2;
And now, it all comes together, e.g.:
void diamond (int rows) {
for (int i = 0; i < rows; ++ i) {
int s;
if (i < rows / 2)
s = (rows - 1) / 2 - i;
else
s = i - rows / 2;
int z = rows - (2 * s);
// print s spaces, then z zeroes, then a newline
}
}
I'll leave the task of printing s spaces and z zeroes as an exercise to the reader.
This is a fairly general problem solving technique for this type of problem:
Parameterize.
Write it down.
Look for patterns.
Step 1 is the most important step, as it defines a way to convert your complex-looking task (drawing a diamond) into a much simpler problem (determining s as a function of i and rows).
you can try this -
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
}
try this,
public static void main(String []args){
int i = -1;
for (int j = 0; j < 7; j +=2) {
i++;
for (int k = i; k < 3; k++)
System.out.print(" ");
for (int z = 0; z <= j; z++) {
System.out.print(0);
}
System.out.println();
}
i=0;
for(int j=4; j>=0;j-=2){
i++;
for(int k=0;k<i;k++)
System.out.print(" ");
for(int z=0;z<=j ;z++)
System.out.print(0);
System.out.println();
}
}
How about just changing the first j=1 to j=2 and changing the first j=5 to j=4, so that you get one less zero from each of those loops?

Categories