How to work with arrays within arrays in java? - java

Let's say I have an int[][] anArray = new int[4][4];
And let's say that I wanted to make row 3 of anArray {1, 2, 3, 4}. Could I do that without manually assigning each individual value its value? What if it was column 2 of anArray?
I'm posting this because it's rather inconvenient to do stuff like this:
int[][] foo = new int[bar][baz];
//
//Code that uses other columns of foo
//
for (int n=0; n < bar; n++)
foo[n][1] = bin[n];

If I understand your question correctly, here is the code to assign row index 3 of anArray as {1,2,3,4} without loops:
int[][] anArray = new int[4][4];
anArray[3] = new int[] {1,2,3,4};
System.out.println(Arrays.deepToString(anArray));
Output:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 4]]

If you want to assign the entire row of a two-dimensional array to another (one-dimensional) array, you can simply do
int[][] foo = new int [3][3];
int[] bin={1,2,3};
foo[1] = bin;
If want to assign the column though, I am afraid that you can only do it manually...

anArray[3] = new int [] {1, 2, 3, 4}

It is basically an array of arrays and so we can add full arrays in one go:
int[][] array = new int[4][4];
for (int i = 0; i < array.length; i++) {
array[i] = new int[] { 1, 2, 3, 4 };
}

You can use a helper method to set a column:
public class MatrixTest {
public static void main(String... args) {
Integer[][] target = new Integer[3][2];
setMatrixColumn( target, 1, new Integer[]{ 1, 1, 1 } );
System.out.println( Arrays.deepToString( target ) );
}
public static <T> void setMatrixColumn(T[][] matrix, int index, T[] values) {
for ( int i = 0; i < values.length; i++ )
matrix[i][index] = values[index];
}
}

Related

Slice a column or row from 2d Java Array

I'm trying to slice the columns or rows of a 2d Integer Array in Java.
I tried the following syntax array[:][0] or array[0][:] to get the first column/row. I get an error, so most probably this is not the correct syntax in Java. Is it possible to slice in any case a specific column/row in Java?
If I'm not mistaken, slicing in Python corresponds to extracting a subarray from the given array, so if you have an array like below:
int[][] vet = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Performing the following slicing vet[0:3][1] corresponds to retrieve an array with the elements 2, 5, 8 (second column from row 0 included to row 3 excluded).
Unfortunately, in Java this is not possible, at least not "vertically" since a 2D array is basically an array of arrays. Each "row" index identifies a sub-array but in reality there are now actual rows or columns, just arrays within another array.
What you could do is to use the Arrays.copyOfRange() method to slice an array "horizontally".
Integer[][] vet = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Integer[] subArray = new Integer[3];
subArray = Arrays.copyOfRange(vet[1], 0, 3); //Retrieves the elements [4, 5, 6]
Instead, for slicing "vertically" you need to write a utility method:
public static void main(String[] args) {
Integer[][] vet = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Integer[] subArray = new Integer[3];
verticalSlicing(vet, subArray, 1, 0, 3);
System.out.println(Arrays.toString(subArrayVert)); //Prints [2, 5, 8]
}
public static <T> void verticalSlicing(T[][] vet, T[] subArray, int col, int rowStart, int rowEnd) {
if (col < 0 || col > subArray.length || (rowEnd - rowStart) > subArray.length) {
return;
}
IntStream.range(rowStart, rowEnd).forEach(i -> subArray[i] = vet[i][col]);
}
Usually a 2d array in java will look something like this:
double[][] doubleArray = new double[3][4];
So getting the first row can be:
double[] firstRow = doubleArray[0];
And getting the first column can look like this:
double[] firstColumn = new double[doubleArray.length];
for (int i = 0; i < doubleArray.length; i++) {
firstColumn[i] = doubleArray[i][0];
}
Given that you index array[x][y] you can get column x by:
int column[] = array[x].
To get row y:
int row[] = new int[array.length];
for (int i = 0; i < array.length; i++) {
row[i] = array[i][y];
}

Appending arrays using method call [duplicate]

