counting occurrence of 2d array in java - java

This is the question i am trying to solve:
Write a class called ArrayHistogram, which contains a main method and a static method called histogram, which has the following signature:
public static int[] histogram(int[][] arrayA)
In the main method, declare and initialize a two dimensional array, call it arrayA. This array must contain some non-negative integer numbers. The histogram method accepts arrayA and puts the frequency of occurrence of elements of arrayA into a one dimensional array (histA) and returns histA. Frequency of occurrence means, the number of times an element occurs in the array. Your program should work for a ragged array, as well. Your program should determine the size of the histA automatically, before declaring the variable histA.
Hint: Figure 1 shows a sample 2D array(arrayA) and the corresponding histA. histA[0] = 2 shows that 0 occurred twice in A. Or, histA[3] = 1, shows that number 3 appeared once in A.
I have done this so far
public class ArrayHistogram
{
public static void main (String[]args)
{
// declearing and initializing a 2D array.
int [][] arrayA = {{5,8,8,4,3},{1,4,2,2,3},{7,4,6,6,9}};
histogram(arrayA);
}
public static int[] histogram (int [][] arrayA)
{ // nested for loop to go through the array.
int max = 0;
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
if ( arrayA[row][col]> max ){
max = arrayA[row][col];
}
}
}
int histA[] = new int [max];
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
histA[arrayA[row][col]]++;
}
}
System.out.println(histA);
return histA;
}
}
This line:
histA[arrayA[row][col]]++;
shows a java.lang.ArrayIndexOutOfBoundsException
First am I doing this right?
If not how should I make it happen?

Keep in mind that arrays are indexed starting at 0, so your max value is not going to be an index available in your histA array. One way to fix this is create your array like so:
int histA[] = new int[max + 1];
In your second loop, when you hit row being 2 and col being 4 it's going to attempt to use histA[9] which isn't a valid index in that array unless you define your array to be of size 10, which in your case is max + 1.

length is an attribute of array objects which returns the size. Now since you are looping your array starting from 0 to the length of array, its referring to the index of array which doesn't even exists. Hence an ArrayIndexOutOfBoundException.
Just update your for loop termination expression to arrayA.length-1 and arrayA[row].length-1 and it will all be working fine.
Also for all such exceptions just check their Java Doc and you will get your answer.

Related

Delete the highest number of an array

First I created a random array then I decided to create another array to save the number except the highest. I got the prob when printing the array removed the highest number. I assume the issue when assigning item in b but I can't figure out. Please help :<
public static int[] deleteHighestNum(int a[]) {
int b[] = new int[a.length - 1];
for (int i = 0, j = 0; i < a.length; i++) {
if (a[i] > a[j]) {
b[j++] = a[j];
}
}
return b;
you first create a copy of the array with the .clone() method. This will be the second array you created. then you create an int x or something of this sort and set it equal to 0.
start now by iterating the array. if the number is greater then your int, replace the int.
once it is done, make another loop, that checks each value of your second array and if a number is equal to your int, delete it. done.

Why does changing one entry in a 2D array change the entire column?

//main method
int one = 1;
int[] ones = {one, one, one};
int[][] lotsofones = {ones, ones, ones};
lotsofones[0][1] = 2;
for (int[] array : lotsofones) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
/*
Expected output:
1 2 1
1 1 1
1 1 1
Actual output:
1 2 1
1 2 1
1 2 1
*/
Why is this happening? I don't understand. Why is it changing the entire column instead of just the single entry?
How do I achieve changing only one entry without initializing the 2D array differently? Is it possible?
Why is it changing the entire column instead of just the single entry?
Because each column, of each row, is the element stored in one same array object on the heap, and changing element in the array referenced with ones, will reflect that change in every other variable, which refers (or will refer) to the same array instance.
int one = 1;
int[] ones = {one, one, one}; //creates 1D array `{1, 1, 1}`
int[][] lotsofones = {ones, ones, ones}; //reuses and puts the same "ones" array, object in three indices of "lotsofones" 2D array
Therefore, changing:
lotsofones[0][1] = 2;
changes entry in ONE array object, that is referenced three times.
How do I achieve changing only one entry without initializing the 2D array differently? Is it possible?
Sure, it is. Just create 2D array by not using the same array object for every element of that 2D array. One way would look like this:
int one = 1;
int size = 3;
int[][] lotsofones = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < lotsofones[i].length; j++) {
lotsofones[i][j] = one;
}
}
lotsofones[0][1] = 2; //this will now change one particular element on one 2D array, instead of changing element in an array that is re-used over and over.
Then,
for (int[] array : lotsofones) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
will output:
1 2 1
1 1 1
1 1 1

Finding Maximum Height and Width for 2D Array of Unknown Dimensions (Java)

In Java, I'd like to get the maximum element from both dimensions of a simple image array, ie:
int getWidth(Color[][] pixels){
//return max of dimension 1
}
int getHeight(Color[][] pixels){
//return max of dimension 2
}
I know how to do this for a 1D array in Java, I would just run a for loop with the condition of i < pixels.length. However, I'm not quite sure how .length works for a 2D array, or even if it does work. How would I approach this?
Will .length still work?
A 2D array is just simply an array, where the items in it are other arrays. Since .length works on a 1D array, it will surely work on all arrays - the amount of dimensions does not matter.
However, pixels.length gives you the length of the parent array - i.e. the array that contains all of the other arrays inside it. To get the length of the second dimension, you will have to get the length of the arrays inside it.
So, how do we get the length of the 2nd dimension?
We know that all of these arrays must be the same length, so we use the one at position 0 only because it is the only one that we can be 100% sure will always exist - an array should always have at least one element.
Then, we just get the length of that array - pixels[0].length.
If we consider 2D array they it is an array holding references to other arrays.
If we consider matrix like this:
{
{1,2,3},
{4,6},
{7,7,8,9}
}
So height for above matrix is 3 = no. of rows.
Width of matrix is 4 = Max(no. of element in each array).
int getHeight(Color[][] pixels) {
return pixels.length;
}
int getWidth(Color[][] pixels) {
int maxCount = 0;
int rows = pixels.length;
for (int i = 0; i < rows; i++) {
if (maxCount < pixels[i].length) {
maxCount = pixels[i].length;
}
}
return maxCount;
}

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

Multidimensional Arrays lengths in Java

How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);

Categories

Resources