What determines the value of array.length for a 2D array? - java

Working in Java, suppose I have made a 2D array which is 30 by 50 units, like this:
public Array() {
int[][] array = new int[30][50];
}
and then I do this:
int rows = array.length;
int columns = array[1].length;
why does array.length get me a value of 30? Could the length not also be 50? Similarly, how then does array[1].length work out to be 50?
I have seen this answered elsewhere but I didn't understand the answer (beginner in Java here).
EDIT: This is how it was explained to me before, which I didn't understand. "when we refer to array.length, we get the length of the larger list, which is 30. When we refer to array[1].length, we get the length of the small list with index 1 in the large list, which is the second small list in the large list. This will have a value of 50."

If you rewrite to this, maybe it gets clearer
public Array() {
int[][] array = new int[30][];
array[0] = new int[50];
array[1] = new int[50];
// ... you may use a loop, but to make it explicit
array[29] = new int[50];
}
When you declare an array you MUST indicate at least the first dimension (30).
In your example all elements of the first dimension holds an array reference to an array with 50 elements.
You can have diferent lengths also:
public Array() {
int[][] array = new int[30][];
array[0] = new int[5];
array[1] = new int[7];
// ...
}

Consider this simple example
array[3][5];
array[number_of_row][number_of_column];
array[3][5] means 3*5 matrix which is
[0,0][0,1][0,2][0,3][0,4]
[1,0][1,1][1,2][1,3][1,4]
[2,0][2,1][2,2][2,3][2,4]
here you can clearly see that 3*5 matrix has 3 rows and 5 columns,
that's also means each row has 5 columns. So, array.length means
number of rows which is 3 and array[1].length means number of columns
in row position 1 which is 5
This logic is same as array[30][50]

First you need to know that a 2D array is actually a 1D array with each element in that array is another 1D array.
a[0] = [0][1][2][3]
a[1] = [0][1][2][3]
a[2] = [0][1][2][3]
a[3] = [0][1][2][3]
so length will get the length or the array being called at
i.e a.length will be the length of a, not the length of the array assigned at element 0 or 1 , ...n in a
also note the arrays created in each element of the 1D array a could be of different length. so calling a.length will not be accurate if always returned the length of 1st row i.e: a[0].length
int a[][] = new int[4][];
a[0] = new int [10];
a[1] = new int [7];
a[2] = new int [11];
a[3] = new int [30];

Related

How to partition a given list of numbers to N array where the sum of each array is closest to a specific number, M?

Given array int[] arr = {3,4,7,8,9,10,12,14,14,25,25,28,30,32}
Given specific number int M = 33
The question is how do I partition the array arr to N amount of arrays so that each sum of the array is trying to reach 33 (since M=33). My main purpose is just to get a lower value of N and the final result looks something like this:
arr1 = {32}
arr2 = {3,30}
arr3 = {4,28}
arr4 = {8,25}
arr5 = {7,25}
arr6 = {4,14}
arr7 = {9,12,10}
This results me in N=7 arrays, correct me if you get lower than 7 arrays as I am trying to get as low amount of N as possible.
Constraint:
Only can use each element once in the array given
firstly, I suggest using brute force to iterate through all elements of the array that sum up 32, then, each time arr[i] + arr[j] = 32 return it as a new object, return new int[] {}; (the method should be an array return type)

Randomly prints elements in an array

