Guys, I am struggling studying for exam with the 2d array of past exam paper. I have to write a method
sumr static (int[][] v)
that returns a 2d array consisting of 2 rows and the entries of the first row sums of v and the second row is the same of the first row of v. Eg:
a = {{2,3,3}, {1,3}, {1,2}}
the method returns 2d array
b = {{8,4,3},{2,3,3}}
I first try to make my method return a 2d array, but I was having the error illegal start of expression, now I have the following code, but the last element does not print and the elements a printed all in in line, not in a matrix way... Please guys help me, my exam is tomorrow.
public class Sum
{
// int[][] a = {{2, 3, 3}, {1, 3}, {1, 2}};
public void sumr(int[][] v)
{
for(int rows = 0; rows < v.length; rows++){
for(int columns = 0; columns < v.length; columns++){
int result = v[rows][columns];
System.out.print(result + " ");
//return [][] result;
}
}
}
public int getCount(int[][] Array)
{
int result = 0; //temp location to store current count
for (int i = 0;i <= Array.length -1;i++){//loop around first array
//get the length of all the arrays in the first array
//and add them onto the temp variable
result += Array[i].length;
}
return result;
}
}
In the outer loop (after the inner loop) include:
System.out.println(); // go to next line!
And check against the inner-array length!!
int[] innerArray = v[rows];
for(int columns = 0; columns < innerArray.length; columns++){
It is:
public void sumr(int[][] v)
{
for(int rows = 0; rows < v.length; rows++){
int[] innerArray = v[rows];
for(int columns = 0; columns < innerArray.length; columns++){
int result = v[rows][columns];
System.out.print(result + " ");
//return [][] result;
}
System.out.println(); // go to next line!
}
}
Once you can iterate:
You must construct a two-items array:
1st item: "summed array"
2nd item: the same as v[0]
You must build that result.
You must build the 1st item iterating over v. Like you are trying to do. For each row (outer loop) you will iterate over the row and sum its values. So after processing each row (after the inner loop) you will have the summed value. That value must be placed into the "summed array".
Next you can build directly the result array, assigning the built sum to its first place and v[0] to the second place.
But I'm not writing code yet to let you do it ;-)
Related
Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
I am trying to find a comparable value that is common to all rows in a 2D array.
For that value, I'd like to find the minimal (> 0) number of repetitions that exist in all rows.
For example, when working with a 2D array of String:
{
{A, C, B},
{A, A, B},
{C, D, A}
}
The only value that exists in all rows is "A". The minimal number of appearances in a row is 1, so the answer would be 1 A.
Here is my code: I am trying to search each column in a row for duplicates (or triplets, etc.), determine the count for a given row and compare it to the other rows to determine the row with the lowest quantity. Also, maybe there is a more elegant approach? For some reason it is not working (Collections is a 2d String array):
public class CommonElements {
ArrayList<String> commonCollections = new ArrayList<String>();
private int comparisons = 0;
int i, j, k;
int count, lowestCount;
String previousString = "";
int row[];
String current;
public Comparable[] findCommonElements(Comparable[][] collections) {
Arrays.sort(collections[0]);
row = new int[collections[0].length];
for (i = 0; i < collections[0].length; i++) { // first row column selection
current = collections[0][i].toString();
lowestCount = 1;
for (j = 0; j < collections.length; j++) { // row
count = 0;
for (k = 0; k < collections[0].length; k++) { // column
if (current.equals(collections[j][k].toString())) { // if contains same string as first row column selected
count++;
System.out.print(count + "\n");
}
}
if (lowestCount < count) {
lowestCount = count;
}
}
}
System.out.print(lowestCount);
return collections[0];
}
public int getComparisons() {
return comparisons;
}
}
Well, first you take collections[0][i].toString() when i is 0 so that evaluates to A, then program goes through all those loops and lowestCount is set to 1. Then your first for loop moves on to B and lowestCount is reseted without it being saved anywhere. You should save your lowestCount perhaps in array or a list, and at the end of the first for loop (after 2 other for loops) add the lowestCount to that array and you will have the lowest count of every letter. If you don't want to save it you can just System.out.println("Lowest count of letter: "+current+" is: "+lowestCount);. If you want to determine the row with the lowest count you can also save it in array (row with lowest count for every letter) and set it in that if that if statement passes (if(lowestCount < count)).
I'm not sure if I understood you correctly, but there is definitely a better approach to solving this problem.
You can do like this
int[][] arr = new int[5][2];
int count =0;
for(int[] i : arr){
count = count + i.length;
}
System.out.println(count);
An integer array stores values 3,2,3,4,5. I am trying to create a program that increments these values by 2 and then saves the result into the same array using a for loop. I tried but something is wrong with my code, here:
public class ArrayClass {
int a[] = {2, 3, 3, 4, 5};
}
public class ArrayObject {
public static void main(String[] Ella) {
int a[] = new int[5];
int i;
for (i = 2; i < a.length; i = i + 2) {
a[i] = i + 2;
System.out.println(a[i]);
}
}
}
This should work:
for (i = 0; i < a.length; i++) {
a[i] += 2;
System.out.println(a[i]);
}
You see, when increasing every single value of an array, the index has to be 0 and max the array's length. By adding one to i, the indexing of the array increases by one, which means the next number will be increased by two. what you did was add two to the "i" variable which means that only 3 of the varialbes would have been changed.
Please make below change to your code.It will work.
for (i = 0; i < a.length; i++) {
a[i] = a[i] + 2;
System.out.println(a[i]);
}
The error is that when you do i = i + 2, you are just incrementing the position index, not the actual value in that position.
you need to do:
a[i] = a[i]+2;
Let me explain what a[i] is:
|3|2|3|4|5|
1 2 3 4 5
The first row are the values. The second row is the index. "Index" means the position number of each of positions in the array.
Another problem is that, when you initialise i, it need to be i=0. That is because i array indices (plural of index) always start from 0. That means that a[0] is the first position in the array That would be number 3 from your data set.
I can get a row from a 2D array in java by foreach loop like :
int[][] array = new int[5][5]
for (int[] row : array) {
for (int c : row) {
}
}
But How can I get the column form 2D array by foreach loop ? Or is this possible to get column from 2D array by foreach loop ?
Thank you.
One alternative can be
int i =0;
for (int k : array[0]){
for (int[] row : array) {
System.out.println(row[i]);
}
i++;
}
It's not possible. You'll have to use the traditional for loop :
int[][] array = new int[5][5]
for (int j = 0; j < array[0].length; j++) {
for (int i = 0; i < array.length; i++) {
int current = array[i][j];
}
}
2D array is just a conceptual meaning. in fact 2d array is a combination of multiple one-dimensional array. Therefore you cannot access the columns without using a counter. even if you use for each loop you need a counter inside.
If you need to get all the columns then you can make a loop with number of column. But in this case all the rows should have the same number of columns (elements)
public static void main(String[] args)
{
int [][] yourArray = {{1,2,3,4,5,6},//sample 2d array with 6 rows and six columns
{1,2,3,4,5,6}, //this is actually a collection of 6 different 1d arrays
{1,2,3,4,5,6},
{1,2,3,4,5,6},
{1,2,3,4,5,6},
{1,2,3,4,5,6}};
int yourColumn = 3; //example of selected column (be careful columns start from 0)
for(int[] row: yourArray)
{
System.out.println(row[yourColumn]);
}
}
How do I get the second dimension of an array if I don't know it? array.length gives only the first dimension.
For example, in
public class B {
public static void main(String [] main){
int [] [] nir = new int [2] [3];
System.out.println(nir.length);
}
}
See that code run live at Ideone.com.
2
How would I get the value of the second dimension of nir, which is 3?
which 3?
You've created a multi-dimentional array. nir is an array of int arrays; you've got two arrays of length three.
System.out.println(nir[0].length);
would give you the length of your first array.
Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).
int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
You can do :
System.out.println(nir[0].length);
But be aware that there's no real two-dimensional array in Java. Each "first level" array contains another array. Each of these arrays can be of different sizes. nir[0].length isn't necessarily the same size as nir[1].length.
use
System.out.print( nir[0].length);
look at this for loop which print the content of the 2 dimension array
the second loop iterate over the column in each row
for(int row =0 ; row < ntr.length; ++row)
for(int column =0; column<ntr[row].length;++column)
System.out.print(ntr[row][column]);
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
Here's a complete solution to how to enumerate elements in a jagged two-dimensional array (with 3 rows and 3 to 5 columns):
String row = "";
int[][] myArray = {{11, 12, 13}, {14, 15, 16, 17}, {18, 19, 20, 21, 22}};
for (int i=0; i<myArray.length; i++) {
row+="\n";
for (int j = 0; j<myArray[i].length; j++) {
row += myArray[i][j] + " ";
}
}
JOptionPane.showMessageDialog(null, "myArray contains:" + row);
nir[0].length
Note 0: You have to have minimum one array in your array.
Note 1: Not all sub-arrays are not necessary the same length.
Assuming that the length is same for each array in the second dimension, you can use
public class B {
public static void main(String [] main){
int [] [] nir= new int [2] [3];
System.out.println(nir[0].length);
}
}
Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size.
so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.
Hope that helps..:)
Expansion for multi-dimension array total length,
Generally for your case, since the shape of the 2D array is "squared".
int length = nir.length * nir[0].length;
However, for 2D array, each row may not have the exact same number of elements.
Therefore we need to traverse through each row, add number of elements up.
int length = 0;
for ( int lvl = 0; lvl < _levels.length; lvl++ )
{
length += _levels[ lvl ].length;
}
If N-D array, which means we need N-1 for loop to get each row's size.
//initializing few values
int[][] tab = new int[][]{
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}
};
//tab.length in first loop
for (int row = 0; row < tab.length; row++)
{
//tab[0].length in second loop
for (int column = 0; column < tab[0].length; column++)
{
//printing one value from array with space
System.out.print(tab[row][column]+ " ");
}
System.out.println(); // new row = new enter
}