Multiplying an array and a 2-d array in java - java

I'm trying to multiply an array and a 2d array on java and my program compiles but keeps returning the error java.lang.NullPointerException; null when I try to input anything into it. Here is my code so far:
static double[][] productWithDiagonal(double[] a, double[][] b)
{
double[][] c = new double[3][];
{
for (int i = 0; i < b.length; ++i) {
for (int j = 0; j < b[1].length; ++j) {
c[i][j] = a[j] * b[i][j];
}
}
}
return c;
}
Thanks

This here:
double[][] c = new double[3][];
Only instantiates your "rows". You need something like
double[][] c = new double[3][3];
Or more useful probably
... c = new double[b.length][b[0].length];
instead. But just to be sure: those numbers there matter; you should make sure that b for example is really a "regular rectangle" shaped matrix - so that all rows have the same number of columns. And of course a should have the same number of columns as b, too. You could add such checks in the beginning of your method; to ensure that the shapes of a and b actually allow for this multiplication!
You see, in Java, a two-dim array is nothing but an array that contains another array. Your initial code would only initiate that "outer" array, leaving the "inner" arrays at null.

Related

Multiplying 2D arrays in Java

I'm having some trouble with the question below, not entirely sure if its write as I can't figure out how to call the method in the driver method to print the result.
(Question) Create a Method with header:
public static int[][] multiplyArrays(int[][] a, int[][] b)
The above method will multiply two 2D arrays referred to by a and b, and return a 2D array
reference of a × b. Multiplying two 2D array work on the following algebraic expression to
find out the resultant array: result[i][j]= a[i][k] * b[k][j]
Hint: In this case, inside the method, declare a 2D int[][] array reference variable and
instantiate it with a size of a.length x b[0].length. They complete the rest using the
series multiplication. This is an application of nested loop. The outermost loop will run from
0 to N. The middle loop will run for index i and the innermost one will run for index j.
My code so far:
public static int[][] multiplyArrays(int[][] a, int[][] b) {
var aNumRows = a.length;
var aNumCols = a[0].length;
var bNumCols = b[0].length;
int[][] m = new int[aNumRows][bNumCols];
for (var r = 0; r < aNumRows; ++r) {
for (var c = 0; c < bNumCols; ++c) {
m[r][c] = 0;
for (var i = 0; i < aNumCols; ++i) {
m[r][c] += a[r][i] * b[i][c];
System.out.printf("%3d",r, c);
}
}
}
return m;
}
Since the method you defined is static, you could simply use classname.multiplyArrays(a, b) ; where a and b are the names of the variables in your driver method.

Implementing Selection Sort: Inputted array is changed along with returned array

