find number of columns in a 2D array Java - java

I'm new to java and am trying to find the transpose of a matrix X with m rows and x columns. I'm not familiar with java syntax but I think I can access the number of rows using double[x.length] but how do I figure out the number of columns? Here is my code:
import stdlib.StdArrayIO;
public class Transpose {
// Entry point
public static void main(String[] args) {
double[][] x = StdArrayIO.readDouble2D();
StdArrayIO.print(transpose(x));
}
// Returns a new matrix that is the transpose of x.
private static double[][] transpose(double[][] x) {
// Create a new 2D matrix t (for transpose) with dimensions n x m, where m x n are the
// dimensions of x.
double[][] t = new double[x.length][x[1.length]]
// For each 0 <= i < m and 0 <= j < n, set t[j][i] to x[i][j].
// Return t.
}
}
Also, I was trying to figure it out by printing a 2D list in a scrap file but It wouldn't work for some reason, where is what I had:
import stdlib.StdArrayIO;
import stdlib.StdOut;
public class scrap {
public static void main(String[] args){
double[][] x = new double[10][20];
StdOut.println(x.length);
}
}
Could you point out what I was doing wrong? It kept waiting on input. I could also use any other tips that would help, I am transitioning from Python.

In Java, a two-dimensional array is merely an array of arrays. This means the length of any of the array elements can be checked to find the number of columns. Using your example, this would be:
double[][] t = new double[x[0].length][x.length];
This should be sufficient for your matrix situation, where we can assume the outer array is not empty, and all inner arrays have the same length.
Note that this is not guaranteed to work in general. If the outer array is empty, there are no inner arrays to check, so the number of columns isn't defined and can't be determined. Secondly, there is no guarantee that all inner arrays of a given array of arrays in Java are all the same length. They will be using the new double[x][y] syntax, but the array could have been created using another mechanism or one of the inner arrays could have been replaced with an array of a different length.

class TwoDmArray {
public static void main(String[] args) {
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } };
for(int i = 0; i < 2; i++) { // It represents row
for(int j = 0; j < 3; j++) { // It represents column
System.out.print(arr[i][j]);
if(j == 2) { // When column index will be 2 then will print elements in new line
System.out.println();
}
}
}
}
}
OUTPUT : 123
456
Explanation : Here array has 2 rows and 3 columns so, matrix will be in row and column form.

Related

Arrays and For-loop - Incorrect output while printing Random elements

I am pretty new in this world, and I must say sometimes things that looks easy are pretty harsh.
I am stuck with a task that entails dealing with an array and for-loops.
I should iterate over the array and for every iteration step print a different random string. My current code is not working correctly, the only thing I'm getting a random item and the same index printed multiple times.
My output right now:
relax
2
2
2
2
How can I fix that and get a correct randomized output?
My code:
public static void main(String[] args) {
int i;
String Cofee[] = {"pick it","drink it","relax","put it in a cup",};
java.util.Random randomGenerator = new java.util.Random();
int x = Cofee.length;
int y = randomGenerator.nextInt(x);
String frase = Cofee[y] ;
System.out.println(frase);
for(i = 0; i < Cofee.length; i++)
System.out.println(y);
}
You assign a value to y once, and you print y repeatedly. The value of y doesn't change. To do that, you would need to call randomGenerator.nextInt(x) for each iteration of the loop!
However, if you want to randomize and print the array, use:
public static void main(String[] args)
{
String[] coffee = {"pick it","drink it","relax","put it in a cup",};
// this wraps the array,
// so modifications to the list are also applied to the array
List<String> coffeeList = Arrays.asList(coffee);
Collections.shuffle(coffeeList);
for(String value : coffee)
System.out.println(value);
}
As an aside, don't use String coffee[], but use String[] coffee. Although Java allows putting the array type after the variable name, it is considered bad form.
Or use a list directly:
public static void main(String[] args)
{
List<String> coffeeList = Arrays.asList("pick it","drink it","relax","put it in a cup");
Collections.shuffle(coffeeList);
for(String value : coffeeList)
System.out.println(value);
}
For that, you can implement a shuffling algorithm.
It's not so scaring as it might sound at first. One of the famous classic shuffling algorithms, Fisher–Yates shuffle is relatively easy to grasp.
The core idea: iterate over the given array from 0 to the very last index, and for each index swap the element that corresponds to the randomly generated index between 0 and the current index (i) with the element under the current index.
Also, I would advise creating a separate array representing indices and shuffle it in order to preserve the array of string its initial state (you can omit this part and change the code accordingly if you don't need this).
That's how it might be implemented:
public static final Random RANDOM = new Random(); // we need an instance for random to generate indices
A Fisher–Yates shuffle implementation:
public static void shuffle(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int j = RANDOM.nextInt(i + 1); // generating index in range [0, i]
swap(arr, i, j); // swapping elements `i` and `j`
}
}
Helper-method for swapping elements:
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
Usage-example:
String[] coffee = {"pick it","drink it","relax","put it in a cup"};
int[] indices = new int[coffee.length];
for (int i = 0; i < indices.length; i++) indices[i] = i; // or Arrays.setAll(indices, i -> i); if you're compfortable with lambda expressions
shuffle(indices);
for (int i = 0; i < coffee.length; i++) {
String next = coffee[indices[i]];
System.out.println(next);
}
Output:
drink it
pick it
put it in a cup
relax

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