This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 6 years ago.
I'm a beginner with JAVA so this question is not making much sense:
Write a method called append that accepts two integer arrays as
parameters and returns a new array that contains the result of
appending the second array's values at the end of the first array. For
example, if arrays list1 and list2 store {2, 4, 6} and {1, 2, 3, 4, 5}
respectively, the call of append(list1, list2) should return a new
array containing {2, 4, 6, 1, 2, 3, 4, 5}. If the call instead had
been append(list2, list1), the method would return an array containing
{1, 2, 3, 4, 5, 2, 4, 6}
Help is greatly appreciated. Thanks.
package iran;
public class ExampleTest {
//https://telegram.me/javalike
public int[] append(int[] array1, int[] array2) {
int array[] = new int[array1.length + array2.length];
int counter = 0;
int flage = 0;
for (int i = 0; i < array.length; i++) {
if (i < array1.length) {
array[i] = array1[counter];
counter++;
} else {
if (flage == 0) {
counter = 0;
flage = 1;
}
array[i] = array2[counter];
counter++;
}
}
return array;
}
public static void main(String[] args) {
ExampleTest t = new ExampleTest();
int a[] = { 2, 4, 6 };
int b[] = { 1, 2, 3, 4, 5 };
int c[] = t.append(b, a);
for (int i = 0; i < c.length; i++) {
System.out.print(c[i] + " ");
}
}
}
result:
1 2 3 4 5 2 4 6
Try this.
static int[] append(int[]... a) {
return Stream.of(a)
.flatMapToInt(IntStream::of)
.toArray();
}
and
int[] a = {2, 4, 6};
int[] b = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(append(a, b)));
result:
[2, 4, 6, 1, 2, 3, 4, 5]
You can also append three or more arrays.
If you are looking for the best performance, you can use native methods like System.arraycopy() instead of a loop.
public static int[] append(int[] a, int[] b)
{
int[] merged = new int[a.length + b.length];
System.arraycopy(a, 0, merged, 0, a.length);
System.arraycopy(b, 0, merged, a.length, b.length);
return merged;
}
But not coming up with your own "manual" solution could defeat the purpose of this assignment.
This works, and is fairly self-explanatory:
int[] append(int[] ary1, int[] ary2) {
int[] arrayOut = new int[ary1.length + ary2.length];
for(int i = 0; i<ary1.length; i++) {
arrayOut[i] = ary1[i];
}
for(int i = ary1.length; i< (ary1.length + ary2.length); i++) {
arrayOut[i] = ary2[i - ary1.length];
}
return arrayOut;
}

Java - Return an array from array with two given indexes