Is there a way where you can use Math.random to prints the element in a given array?
int[] list = new int[] {1,2,3};
So the output will be like
2,1,3
or
3,1,2
or
2,3,1
Perhaps you can approach it by shuffling your array then print it. If the original should not be modified, you can make a copy and then shuffle the copy.
There are well-known algorithms for shuffling array (or a deck of cards). One can be found here. An implementation in java looks like this:
static void shuffleArray(int []array) {
int length = array.length;
for (int i = length -1; i > 0; i--) {
// generate a random 0 <= j < i
int j = (int)(Math.random() * i);
// swap elements at i and j
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
The approach proposed in most answers is extremely inefficient, as it works in O(N2) time. Think about it: at first you'll generate unused indexes with one attempt, but closer to the end, when almost all array is processed, it will require nearly N steps to generate next unused index.
The optimal O(N) approach is to create shuffled array of indexes (0..N) where each index appears only once and then process your original array in the order of shuffled indexes. Each step requires O(N) time, so the whole algorithm is O(N).
int[] input = new int[]{5, 4, 3, 6, 2, 1};
int []indices = new int[input.length];
//Fisher-Yates shuffle
Random rnd = new Random();
for (int i = 0; i < indices.length; i++) {
int j = rnd.nextInt(i + 1);
indices[i] = indices[j];
indices[j] = i;
}
for (int i : indices) {
System.out.println(input[i]);
}
I didn't use Collections.shuffle, as it would require usage of Collection and thus wrapped Integer elements, which is very inefficient comparing to the plain int array.
Also, if you are ok with modifying your original array, you can just shuffle it in place (using the same Fisher-Yates shuffle) and then consume it while traversing.
UPD: Replaced shuffling array of indices with shuffled initialization.
Since you have java 8, you can take advantage of the beautiful Stream API.
In short, you can do:
new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));
Where 1 is the lowest int generated (inclusive) and 500 is the highest (exclusive). limit means that your stream will have a length of 500, maybe in that argument you want to put list.length.
For your case:
int[] list = new int[] {1,2,3,4,5,6};
new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p]));
Prints: 5 2 5 4 6 3 3 5 6 4 (Obviously will not print the same numbers for you)
Create a random integer that may be as high as the length of the array - 1. If the random integer is equal to a previous used random integer -- known by storing used integers in an array -- create a new random integer. Otherwise, print the string correlated with that index specified by the random integer. If the length of the array storing the used random integers is equal to the length of the array of strings, stop the process.
This should print all your strings only once each and randomly.
Here is the solution
public static void main(String[] args) {
int[] list = new int[] { 1, 2, 3 };
int[] aux = new int[list.length];
int countTimes = 0;
while (countTimes < list.length) {
int position = new Random().nextInt(list.length);
if (aux[position] != list[position]) {
System.out.println(list[position]);
aux[position] = list[position];
countTimes++;
}
}
}
As I said in the comments. This answer will work.. All you need to do is track the indices that it accessed so you don't repeat them or remove that element from the array.
void printRandom(int[] array) {
if (array.length == 0)
return;
Random rand = new Random();
int rnd = rand.nextInt(array.length);
int element = array[rnd];
array = ArrayUtils.removeElement(array, element);
System.out.print(element);
printRandom(array);
}
Just repeat this process until all elements are removed. Obviously add checks to prevent errors and keep in mind I haven't used JAVA in a long time so post back if you have issues!
Lastly keep in mind this deletes the array so you may want to wrap this code in a function and then copy the array as a local variable so you can reuse the original as needed
In this case we can print random value from array using like below :
Steps:
Create list object of Integer to hold printed indices
Get random number and check whether this index is already printed or not
if not printed then add it in list and print value from array using this index
if list size and array length is equal then terminate the loop
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomIndices {
public static void main(String[] args) {
int[] list = new int[]{1, 2, 3};
Random random = new Random();
List<Integer> randomIndices = new ArrayList<>(); //to hold indices which are already printed
boolean isRemain = true;
while (isRemain) {
int randomIndex = random.nextInt(list.length);
if (!randomIndices.contains(randomIndex)) { //check random index value of array is printed or not
randomIndices.add(randomIndex);
System.out.println(list[randomIndex]);
}
if (randomIndices.size() == list.length) {
isRemain = false;
}
}}
}
Implement a simple "do while" statement to prevent duplicate numbers from showing up out of your array (I used a StringArray - but an IntegerArray would work the same way - as a side note, I can place the complete code up here but didn't want to do so if it didn't apply. I use a drop-down to select how many random words to generate - then display that set of true RANDOM words (non-repeated):
final Random rand1 = new Random();
final Random rand2 = new Random();
final int rndInt1 = rand1.nextInt(getResources().getStringArray(R.array.words).length);
int rndInt2 = rand2.nextInt(getResources().getStringArray(R.array.words).length);
if (rndInt1 == rndInt2){
do {
rndInt2 = rand2.nextInt(getResources().getStringArray(R.array.words).length);
}while (rndInt1 == rndInt2);//if indexes are equal - re-run the array search
}
outString = getResources().getStringArray(R.array.words)[rndInt1];
outString += ", " + getResources().getStringArray(R.array.words)[rndInt2];//concatenate the list
textWord = (TextView) findViewById(R.id.textWords);//An empty text field in my layout
textWord.setText(outString);//Set that empty text field to this string of random array elements

What does a method with (int[] []) mean?

We are given some code snippets to look at and figure out what the code does/will do.
I understand methods and methods with arrays but I have never seen methodName(int[][] m) with two [][]
What does this mean? an array within an array?
int[][] in the method signature refers to a double array of integers. You can think of a double integer array as being a matrix of int values.
Taking your example 2D array:
int[][] in = {{2, 0, 2}, {3, 1, 2}, {1, 8, 4}};
This array has the following properties:
System.out.println(in.length); // prints 3 (number of arrays inside 'in')
System.out.println(in[0].length); // prints 3 (number of ints in first array)
System.out.println(in[1].length); // also prints 3 (number of ints in second array)
Here is a visual to show you how accessing this array works:
int a = 1;
int b = 0;
Then in[a][b] == in[1][0] == 3:
2 0 2
{3 1 2} <-- a = 1 (second subarray)
1 8 4
{3 1 2}
^-- b = 0 (first element in that subarray)
The first index a chooses the subarray, and the index b chooses the element inside the subarray.
It represents multi dimensional arrays (AKA arrays or arrays) of given data type.
Think hierarchical to understand it the best way.
If you have int[3][2], it means,
It holds value for each of the following index.
int[0][0]
int[0][1]
int[1][0]
int[1][1]
int[2][0]
int[2][1]
Hope it will help. I struggled a lot to understand it when i was a beginner.
Possible assign is
int[3][2] iValue = {{00,01}, {10,11}, {20, 21}}
Thanks for the correction.
methodName(int[] []) is an array of arrays. In response to all the comments, I tested it in eclipse and the length is 3.
In many programming languages (including Java), it is possible to create (and use) an array of arrays. In Java (specifically), all arrays are Object instances. Consider
Object intArray1 = new int[10];
Object intArray2 = new int[10];
Object intArray3 = new int[10];
Then you might have
Object[] arrs = { intArray1, intArray2, intArray3 };
or even
Object arrs = new Object[] { intArray1, intArray2, intArray3 };
JLS-15.10.1 Run-Time Evaluation of Array Creation Expressions says (in part)
Otherwise, if n DimExpr expressions appear, then array creation effectively executes a set of nested loops of depth n-1 to create the implied arrays of arrays.
A multidimensional array need not have arrays of the same length at each level.
Finally, there is Arrays.deepToString(Object[]) the Javadoc says (in part)
Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.
In Java, "int [ ][ ]" stands for a 2-dimensional integer array. To make it easy to understand, simply we can compare 2-d integer array with a simple 1-d integer array;
1) Down below, a 1-d int array is initialized;
int[] arr1d = { 1,2,3 };
2) And on this one, a 2-d int array is initialized;
int[][] arr2d = { {1,2,3}, {4,5,6} };
It is important to understand the structure of 2d arrays. If you print the length of the arr2d , you will get 2 the rows of the array which is 2.
System.out.println(arr2d[].length);
You will get the length of the outer array, which is actually row count of the array.
To get the inner array length, which is actually the column count;
System.out.println(arr2d[0].length);
Notice that we take the first row, and get the length of the inner array and print the column number.
To get familiar with the usage of the 2d array in a method, you can check this out;
private static void printIntegerArray(int[][] intArray) {
for(int i = 0; i < intArray.length; i++ ) {
for(int j = 0; j < intArray[i].length; j++ ) {
System.out.printf("%3d ", intArray[i][j]);
}
System.out.println();
}
}
In this static method, int[][] intArray is the only parameter which is obviously a 2 dimensional int array. There are two nested for loops to print the array as a matrix. The outer loop is traversing the rows and the inner loop is traversing on the inner loop.
Here is the complete example for the 2D Method usage;
public class Test2DArray {
public static void main(String[] args) {
//Init 2d integer list
int simpleArray[][] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} };
//Length of outer array which is actually Row Count;
System.out.println("Rows : " + simpleArray.length);
//Length of inner array which is actually Column Count;
//Notice that we take the first Row to get the Column length
System.out.println("Columns: " + simpleArray[0].length);
//Call the printIntegerList method with int[][] parameter
printIntegerArray(simpleArray);
}
private static void printIntegerArray(int[][] intArray) {
for(int i = 0; i < intArray.length; i++ ) {
for(int j = 0; j < intArray[i].length; j++ ) {
System.out.printf("%3d ", intArray[i][j]);
}
System.out.println();
}
}
}
And the output to the console is as below;
Rows : 3
Columns: 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