I have a program that manipulates Cartesian points. At one spot in the program, I load my x and y values into a Point array. No big deal. But then, I want to sort this array by x values and set it to a new variable while still keeping the original array the way it is.
The original array is "points" and the new array is defined as:
points1 = sortBy(points, "x");
The sortBy method is defined earlier as:
private static Point[] sortBy( Point[] pointsXY, String xOrY) {
int min;
Point[] inputPoints = pointsXY;
if( xOrY == "x"){
for( int i = 0; i < (inputPoints.length - 1); i++ ) {
min = i;
for( int j = i+1; j < inputPoints.length; j++ ) {
if( inputPoints[j].getX() < inputPoints[min].getX()) min = j;
}
// Swap points[i] and points[min]
Point temp = inputPoints[i];
inputPoints[i] = inputPoints[min];
inputPoints[min] = temp;
}
There is an "else if" block later that takes "y" instead. It then does: return inputPoints;
However, what I am getting when I am printing these arrays out are the exact same thing - two arrays sorted by x values. I have tested the output by just outputting the unsorted array, and it works fine.
I also have tried using this method without it being static, which has given the same output.
Point[] inputPoints = pointsXY; does not copy the array, it just creates a new name (inputPoints) for the same array. To create a copy of the array, you should use Point[] inputPoints = pointsXY.clone(); (javadoc).

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

I am trying to reverse a two dimensional array and keep getting a null exception

Here is my method that is suppose to reverse the array.
(Also, keep in mind that this method can receive a jagged array)
public static int[][] reverse(int[][]a){
int[][] rev = new int[a.length][];
int row = a.length;
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
for(int y=0; y< a[x].length;y++){
rev[row-1][col-1]= a[x][y];
col--;
}
row--;
}
return rev;
}// reverse method
I keep getting
Exception in thread "main" java.lang.NullPointerException
at Home.reverse(Home.java:259)
at Home.main(Home.java:56)
Java Result: 1
Here is my main that calls that method
int[][] two = {{1,2,3,4},{0,1,2},{9},{1,3,5,7}};
System.out.println("The size of array os " + ar.length);
System.out.println("The columns of array is " + ar[0].length);
int[][] rev;
//int[] b = concatenate(ar);
//int[] c = concatenate(two);
//int[][] rev = reverse(ar);
//for(int x=0;x<c.length;x++){System.out.println("worked" + c[x]);}
rev = reverse(two);
//for(int x = 0;x<rev.length;x++){
// for(int y = 0;y<rev[x].length;y++){
// System.out.print(rev[x][y]);
//}
//}
for(int x=0;x<rev.length;x++){
for(int y=0;y<rev[x].length;y++){
System.out.print(rev[x][y]);
}
}
}// main
So my question is really, where did I go wrong?
I traced my reverse method and it looks like it should be doing its job but apparently not.
Your array rev has not been initialized in its second coordinate. After your declaration int[][] rev = new int[a.length][], all your rev[i] are null objects (arrays are objects, even for primitive types). To avoid that, initialize with int[][] rev = new int[a.length][a[0].length] or with rev[i] = new int[a[i].length] or so, if the array is jagged.
When you say this line
int[][] rev = new int[a.length][];
You have created an array of length a.length of arrays, but the internal arrays are all null. So you are getting a NullPointerException on this line:
rev[row-1][col-1]= a[x][y];
You need to create your internal arrays inside the first for loop. This will satisfy your "jagged array" requirement.
for(int x=0;x<a.length;x++){
int col = a[x].length-1;
rev[row-1] = new int[a[x].length]; // Add this to create differing lengths.
for(int y=0; y< a[x].length;y++){

getting floats rather than objects out of an Arraylist

I am trying to create a method that removes duplicates from a 2d array. the outside array conains point indexes and the inner array contains their coordinates. It looks like i have to use an arraylist in order to remove elements without ending up with null values in the array. I would then like to convert the arraylist back into a 2D array in order to return it in the format i require. The problem is that the arraylsit contains an array of objects so i can't cast it into an array designed for floats. what is the correct syntax for filtering the floats from my array list. my code follows:
public class rem_duplicates {
public float [][] rem_geo_duplicates(float a[][]){
ArrayList<float[]> al = new ArrayList<float[]>();
float no_points = a.length;
int count = 0;
for (int i = 0; i < no_points-1; i++){
if((a[i][0] == a[i+1][0])&&(a[i][1] == a[i+1][1])){
a[i] = null;
count ++;
}
for (int j = 0; j < no_points; j++){
if (a[j] != null){
al.add(a[j]);
}
}
//how do i get the arraylist 'al' into this array b[][]?
float b[][] = new float [a.length-count][3];
b = al.toArray();
}
}
return b
}
Try using the following:
float b[][] = new float [a.length-count][3];
b = al.toArray(b);
This is the generic version of toArray() which in your case will return a float[][]. Keep in mind that float[] is an object, so there are no issues of boxing/unboxing here.
I notice several basic issues with your code however - I recommend trying to compile it and resolving the errors.
It works fine if you pass your newly created array as parameter:
float b[][] = new float[a.length-count][];
b = al.toArray(b);

Categories