Understanding Iteration with 2d arrays Java

I am watching a tutorial on 2d arrays and I can't seem to understand where the values for
states.length and states[i].length are coming from. How does it know the outer loop deals with the size 3 array and the inner is the size 2 array?
public class Test3 {
public static void main(String[] args) {
String [][] states = new String[3][2];
states[0][0] = "California";
states[0][1] = "Sacremento";
states[1][0] = "Oregon";
states[1][1] = "Salem";
states[2][0] = "Washington";
states[2][1] = "Olympia";
for (int i = 0; i < states.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < states[i].length; j++) {
sb.append(states[i][j]);
}
System.out.println(sb);
}
}
}
The states.length is the row length of your array while the states[i].length is the number of column of the specified row.
Well, a two dimensional array is an array of arrays.
So String[3][2] is
[["string", "string"],
["string", "string"],
["string", "string"]]
states.length is the length of the outer array, which is 3.
states[i].length is the length of each individual array, which are all 2.
You begin by creating a 2D array that looks like the following.
[[California, Sacramento]
[Oregon, Salem]
[Washington, Olympia]]
The first for loop will iterate over each row. In this case states.length is 3 because there are 3 rows.
The next for loop will iterate over the columns in each row.
In other words, states[i] will give you a row. If i is 0, then states[0] is [California, Sacramento]
There are 2 entries in that row, so states[0].length is 2.

Taking N number of arrays and turning it into a multidimensional array with N rows JAVA

