Multiplying 2D arrays in Java - 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.

Related

Multiplying an array and a 2-d array in 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.

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).

Variable may not have been initizialized (java)

So I was trying to write a function for a ragged array; I may have got this entirely wrong, if so please explain why/how I went wrong. It took me ages to get this far and I have a feeling I've alreayd done it wrong.
I tried compiling it because I'm pretty sure currently it will work, however i'm getting the error "variable n may not have been initialized". My code so far is:
static double[][] exampleMatrix()
{
int n;
double[][] a = new double [3][];
a[0] = new double[n-1];
a[1] = new double[n];
a[2] = new double[n-1];
{
for (int i = 0; i < n-1; i++)
{
a[0][i] = 1;
a[2][i] = 1;
}
for (int i = 0; i < n; i++)
{
a[1][i] = - i - 1;
}
return a;
}
}
I'm probably missing something really really obvious, but i'm not sure what it is to initialize n.
EDIT: I have been told to make this work for a value n that is not yet given.. How would I do that? As in, the user is supposed to input the value of n, and be given an array in return.
Basically, my given question is to implement a function exampleMatrix that, given n, produces the array where all values in teh array a[0] is 1, and same for a[2], and then for a[1], be given a range of values from -1 down to -n for a[1][n-1]. This is what I have so far to calculate this, but I am guessing I have gone completely wrong?
You don't set any value to n. How will your program know how big to make the arrays and how many iterations to run in the for loops?
Method variables (unlike fields) cannot rely on the default value (0 in this case). As such n is not anything when it is declared
int n;
You need to state what n is at some point between declaring it and using it, for example.
int n;
n=7;
or
int n=7;
n not known at compile time
You can also pass n as a variable, if n is variable
static double[][] exampleMatrix(int n){
double[][] a = new double [3][];
a[0] = new double[n-1];
a[1] = new double[n];
a[2] = new double[n-1];
{
for (int i = 0; i < n-1; i++)
{
a[0][i] = 1;
a[2][i] = 1;
}
for (int i = 0; i < n; i++)
{
a[1][i] = - i - 1;
}
return a;
}
}
This method would then be used as
double[][] someMatrix= exampleMatrix(5); //<-- 5 is passed into the function and becomes n
Or you can calculate n in whatever way you see fit
Actually the Problem is with local variable
int n;
The scope of local variables is much narrower. Compiler knows when its getting used. Hence, forcing programmer to initialize the variable
You have to initialize it with any default value as int n=0;
I want to complement the above responses.
You have to take care with the static segments, because when a class load its static segments, the class don't assign default value, if you type:
public static int n;
in your class, the value depends on the programmer. this can throw an exception about initialized.

Count characters in a multidimensional array, Java