Let's say I have an array:
int[] values = {1, 2, 3, 4, 5, 6, 7 , 8, 9, 0};
With two indexes (let's say 2 and 5), I want to be able to return array from indexes 2 to 5 from the variable values given above. The final output should be this:
newValues[] = {3, 4, 5, 6};
Also, how would this procedure be used with multi dimensional arrays?
I would have googled this, but I'm not sure what to google, so I came here.
Use java.util Arrays class. Use copyOfRange(int[] original, int from, int to) method:
newValues[] = Arrays.copyOfRange(values, 2, 6);
Try the following
public static void main(String[] args)
{
int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int start = 2, end = 5; // Index
int[] newValues = new int[end - start + 1]; // Create new array
for (int i = start; i <= end; i++) {
newValues[i - start] = values[i]; // Assign values
}
// Print newValues
for (int v : newValues) {
System.out.print(v + " ");
}
}
Output:
3 4 5 6
Try the following for 2D arrays:
public int[][] getRange(int[][] src, int x, int y, int x2, int y2) {
int[][] ret = new int[x2-x+1][y2-y+1];
for(int i = 0; i <= x2-x; i++)
for(int j = 0; j <= y2-y; j++)
ret[i][j] = src[x+i][y+j];
return ret;
}
For 1D Arrays, Arrays.copyOfRange() should be fine and for more dimensions you can simply add more params and for loops
You can use the following :
int[] values = {1, 2, 3, 4, 5, 6, 7 , 8, 9, 0};
int newValues[] = new int[4];
System.arraycopy(values,1,newValues,0,4)
Here's the complete code :
public class CopyRange {
public static void main (String...args){
int[] values = {1, 2, 3, 4, 5, 6, 7 , 8, 9, 0};
int newValues[] = new int[4];
System.arraycopy(values,1,newValues,0,4);
for (int i =0;i <newValues.length;i++)
System.out.print(newValues[i] + " ");
}
}
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

How to add an element to Array and shift indexes?

I need to add an element to Array specifying position and value.
For example, I have Array
int []a = {1, 2, 3, 4, 5, 6};
after applying addPos(int 4, int 87) it should be
int []a = {1, 2, 3, 4, 87, 5};
I understand that here should be a shift of Array's indexes, but don't see how to implement it in code.
The most simple way of doing this is to use an ArrayList<Integer> and use the add(int, T) method.
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
// Now, we will insert the number
list.add(4, 87);
This should do the trick:
public static int[] addPos(int[] a, int pos, int num) {
int[] result = new int[a.length];
for(int i = 0; i < pos; i++)
result[i] = a[i];
result[pos] = num;
for(int i = pos + 1; i < a.length; i++)
result[i] = a[i - 1];
return result;
}
Where a is the original array, pos is the position of insertion, and num is the number to be inserted.
Jrad solution is good but I don't like that he doesn't use array copy. Internally System.arraycopy() does a native call so you will a get faster results.
public static int[] addPos(int[] a, int index, int num) {
int[] result = new int[a.length];
System.arraycopy(a, 0, result, 0, index);
System.arraycopy(a, index, result, index + 1, a.length - index - 1);
result[index] = num;
return result;
}
You must make a new array, use System.arraycopy to copy the prefix and suffix, and set that one slot to the new value.
If you prefer to use Apache Commons instead of reinventing the wheel, the current approach is this:
a = ArrayUtils.insert(4, a, 87);
It used to be ArrayUtils.add(...) but that was deprecated a while ago. More info here: 1
I smell homework, so probably an ArrayList won't be allowed (?)
Instead of looking for a way to "shift indexes", maybe just build a new array:
int[] b = new int[a.length +1];
Then
copy indexes form array a counting from zero up to insert position
...
...
//edit: copy values of course, not indexes
Unless I'm missing something, the question is not about increasing the array size. In the example the array size remains the same. (Like a bit shift.)
In this case, there is really no reason to create a new array or to copy it. This should do the trick:
static void addPos(int[] array, int pos, int value) {
// initially set to value parameter so the first iteration, the value is replaced by it
int prevValue = value;
// Shift all elements to the right, starting at pos
for (int i = pos; i < array.length; i++) {
int tmp = prevValue;
prevValue = array[i];
array[i] = tmp;
}
}
int[] a = {1, 2, 3, 4, 5, 6};
addPos(a, 4, 87);
// output: {1, 2, 3, 4, 87, 5}
Here is a quasi-oneliner that does it:
String[] prependedArray = new ArrayList<String>() {
{
add("newElement");
addAll(Arrays.asList(originalArray));
}
}.toArray(new String[0]);
org.apache.commons.lang3.ArrayUtils#add(T[], int, T) is deprecated in newest commons lang3, you can use org.apache.commons.lang3.ArrayUtils#insert(int, T[], T...) instead.
Deprecated this method has been superseded by insert(int, T[], T...) and may be removed in a future release. Please note the handling of null input arrays differs in the new method: inserting X into a null array results in null not X
Sample code:
Assert.assertArrayEquals
(org.apache.commons.lang3.ArrayUtils.insert
(4, new int[]{1, 2, 3, 4, 5, 6}, 87), new int[]{1, 2, 3, 4, 87, 5, 6});
Have a look at commons. It uses arrayCopy(), but has nicer syntax. To those answering with the element-by-element code: if this isn't homework, that's trivial and the interesting answer is the one that promotes reuse. To those who propose lists: probably readers know about that too and performance issues should be mentioned.
int[] b = new int[a.length +1];
System.arraycopy(a,0,b,0,4);
//System.arraycopy(srcArray, srcPosition, destnArray, destnPosition, length)
b[4]=87;
System.arraycopy(a,4,b,5,2);
b array would be created as {1, 2, 3, 4, 87, 5,6};
Try this
public static int [] insertArry (int inputArray[], int index, int value){
for(int i=0; i< inputArray.length-1; i++) {
if (i == index){
for (int j = inputArray.length-1; j >= index; j-- ){
inputArray[j]= inputArray[j-1];
}
inputArray[index]=value;
}
}
return inputArray;
}
System.arraycopy is more performant but tricky to get right due to indexes calculations. Better stick with jrad answer or ArrayList if you don't have performance requirements.
public static int[] insert(
int[] array, int elementToInsert, int index) {
int[] result = new int[array.length + 1];
// copies first part of the array from the start up until the index
System.arraycopy(
array /* src */,
0 /* srcPos */,
result /* dest */,
0 /* destPos */,
index /* length */);
// copies second part from the index up until the end shifting by 1 to the right
System.arraycopy(
array /* src */,
index /* srcPos */,
result /* dest */,
index + 1 /* destPos */,
array.length - index /* length */);
result[index] = elementToInsert;
return result;
}
And JUnit4 test to check it works as expected.
#Test
public void shouldInsertCorrectly() {
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 3}, 2, 1));
Assert.assertArrayEquals(
new int[]{1}, insert(new int[]{}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{2, 3}, 1, 0));
Assert.assertArrayEquals(
new int[]{1, 2, 3}, insert(new int[]{1, 2}, 3, 2));
}
public class HelloWorld{
public static void main(String[] args){
int[] LA = {1,2,4,5};
int k = 2;
int item = 3;
int j = LA.length;
int[] LA_NEW = new int[LA.length+1];
while(j >k){
LA_NEW[j] = LA[j-1];
j = j-1;
}
LA_NEW[k] = item;
for(int i = 0;i<k;i++){
LA_NEW[i] = LA[i];
}
for(int i : LA_NEW){
System.out.println(i);
}
}
}
Following code will insert the element at specified position and shift the existing elements to move next to new element.
public class InsertNumInArray {
public static void main(String[] args) {
int[] inputArray = new int[] { 10, 20, 30, 40 };
int inputArraylength = inputArray.length;
int tempArrayLength = inputArraylength + 1;
int num = 50, position = 2;
int[] tempArray = new int[tempArrayLength];
for (int i = 0; i < tempArrayLength; i++) {
if (i != position && i < position)
tempArray[i] = inputArray[i];
else if (i == position)
tempArray[i] = num;
else
tempArray[i] = inputArray[i-1];
}
inputArray = tempArray;
for (int number : inputArray) {
System.out.println("Number is: " + number);
}
}
}