I am trying to write code that will turn N arrays into a multidimensional array with N rows. I currently have a code that can turn 2 arrays into a multidimensional array with 2 rows. However, I am unsure how to modify it in order to make this code take N arrays.
Additionally my code currently can only take arrays of the same size. However, it needs to be able to take arrays of different lengths. This would entail that the rows in my multidimensional array would not always be equal length. I have been told that this means a list might be more suitable than an array. However I am unfamiliar with lists.
Here is my code as it currently stands:
public class test5 {
int [][] final23;
public int [][] sum(int [] x, int[] y)
{
final23= new int[2][x.length];
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0][i] = x[i];
final23 [1][i] = y[i];
}
return final23;
}
public void print()
{
for (int i = 0; i < final23.length; i++)
{
for (int j = 0; j<final23[0].length; j++)
{
System.out.print(final23[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args)
{
int l[] = {7,3,3,4};
int k[] = {4,6,3};
test5 X = new test5();
X.sum(k,l);
X.print();
}
}
Thanks in advance. Sorry i am new to java and just learning.
import java.util.Arrays;
class Arr
{
public static void main(String[] args)
{
int[][] ar=toMulti(new int[]{1,2},new int[]{1,2,3},new int[]{5,6,7,8});
System.out.println(Arrays.deepToString(ar));
/*OR You can directly declare 2d array like this if your arrays don't
come as user inputs*/
int[][] arr={{1,2,3},{1,2},{3,4}};
System.out.println(Arrays.deepToString(arr));
}
/* ... is known as variable argument or ellipsis.
int[] ... denotes that you can give any number of arguments of the type int[]
The function input that we get will be in 2d-array int[][].So just return it.*/
public static int[][] toMulti(int[] ... args) {
return args;
}
}
Since they might not be equal lengths, you're going to have to account for dead spots on the matrix, perhaps utilizing the Null Object pattern. Initialize each element to a special case that can be handled uniformly, like any other element.
That's my advice on how to do it with arrays, by the way. Collections aren't hard though.
Multidimensional arrays in java are not similarly sized - they're just a bunch of arrays arranged in an array, just like any other object would be. if you wanted them to all be the same size you'd have to find the max size and fill smaller arrays with some sort of empty or default value.
In any case, since you want to copy some N number of arrays, as long as you accept different lengths, why not use varargs:
public static int[][] toMulti(int[] ... args) {
// you can't resize an array, so you have to size your output first:
int[][] output = new int[args.length][];
for (int i =0; i<args.length; i++)
{
output[i[=args[i].clone();
//you could also do this copying 1 at a time, or with
int[] arr =new int[args[i].length];
System.arraycopy(args[i], 0, arr, 0, args[i].length);
output[i]=arr;
}
If you wanted to size them all to the same size System.arraycopy would be better, as you'd create the array at the max size, the remaining values would automatically be 0's (or nulls for object arrays).

How can I concatenate multiple rows in a matrix

In Java I would like to concatenate an array (a[], fixed length) to an array of the same length, to create a matrix M[2][length of a]. This way I would like to subsequently paste more of those arrays onto the matrix. (Comparable to the Matlab vertcat function..C=[A;B])
Is this possible?
Thanks
Yes, it is possible. Here is an example:
public class Main
{
public static void main(String[] args)
{
int[] A = new int[]{1, 2, 3};
int[] B = new int[]{4, 5, 6};
int[][] M = new int[2][];
M[0] = A;
M[1] = B;
for ( int i = 0; i < 2; i ++ ){
for (int j = 0; j < M[i].length; j++ ){
System.out.print(" "+ M[i][j]);
}
System.out.println("");
}
}
}
The above prints out:
1 2 3
4 5 6
We can do even better than that, though. If you are using Java 5 or higher, use:
public static int[][] vertcat(int[]... args){
return args;
}
Then you can write:
int[][] M = vertcat(A,B);
And it will work for any number of arguments.
Edit
The above method stuffs the original arrays into another array, which means that any modification to the result will affect the original arrays, which may be undesireable. Use the following to copy the values:
public static int[][] copyMatrix(int[][] original){
if ( (original==null) || (original.length==0) || (original[0].length == 0) ){
throw new IllegalArgumentException("Parameter must be non-null and non-empty");
}
rows = original.length;
cols = original[0].length;
int[][] cpy = new int[rows][cols];
for ( int row = 0; row < rows; row++ ){
System.arraycopy(original[row],0,cpy[row],0,cols);
}
return cpy;
}
If you want vertcat to return a copy rather than the original, you can redefine it as:
public static int[][] vertcat(int[]... args){
return copyMatrix(args);
}
As far as I know, Java has no built-in support for matrices and matrix-related operations. I would either use a 2D array, write my own Matrix wrapper class (in simpler cases) or hunt down a good Matrix library (e.g. http://jmathtools.berlios.de/).

Categories

Resources