Below is my code:
public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];
...
public void loadBombs()
{
//loadArray();
Random randomGen = new Random();
for (int u=1; u<=9; u++)
{
int randomRow = randomGen.nextInt(9);
int randomCol= randomGen.nextInt(9);
bombBoard[randomRow][randomCol] = "#";
}
//counting #'s -- setting variable
for (int d = 0; d < bombBoard[bombRow].length; d++)
{
for (int e = 0; e < bombBoard[bombCol].length; e++)
{
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
{
maxTurns++;
}
}
}
All I want to do is count the amount of (#)'s in the multidimensional array and assign it to a variable called maxTurns.
Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<
This line is equating the character # with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
Instead, access a single cell like this
if (bombBoard[d][e].equals("#"))
And initialize maxTurns before counting i.e. before your for loop:
maxTurns = 0;
You need to change the if codition
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
to
if (bombBoard[d][e].equals("#"))
You are using 2D Array, and do array[i][j] can populate its value for a gavin position.
do you want to count from the whole array or certain parts of the array only?
From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is
bombBoard[bombRow].length and bombBoard[bombCol].length
But if you want to iterate the whole array, think you should just use:
for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
{
if (bombBoard[d][e].equals("#"))
{
maxTurns++;
}
}
}

How can I convert the following java function into C++?

If I have the following Java code:
int[][] readAPuzzle()
{
Scanner input = new Scanner(System.in);
int[][] grid = new int[9][9];
for (int i=0; i<9; i++)
for (int j=0; j<9; j++)
grid[i][j] = input.nextInt();
return grid;
}
public static void main(String[] args) {
// Read a Sudoku puzzle
int[][] grid = readAPuzzle();
}
How can I convert this to C++? I get hung up on passing the array. Here is my attempt:
#include <iostream>
using namespace std;
const int puzzle_width = 9;
const int puzzle_height = 9;
void readAPuzzle(int (&grid)[puzzle_height][puzzle_width])
{
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
grid[i][j] = cin >> grid[i][j];
return;
}
int main()
{
int[9][9] grid;
readAPuzzle(grid);
}
What am I doing wrong in general?
You need to read in the input text into your array grid and pass it on.
grid[i][j] = cin >> grid[i][j];
Doesn't do what you think it does, it tries to assign an object of type istream to grid[ i ][ j ]
cin >> grid[i][j];
however suffices.
Also, note in C++ the dimensions follow the identifier as in:
int grid[9][9];
Try
#include <iostream>
using namespace std;
const int puzzle_width = 9;
const int puzzle_height = 9;
void readAPuzzle(int grid[puzzle_height][puzzle_width])
{
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
cin >> grid[i][j];
}
int main()
{
int grid[9][9];
readAPuzzle(grid);
}
In general, arrays are automatically passed by reference, and array sizes go after the name of the array not after their type.
And if you declared constants, you should always use puzzle_width and puzzle_height (perhaps shorten their names though) and not magic numbers like 9.
The simple answer is to use vectors instead of arrays. C++'s rules for passing arrays as function parameters are esoteric and derived from C. Here are some of the issues:
You can't use arrays for long without understanding and using pointers
Array subscripting is pointer subscripting. Arrays are accessed using pointer arithmetic. Arrays as function parameters are actually pointers in disguise.
Functions don't get information about array size when taking an array argument
Consider the declaration:
void inc_all(int myarray[]); /* increments each member of the array */
Unfortunately, that array parameter is not an array parameter! It's actually a pointer parameter:
void inc_all(int *myarray); /* Exactly the same thing! */
And a pointer doesn't know how many items are in the sequence it points at. As a result this function cannot have the information necessary to know when the array stops. You either need to pass the length:
void inc_all(int *myarray, size_t len); /* size_t rather than int */
or you need to use a sentinel value to mark the end of the array. Either way, an array is not a self-contained encapsulated datatype like a vector is.
You can't pass an arbitrarily-sized two-dimensional array to a function
If you try to create a function which takes a two-dimensional array:
void inc_all(int myarray[][]); /* XXX won't compile! */
it won't compile. The problem is you have an indeterminate length array of indeterminate length arrays of ints. The outer array doesn't know how large its members (the inner arrays) are and therefore doesn't know how to step through them in memory. You need to specify the size of the inner arrays:
void inc_all(int myarray[][10]);
at which point your code is probably not as general as you were hoping it was going to be.
If you use vectors and vectors of vectorss, these problems don't arise because the vectors themselves know how many members they have and carry that information with them.
If you still want to learn more about arrays and pointers I recommend section 6 of the comp.lang.c FAQ.
I think your should to use your constants first of all. You can pass as value pointer as well as ref on pointer (both 4bytes), also it is a pointer on memory (it is valueble).
#include <iostream>
using namespace std;
const int puzzle_width = 9;
const int puzzle_height = 9;
void readAPuzzle(int grid[puzzle_height][puzzle_width])
{
for(int i = 0; i < puzzle_height; i++)
for(int j = 0; j < puzzle_width; j++)
cin >> grid[i][j];
}
int main()
{
int grid[puzzle_height][puzzle_width];//I think your need to do this
readAPuzzle(grid);
}

Categories