Getting the array length of a 2D array in Java

I need to get the length of a 2D array for both the row and column. I’ve successfully done this, using the following code:
public class MyClass {
public static void main(String args[])
{
int[][] test;
test = new int[5][10];
int row = test.length;
int col = test[0].length;
System.out.println(row);
System.out.println(col);
}
}
This prints out 5, 10 as expected.
Now take a look at this line:
int col = test[0].length;
Notice that I actually have to reference a particular row, in order to get the column length. To me, this seems incredibly ugly. Additionally, if the array was defined as:
test = new int[0][10];
Then the code would fail when trying to get the length. Is there a different (more intelligent) way to do this?
Consider
public static void main(String[] args) {
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
System.out.println(foo.length); //2
System.out.println(foo[0].length); //3
System.out.println(foo[1].length); //4
}
Column lengths differ per row. If you're backing some data by a fixed size 2D array, then provide getters to the fixed values in a wrapper class.
A 2D array is not a rectangular grid. Or maybe better, there is no such thing as a 2D array in Java.
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
int[][] test;
test = new int[5][];//'2D array'
for (int i=0;i<test.length;i++)
test[i] = new int[i];
System.out.println(Arrays.deepToString(test));
Object[] test2;
test2 = new Object[5];//array of objects
for (int i=0;i<test2.length;i++)
test2[i] = new int[i];//array is a object too
System.out.println(Arrays.deepToString(test2));
}
}
Outputs
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
The arrays test and test2 are (more or less) the same.
It was really hard to remember that
int numberOfColumns = arr.length;
int numberOfRows = arr[0].length;
Let's understand why this is so and how we can figure this out when we're given an array problem. From the below code we can see that rows = 4 and columns = 3:
int[][] arr = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3} };
arr has multiple arrays in it, and these arrays can be arranged in a vertical manner to get the number of columns. To get the number of rows, we need to access the first array and consider its length. In this case, we access [1, 1, 1, 1] and thus, the number of rows = 4. When you're given a problem where you can't see the array, you can visualize the array as a rectangle with n X m dimensions and conclude that we can get the number of rows by accessing the first array then its length. The other one (arr.length) is for the columns.
Java allows you to create "ragged arrays" where each "row" has different lengths. If you know you have a square array, you can use your code modified to protect against an empty array like this:
if (row > 0) col = test[0].length;
If you have this array:
String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
{{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};
You can do this:
example.length;
= 2
example[0].length;
= 2
example[1].length;
= 2
example[0][1].length;
= 3
example[1][0].length;
= 4
There's not a cleaner way at the language level because not all multidimensional arrays are rectangular. Sometimes jagged (differing column lengths) arrays are necessary.
You could easy create your own class to abstract the functionality you need.
If you aren't limited to arrays, then perhaps some of the various collection classes would work as well, like a Multimap.
.length = number of rows / column length
[0].length = number of columns / row length
Example Array 1:
int arr[][] = { { 1, 3, 1, 5 },
{ 2, 2, 4, 1 },
{ 5, 0, 2, 3 },
{ 0, 6, 1, 2 } };
Example Array 2:
int arr[][] = { { 1, 3, 1 },
{ 2, 2, 4 },
{ 5, 0, 2 },
{ 0, 6, 1 } };
Below function will work for any Symmetric and Asymmetric Array Matrix
row_Count = arr.length
column_Count = arr[0].length
Try this following program for 2d array in java:
public class ArrayTwo2 {
public static void main(String[] args) throws IOException,NumberFormatException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[][] a;
int sum=0;
a=new int[3][2];
System.out.println("Enter array with 5 elements");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[0].length;j++)
{
System.out.print(a[i][j]+" ");
sum=sum+a[i][j];
}
System.out.println();
//System.out.println("Array Sum: "+sum);
sum=0;
}
}
}
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
double[][] test = { {100}, {200}, {300}, {400}, {500}, {600}, {700}, {800}, {900}, {1000}};
int [][] removeRow = { {0}, {1}, {3}, {4}, };
double[][] newTest = new double[test.length - removeRow.length][test[0].length];
for (int i = 0, j = 0, k = 0; i < test.length; i++) {
if (j < removeRow.length) {
if (i == removeRow[j][0]) {
j++;
continue;
}
}
newTest[k][0] = test[i][0];
k++;
}
System.out.println(Arrays.deepToString(newTest));
}
}
With Java 8, allow you doing something more elegant like this:
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
int length = Arrays.stream(array).max(Comparator.comparingInt(ArrayUtils::getLength)).get().length
int rows=arr.length; //For knowing No of rows
int cols=arr[0].length; //For Knowing No of columns
Run This code... and Understand...
public class Store2darrays {
public static void main(String args[]) {
int[]arr={1,2,3,4};
System.out.println(arr.length);
int[][] arr2d={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
System.out.println(arr2d.length);
System.out.println(arr2d);
System.out.println(arr2d[0]);
System.out.println(arr2d[1]);
System.out.println(arr2d.length);
System.out.println(arr2d[0].length); }
}
public class Array_2D {
int arr[][];
public Array_2D() {
Random r=new Random(10);
arr = new int[5][10];
for(int i=0;i<5;i++)
{
for(int j=0;j<10;j++)
{
arr[i][j]=(int)r.nextInt(10);
}
}
}
public void display()
{
for(int i=0;i<5;i++)
{
for(int j=0;j<10;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
}
public static void main(String[] args) {
Array_2D s=new Array_2D();
s.display();
}
}

Categories