How to trim out an array of integers in Java?

Let's that I have a number N. N will be the size of the array.
int numArray [] = new numArray[N];
However, the contents of the array will hold every other number from 1 to positive N. This means that the entire size N array will not be full after that for loop. So after the for loop, I want to trim (or resize) the array so that there will no longer be any empty slots in the array.
Example :
Let's say N = 5;
That means, after the for loop, every other number from 1 to 5 will be in the array like so:
int arr[] = new int[N];
int arr[0]=1;
int arr[1]=3;
int arr[2]= null;
int arr[3]= null;
int arr[4]= null;
Now, I want to trim (or resize) after the for loop so that the indexes that hold null will be gone and then the array should be:
int arr[0]=1;
int arr[1]=3;
The size of the array is now 2.
You can't trim an array. The fastest approach is just to copy it into a smaller one, using System.arraycopy, which is almost always much faster than a for loop:
int somesize = 5;
int[] numArray = new int[somesize];
//code to populate every other int into the array.
int[] smallerArray = new int[somesize/2];
//copy array into smaller version
System.arraycopy(numArray, 0, smallerArray, 0, somesize / 2);
You can't change the size of an array in Java after it has been created.
What you can do however, is to create a new array of the size that you need.
Another important point is that you are creating an array of a primitive: int. Primitives are not objects and you cannot assign the value null to a primitive.
You need to create an array of java.lang.Integer if you want to be able to set entries in it to null.
Integer[] numArray = new Integer[N];
Thanks to a Java feature called auto-boxing, almost all code that works with primitive int values, also works with Integer values.
Steps:
Use Integer[] instead of int[]
Calculate the size that you need (count non-null entries in original array)
Allocate a new array of the size that you need
Loop over the old array, and copy every non-null value from it to the new array.
Code:
Integer[] oldArray = ...;
// Step 2
int count = 0;
for (Integer i : oldArray) {
if (i != null) {
count++;
}
}
// Step 3
Integer[] newArray = new Integer[count];
// Step 4
int index = 0;
for (Integer i : oldArray) {
if (i != null) {
newArray[index++] = i;
}
}
I think there is a bit shorter way to do the trimming itself.
Whats left is to find the proper index.
You can do:
int someIndex = Arrays.asList(arr).indexOf(null);
arr = Arrays.copyOfRange(arr,0,someIndex);
You surely better of with some more appropriate data structure, for example a list or a set depending on what's your intention with it later. That way you don't even need to create an N sized structure just so you'd have to reduce it anyway. Rather you create an empty list and add the elements that you actually need
import java.util.Arrays;
public static void main( String[] args )
{
int[] nums2 = {9,4,1,8,4};
nums2 =Arrays.copyOf(nums2,3);
for (int i : nums2) {
System.out.print(i+" ");
}
}
//Output
9 4 1

double row length of 2D array

I'm trying to double the length of a 2D array as I add values to it. I know for a 1D an array the code for this is:
int oneD[] = new int[10];
//fill array here
oneD = Arrays.copyOf(oneD, 2 * oneD.length);
so if I have a 2D array and only want to double the amount of rows while keeping say 2 columns I figured I would just do this:
int twoD[][] = new int[10][2];
//fill array here
twoD = Arrays.copyOf(twoD, 2* twoD.length);
This however does not seem to work for the 2D array. How does one go about doubling the length of a 2D array. In this case to make it [20][2] instead.
A 2D array in Java is an array of arrays. For doubling it, you'll have to manually iterate over each row in the array and copy all of its columns in turn.
In your case something like this would do the job:
public static <T> T[][] copyOf(T[][] array, int newLength) {
// ensure that newLength >= 0
T[][] copy = new T[newLength][];
for (int i = 0; i < copy.length && i < array.length; i++) {
copy[i] = Arrays.copyOf(array[i], array[i].length);
// this should also work, just not create new array instances:
// copy[i] = array[i];
}
return copy;
}
And you could call this method, just like you called Arrays.copyOf()

Categories

Resources