copying column of a 2D array as 1D array in java? - java

Let's say I have a 2D array:
int[][] a = new int[4][3];
populated such that:
1 2 3
4 5 6
7 8 9
2 5 7
Is there any shortcut method in java to extract lets say column 1 as single array:
array1 = {1 4 7 2};
Currently what I am doing is traversing through the whole 2D matrix and with if condition (if j==0), I traverse over the rows and add values to 1D array.
Just wondering if there is any standard method offered in java for such tasks.

No there is no shortcut to doing this. You have to loop over the arrays, switching the x & y indices.

There is no such build-in method. You have to write a simple loop.

You might want to consider use of a matrix library. But this is pretty simple stuff - if this is all you need, you can probably write it quicker than you can get up to speed on a library.

Related

Suitable data structure for Java 1000*1000 matrix.

I am practising java programming. I encountered a problem which requires 1000 x 1000 matrix which stores integers value less than 1500
I would want to navigate across all the elements
I might need to fetch max element and its 4 adjacent elements.
What is the best data structure which doesn't affect performance?
1 2 3 4
5 6 7 8
9 10 11 12
12 14 15 16
for the element 11 --> 7, 10, 12, 15 are adjacent elements.
what is wrong with the 2d array data structure?
to get an adjecent of a number at i,j return [i-1][j],[i+1][j],[i][j+1],i[j-1] (you will have to deal with cases where i is zero etc)...
as performance goes, its O(1), doesn't get any better than that...
If you are talking about finding the location of the element. if the matrix is sorted you can simply do a binary search.
A 2dim Array of shorts:
-> short [][] matrix = new short[1000][1000];
| Added variable matrix of type short[][] with initial value [[S#1794d431
Generate in a second, few MB in size. What could be better than that?

Are there are any important differences between these two ways of writing arrays?

This is a conceptual question following on from a question (here) I recently got an answer to.
I will use a java example to demonstrate my question but I think this should hold for other similar languages (I could not say for sure -hopefully someone can confirm this or say otherwise). Basically I am wondering if there is any subtle difference between the possible uses for following (given how they are initialised):
double[] array1D = new double[max]
and
double[][] array2D = new double [max][1]
Assuming that we are initialising the second array to have only one column, is there really any need for the 1D array to exist? Does it have any quality that a 2D array doesn't have, or is it just there to confuse poor souls like myself? Furthermore I would like to know if array2D with only one column can do anything that array1Dcannot?
The main difference between array1D and array2D is that in the latter the rows (or columns, however you want to look at it) are individual objects that can be used independently of the entire array.
For example you can pass an entire row to a function, and the function is allowed to modify the row. To achieve the same with a 1D array you'd have to pass the original array, the start index of the row in the array, and length of the row.
Every reference to an object costs 4 bytes, so the memory usage increases with 4 bytes for each element, so it is a waste of memory to use a 2D array for something that a 1D array can do.
new double[max] creates an array of doubles (initialized with 0.0) with lengh = max
new double [max][1] creates an array of pointers each of them points to a double array with one element = 0.0
int A[2][3]={{1,2,3},{4,5,6}};
A 2D array is stored in the memory as follows. Entries in
row 0 are stored first followed by row 1 and so on.
2-D arrays are represented as a
contiguous block of n blocks each with size m (i.e. can
hold m integers(or any data type) in each block). The
entries are stored in the memory as shown above.Here n represent the number of rows and m represents the
number of columns.
In Java:
As with all arrays, the new keyword must be used to allocate memory for an array. For example,
int[][] a = new int[2][4];
This two-dimensional array will have two rows and four columns.
This actually allocates 3 objects: a one-dimensional array of 2 elements to hold each of the actual row arrays, and two one-dimensional arrays of 4 elements to represent the contents of the rows.
+-----+ +-----+-----+-----+-----+
|a[0] | -> | [0] | [1] | [2] | [3] |
| | +-----+-----+-----+-----+ In Java two-dimensional arrays are implemented is a
one-dimensional array of one-dimensional arrays -- like this.
+-----+
| | +-----+-----+-----+-----+
|a[1] | -> | [0] | [1] | [2] | [3] |
+-----+ +-----+-----+-----+-----+
In your case:
double[][] array2D = new double [max][1]
This actually allocates max+1 objects: a one-dimensional array of max elements to hold each of the actual row arrays, and max one-dimensional arrays of 1 elements to represent the contents of the rows.
Let me know if I am wroung .
Both will just do the same thing. Moreover you don't need to create a 2-dimensional array when all you need is just one row. A 2-dimensional array is used when you need to work with multiple 1-dimensional arrays.
Also, I think you need to initialize your 2-dimensional in this way to achieve it to work for 1-d array
double[][] array2D = new double[1][max]
Imagine this is 1D array
1 2 3 4 5 6 7 8 9
and this is 2D array
1
2
3
4
5
6
7
8
9
1 2 3 4 5 6 7 8 9
basically, 2D array can store more data than 1D array, and more complex than 1D array
You seem to have the misconception that it is normal for arrays to have two dimensions. This is not true.
In programming languages one-dimensional arrays are the norm, while two- and higher dimensional ones are rather rare (I can't remember when I last used one in Java).
Using a two-dimensional array instead of a one-dimensional one would be possible, but it would obscure the meaning of the array and make accessing the array elements more complicated.

Java array initialization

Given a bunch of temperatures, I am supposed to put them into an array that sorts them by every 10 degrees. I am pretty confused. I was able to print out all the temperatures from a provided txt file, but now I am not sure how to put them into an array. There should be 11 indexes( <=9, 10-19, 20-29, 30-39, 40-49, 50-59, 60-69, 70-79, 80-89, 90-99, and >=100). I am just really confused on how to use arrays.
I think you should use multidimensional array or a hash table that sort temperatures in a range from 1 to 10 and from 10 to 20
Put to the array the upper edges:
int[] a = {10, 20, 30, ..., Integer.MAX_INTEGER}
It defines intervals 0-9, 10-19, etc.

Best data structure to store and manipulate my data?

I am writing a simple Java program that will input a text file which will have some numbers representing a (n x n) matrix where numbers are separated by spaces. for ex:
1 2 3 4
5 6 7 8
9 1 2 3
4 5 6 7
I then want to store these numbers in a data structure that I will then use to manipulate the data (which will include, comparing adjecent numbers and also deleting certain numbers based on specific rules.
If a number is deleted, all the other numbers above it fall down the amount of spaces.
For the example above, if say i delete 8 and 9, then the result would be:
() 2 3 ()
1 6 7 4
5 1 2 3
4 5 6 7
so the numbers fall down in their columns.
And lastly, the matrix given will always be square (so always n x n, where n will be always given and will always be positive), therefore, the data structure has to be flexible to virtually accept any n-value.
I was originally implementing it in a 2-d array, but I was wandering if someone had an idea of a better data structure that I could use in order to improve efficiency (something that will allow me to more quickly access all the adjacent numbers in the matrix (rows and columns).
Ultimately, mu program will automatically check adjacent numbers against the rules, I delete numbers, re-format the matrix, and keep going, and in the end i want to be able to create an AI that will remove as many numbers from the matrix as possible in the least amount of moves as possible, for any n x n matrix.
In my opinion, you yo know the length of your array when you start, you are better off using an array. A simple dataType will be easier to navigate (direct access). Then again, using LinkedLists, you will be able to remove a middle value without having to re-arrange the data inside you matrix. This will leave you "top" value as null. in your example :
null 2 3 null
1 6 7 4
5 1 2 3
4 5 6 7
Hope this helps.
You could use one dimensional array with the size n*n.
int []myMatrix = new myMatrix[n * n];
To access element with coordinates (i,j) use myMatrix[i + j * n]. To fall elements use System.arraycopy to move lines.
Use special value (e.g. Integer.MIN_VALUE) as a mark for the () hole.
I expect it would be fastest and most memory efficient solution.
Array access is pretty fast. Accessing adjacent elements is easy, as you just increment the relevant index(s) (being cognizant of boundaries). You could write methods to encapsulate those operations that are well tested. Having elements 'fall down' though might get complicated, but shouldn't be too bad if you modularize it out by writing well tested methods.
All that said, if you don't need the absolute best speed, there are other options.
You also might want to consider a modified circularly linked list. When implementing a sudoku solver, I used the structure outlined here. Looking at the image, you will see that this will allow you to modify your 2d array as you want, since all you need to do is move pointers around.
I'll post a screen shot of relevant picture describing the datastructure here, although I would appreciate it if someone will warn me if I am violating some sort of copy right or other rights of the author, in which case I'll take it down...
Try a Array of LinkedLists.
If you want the numbers to auto-fall, I suggest you to use list for the coloumns.

how to delete an element in a two dimensional array in java?

let the array be
5 1 6 8
2 4 9 3
1 9 3 2
5 3 8 9
in the above shown array i need to delete the last element of even rows (2,4rows). So that my new array looks like
5 1 6 8
2 4 9 1
9 3 2 5
3 8
Please help how to do this with java code?
It looks like you are trying to treat this 2d array as a single array which is just being displayed in 2d. Maybe you should just use a single ArrayList and remove the elements normally.
Maybe you have to use a internal ArrayList (Single dimension) and have
a method that returns an
bidimensional array
a methos that removes the x position in line y
Your class must have the dimension size (maybe in the constructor).
You should assign the last element of your 2D array to be a new 1D array containing only the elements you want to keep:
arr[3] = new int[] {arr[3][1], arr[3][3]};
(assuming your array arr is of type int[][])
Treat it as a list and iterate backward and delete all items divisible by 8 and you will get the result you are hoping to get , and in case you want in array format , you can convert the its to array or 2D array

Categories

Resources