Simple Java array syntax which i'm confused over - java

public static void main(String[] args) {
int[][] b = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 1}};
int[] u = new int[b.length];
for (int i = 0; i < u.length; i++) {
for (int j = 0; j < b[i].length; j++) {
u[i] = u[i] +b[i][j];
}
System.out.println(u[i]);
}
}
What is the differences between written b[i].length; and b.length;
When i run this code with b[i].length; the output is 1,2,3.
When running with b.length; gives the output 0,1,2

Your array got 2 dimensions, thus it is an array of an array. If you use b.length you will get the amount of arrays that are stored within b
Your array could look like this:
int[][] b = {{1}, {1,2}, {1,2,3}};
So b is an array that contains 3 other arrays. b.length (in this case) will always be 3. If you use b[n].length, you will get the length of the array with index n within b. In my example above: b[0].length will be 1, b[1].length will be 2, b[2].length will be 3.

b.length gives you the length of array b which is 3 because it has three element: b[0] which is an array {0, 0, 0, 1}, b[1] which is an array {0, 0, 1, 1} and finally b[2] which is an array {0, 1, 1, 1}.
b[i].lenght gives you the length of element b[i] which is 4. The reason that you can use length method in b[i] is because b[i] is also array (b is an array of arrays so every element of b is an array of int's).
b[i].length will return 4 for every i because every element b[i] is an array of length 4 .However, note that b[i] doesn't need to have same length
for example if you had:
int[][] b = {{0, 0, 0, 1},{1, 1}};
Then here b.length returns you 2, b[0].length returns 4 and b[1].length returns 2.

In your code your have a 2d array.
/*This is an array of arrays*/
int[][] b = {
{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 1}
};
This is an array to arrays.
b.length will return the amount of arrays in the main array
b[i].length will return the amount of elements in one specific array on index i

b.length return number all rows but b[i].length; return number column for row i

b.length is the number of rows in your matrix
b[i].length is the number of elements i-th row

b refers to an array of arrays.
b.length returns how many elements b has - in other words, how many "nested" arrays you have.
b[i].length returns how many elements b[i] has - in other words, the length of the nested array referred to by b[i].

Related

How to merge two elements in an array together?

For example you have the 2d array Board as shown below:
{0, 2, 4, 2}
{0, 0, 2, 2}
{2, 2, 0, 0}
{0, 5, 0, 2}
You want it to become:
{0, 2, 4, 2}
{0, 0, 4, 0}
{4, 0, 0, 0}
{0, 5, 0, 2}
When there are 2 elements next to each other you need to merge them to make 4 into the left-most place out of those two elements and then make the 2nd element to be 0.
You want to do this with java.
forgot to show my existing loop, this is it below:
for (int row = 0; row < Board.length; row++){
for (int col = 0; col <= Board.length; col++){
if ((Board[row][col] == Board[row][col +1])){
Board[row][col] = 2 * Board[row][col];
Board[row][col + 1] = 0;
}
}
}
Well, I guess that should work. In the loop, you must be careful not to refer to the wrong ( or non-existing) array element.
public static void main(String[] args) {
int[][] arr = new int[][]{{0, 2, 4, 2}, {0, 0, 2, 2}, {2, 2, 0, 0}, {0, 5, 0, 2}, {2, 2, 2, 2}, {2, 2, 2, 0}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length - 1; j++) {
if (arr[i][j] == arr[i][j + 1]) {
arr[i][j] = arr[i][j] + arr[i][j + 1];
arr[i][j + 1] = 0;
}
}
}
System.out.println(Arrays.deepToString(arr));
}
Here is one way, focusing only array values that equal 2.
iterate the 2D array.
then iterate over each linear array, checking adjacent values and making the changes.
for(int[] arr : v) {
for(int i = 0; i < arr.length-1; i++) {
if (arr[i] == 2 && arr[i+1] == 2) {
arr[i]+= arr[i+1];
arr[i+1] = 0;
}
}
}
for(int arr[]: v) {
System.out.println(Arrays.toString(arr));
}
prints
[0, 2, 4, 2]
[0, 0, 4, 0]
[4, 0, 0, 0]
[0, 5, 0, 2]
Well I assume that Board variable holds array (quick tip, common convention is to name variable in camelCase (first letter lowercase, then each letter of next work upper, if that variable is constant, then convention is SNAKE_UPPER_CASE)
Your first for is pretty okay, the second one too but it assumes that matrix will be always NxN and will fail if thats not the case or it will not work properly (depending if amount of cols is lower or greater than length of array)
Inside it you dont want to check if the values are equal, you want to check if these values are both equal to 2. And you should check if thats not processing of last column of the row, in that case youll get IndexOutOfBoundException because you want to get value of matrix that is not present.
So with small changes, you will achieve what you want. This code will hopefuly shows my thoughts better
public class MergingTwos {
public static void main(String args[]) {
// Init a matrix
int[][] array = new int[][] { { 0, 2, 4, 2 }, { 0, 0, 2, 2 }, { 2, 2, 0, 0 }, { 2, 2, 0, 0 }, { 0, 5, 0, 2 }};
// Iterating over each row of matrix, in veriable i, the current X index is stored
for(int i = 0; i < array.length; i++) {
// Iterating over each column of row, in variable n, the current Y index is stored
for(int n = 0; n < array[i].length; n++) {
// To prevent index out of bound exception, last element of row wont be processed so as we dont want to proceed if given and next value on row are not 2
if(n == array[i].length -1 || array[i][n] != 2 || array[i][n+1] != 2) {
continue;
}
// To value at given coordinates [i,n] you add values of value on coordinates [i, n+1]
array[i][n] = array[i][n] + array[i][n+1];
// And setting next element to 0
array[i][n+1] = 0;
}
}
// Printing the result
for (int[] x : array) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
}

Square Value at Index without using a temp array

At 0th index value is 4, so I have to check the value at index 4 and square it and place the value at 0th index without using a temp array:
Index 0 1 2 3 4
Values 4 3 1 2 0
================
Result 0 4 9 1 16
Now I am getting the first two values right, but the last three are not right. My code is as below:
static void Index(int arr[], int n) {
for(int i=0;i<n;i++) {
int index = arr[i];
int value = arr[index];
arr[i]=value*value;
}
}
Below is the output that I am getting:
Original Array
4 3 1 2 0
Array after Squaring
0 4 16 256 0
Can anyone help me out here as to what am I doing wrong?
Assuming the numbers are within range [0, 46341), we can store both the old and the new values in the array during the process (as 32 bits are enough). Then after the first loop we do another one to discard the old values and square the new ones.
// assume array[i] is within range [0, 46341) for any i
static void f(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = array[i] & 0xffff; // get old value
array[i] = array[j] << 16 | j; // put new and old values
}
for (int i = 0; i < array.length; i++) {
int j = array[i] >>> 16; // get new value
array[i] = j * j; // put new value squared
}
}
NOTE: This approach is valid only if length of array is less than 10.
I have completed this code using only one loop without using any extra space.
Although, I have set a flag to run the complete loop twice.
If you do not have any constraint of using one loop, you can avoid using the flag and simply use two loops.
Approach:
Index 0 1 2 3 4
Values 4 3 1 2 0
Updated value 04 23 31 12 40
You must have got the idea what I did here.
I put the values at tens place whose square is to be displayed.
Now you have to just have to iterate once more and put the square of tens place at that index
Here's the code:
void sq(int arr[], int n){
bool flag = false;
for(int i=0; i<n; i++){
if(!flag){
if(arr[arr[i]] < 10){
arr[i] += (arr[arr[i]] * 10);
}
else{
arr[i] += ((arr[arr[i]]%10) * 10);
}
}
if(i==n-1 && !flag){
i=0;
flag = true;
}
if(flag)
arr[i] = (arr[i]/10) * (arr[i]/10);
}
}
It is in C++.
The problem is you are changing the values in your original array. In you current implementation this is how your array changes on each iteration:
{4, 3, 1, 2, 0}
{0, 3, 1, 2, 0}
{0, 4, 1, 2, 0}
{0, 4, 16, 2, 0}
{0, 4, 16, 256, 0}
The problem is you still need the values stored in the original array for each iteration. So the solution is to leave the original array untouched and put your values into a new array.
public static void index(int arr[]) {
int[] arr2 = new int[arr.length];
for(int i=0;i<arr.length;i++) {
int index = arr[i];
int value = arr[index];
arr2[i]=value*value;
}
}
Values of arr2 in revised process:
{0, 0, 0, 0, 0}
{0, 0, 0, 0, 0}
{0, 4, 0, 0, 0}
{0, 4, 9, 0, 0}
{0, 4, 9, 1, 0}
{0, 4, 9, 1, 16}

How to store a 2D array in a regular array? Java

basically I want to be able to store a 2D array such as this
int [][] preferredMoves = {
{0,0}, {0, arrLength}, {length%2, arrLength},
{0, length%2}, {arrLength, 0}, {0, length%2},
{arrLength, arrLength}, {length%2, length%2},
{arrLength, length%2}, {length%2, 0}
};
In a single
int [] moves;
array.
I'm sure this is possible since I'm just storing a list..., but I can't seem to find information on this anywhere... or maybe its not possible?
EDIT
I am dealing with matrices.
I want to store the list in a single array to then return that array to use it elsewhere.
So then every time I call it, all I have to do is something like this...
int row = Computer.moves()[0];
int col = Computer.moves()[1];
I also need to loop through that single array, which contains the 2D array multiple times..
Not sure if this is what you meant,
but you could drop the internal { ... } to convert this to a one-dimensional array:
int [] moves = {
0, 0, 0, arrLength, length % 2, arrLength,
0, length % 2, arrLength, 0, 0, length % 2,
arrLength, arrLength, length % 2, length % 2,
arrLength, length % 2, length % 2, 0
};
And you can translate 2D indexes (i, j) to 1D index k using the formula:
k = i * 2 + j;
Janos' answer is probably what you want. Alternatively you could create a class, e.g. Pair, and store it in a Pair[] array.

Replacing integers in an array with Integers from another array

I am struggling with this problem where I have to take (i/2)+1 numbers from one array and then insert them into that back of a second array.
e.g. 1st array = {2, 5, 3, 4, 8, 9}
2nd array = {-1, -1, -1, -1, -1, -1, -1}
what i want to achieve = {-1, -1, -1, 4, 3, 5, 2}
So I want to take the 1st number in the 1st array and insert it into the last position of the 2nd array replacing the -1 and so on and so forth
What I have so far is:
for(int i = 2nd Array.length; i <2nd Array.length; i--){
int value = 1st Array[i];
2nd Array[i]= 2nd Array[i].replace(i, value);
}
for the moment i'm just trying to get it to insert one set of values into the array.
I have not attempted taking only (1st Array.length/2)+1 numbers from the array.
Can anyone give me some advice on how to do this?
For clarity, use one index for each array, i1 index for array1 and i2 for array2.
Assuming both arrays are already initialised:
int i2 = array2.length-1;
for (int i1 = 0; i1 < (array1.length/2+1) && i2 >=0 ; i1++) {
array2[i2] = array1[i1];
i2--;
}
Or you can put everything in the for:
int[] array1 = {1,2,3,4,5,6,7,8,9};
int[] array2 = {-1,-1,-1,-1,-1,-1,-1,-1,-1};
for (int i1 = 0, i2 = array2.length-1;
i1 < (array1.length/2+1) && i2 >=0 ;
i1++, i2--) {
array2[i2] = array1[i1];
}
System.out.println(Arrays.toString(array2));
Output:
[-1, -1, -1, -1, 5, 4, 3, 2, 1]
EDIT
If you want the otherway, just change the direction for index i1, e.g.
for (int i1 = array1.length/2+1, i2 = array2.length-1;
i1 >= 0 && i2 >=0 ;
i1--, i2--) {
array2[i2] = array1[i1];
}
System.out.println(Arrays.toString(array2));
Output:
[-1, -1, -1, 1, 2, 3, 4, 5, 6]
I think there is an problem in your "for" loop.
for(int i = 2nd Array.length; i <2nd Array.length; i--)
It will exit the loop because "i" starts from 2nd Array.length and it will not be less than 2nd Array.length.
to start in the middle of the array, you should set the initial value for i as (length/2 + 1), since arrays indexes starts on 0, you can use array2.length/2
for(int i = array2.length/2; i < array2.length; i++)
array1[i] = array2[i];

How to reorder the columns of a 2d array?

Is there a simple way to randomize the order of columns in a 2d array? For example could I use it to randomize the columns of this 2d array
int[][] dataArray = {{1, 1, 0, 1, 0, 0},
{0, 0, 1, 0, 1, 1},
{1, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 1, 1}};
I have been trying for awhile with little luck so far.
What i am trying to do is make columns 1 2 3 4 5 6 randomly become columns 2 3 1 6 5 4 for example.
I have tried randomly drawing numbers and trying to make the columns match the order but i can't seem to get that working.
You could always construct a 1D array, randomize its contents, then reconstruct a 2D array.
int[] newArray = new int[a.length + b.length + c.length + d.length];
// where a, b, c, and d are the smaller arrays inside dataArray
System.arrayCopy(a, 0, newArray, 0, a.length);
System.arrayCopy(b, 0, newArray, a.length, b.length);
System.arrayCopy(c, 0, newArray, a.length + b.length, c.length);
System.arrayCopy(d, 0, newArray, a.length + b.length + c.length, d.length);
This will construct a 1D array called newArray that has the contents of all the smaller arrays.
Now randomize that array as shown here.
Then to reconstruct the original array:
int newArray2d[][] = new int[5][4]; //do this dynamically based on the size of the first array.
for(int i=0; i<5;i++)
for(int j=0;j<4;j++)
array2d[i][j] = array1d[(j*10) + i];

Categories