Java put matrix element in array - java

i was trying to compare 2 variables in java but it gives me error and i cant figure it out.
I am reading matrix element then put it in temp then put that temp variable in an array. but it gives error when I try to put matrix element in temp and when I compare elements.
error: array required, but float found. Anyone knows how to correct this ?
public float[] toSortedArray()
{
float b[];
float temp;
int index=0;
for(int i=1; i<=m; i++)
{
for(int j=1; j<=n; j++)
{
temp=a[m][n];
b[index++]=temp;
}
}
Arrays.sort(b);
System.out.print("[");
for(int z=0; z<(m*n)-1; z++)
{
System.out.print(b[z]+", ");
}
System.out.print(b[(m*n)-1]+"]\n");
}

There are several things needed in this:
Pass on the m, n parameter along with original 2D array like
public float[] toSortedArray(float[][] a, int m, int n)
define b array as
float b[] = new float[m*n];
In for loop (one within i and j var) (both loop should start with 0) use
temp=a[i][j];
instead of
temp=a[m][n];
At the end return b.
return b;

Related

Write a function called arraySum that returns the sum (as an int) of all the values in a two-dimensional array of int values (Java)

I am trying to sum all the int values of a 2D array. I named it array. my function is then called arraySum. If arraySum is null, I return 0. Otherwise, it goes through two for-loops, summing the values of these arrays.
int i = 0;
int j = 0;
static int sum = 0;
int[][] array = new int[i][j];
static int arraySum(int[][] array) {
if (array == null) { // test if the incoming param is null
return 0;
} else {
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
my error message:
java.lang.AssertionError: Incorrect result: expected [-217085] but found [-308126]
Fixing the method signature is the first step.
Then you'll need to fix the null check.
Then your loops need to check the size of the inner and outer arrays.
Move the return statement.
Here's the fixed code:
static int arraySum(int[][] array) { // fix the signature
if (array == null) { // test if the incoming param is null
return 0;
} else {
int sum = 0; // you need this in the scope of the method - it will be returned at the end
for (int i = 0; i < array.length; i++) { // length of the outer array
for (int j = 0; j < array[i].length; j++) { // length of the inner array
sum += array[i][j];
}
}
return sum; // moved out of the loop
}
}
Edit: I've concentrated on just the method now - how you call it is up to you. Please note that the method will not affect any externally defined sum variable. It will return the sum and it's up to the caller to store that value somewhere.
Avoid using primitive for statement. See following:
static int arraySum(int[][] array) {
int sum = 0;
if (array == null) return 0;
for(int[] row: array){
for(int col : row) {
sum += col;
}
}
return sum;
}
Streams can do this too:
//Create 2D array
int[][] array = {{1,2,3},{4,5},{6}};
//Sum all elements of array
int sum = Stream.of(array).flatMapToInt(IntStream::of).sum();
System.out.println(sum);
Picking apart the summing code:
Stream.of(array)
Turns the 2D array of type int[][] into a Stream<int[]>. From here, we need to go one level deeper to process each child array in the 2D array as the stream only streams the first dimension.
So at this point we'll have a stream that contains:
an int[] array containing {1,2,3}
an int[] array containing {4,5}
an int[] array containing {6}
.flatMapToInt(IntStream::of)
So far we have a Stream of int[], still two-dimensional. Flat map flattens the structure into a single stream of ints.
flatMapToInt() expands each int[] element of the stream into one or more int values. IntStream.of() takes an array int[] and turns it into an int stream. Combining these two gives a single stream of int values.
After the flattening, we'll have an int stream of:
{1,2,3,4,5,6}
.sum()
Now we have an IntStream with all elements expanded out from the original 2D array, this simply gets the sum of all the values.
Now the disclaimer - if you are new to Java and learning about arrays, this might be a little too advanced. I'd recommend learning about nesting for-loops and iterating over arrays. But it's also useful to know when an API can do a lot of the work for you.

How do I display the sum of the elements of myArray using nested enhanced for loops?

I have created a program for an assignment that requires me to display the elements of an array using nested enhanced for loops.
I get the error that it cannot convert from element type Integer[] to int.
myArray was already instantiated and initialized correctly in a constructor. I know that it's correct because I can display the elements of the array in list format just fine, from 1 to 60.
public void displayArrayProduct() {
DecimalFormat decimalFormat = new DecimalFormat("#.##");
decimalFormat.setGroupingUsed(true);
decimalFormat.setGroupingSize(3);
int p=1;
System.out.print("The product of all element of myArray is ");
for (int a : myArray) {
for (int b : myArray) {
p = p + myArray[a][b];
}
}
System.out.println(decimalFormat.format(p));
}
}
What I expected this to do was output the sum of all of the elements of the array. I tried the exact same thing with regular for loops, and it worked perfectly. Unfortunately when I swapped to enhanced for loops, it stopped working, giving me the error:
Type mismatch: cannot convert from element type Integer[] to int
This is what my constructor looks like:
ExerciseTwo() {
myArray = new Integer[6][10];
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
this.myArray[i][j] = i + 1;
}
}
}
for (int[] a : myArray) {
for (int b : a) {
p = p + b;
}
}
Well the issue is a is an int array and not just an int.
You're using for-each loops which go through each element in an array or collection. So the thing you define in the loop declaration is an element from the array, rather than an index. Since you're using a 2-dimensional array (an array of arrays), each element in myArray is an integer array, so the first loop should be declared:
for (int[] a : myArray) {
So each a value will be of type int[], and what you want next is to get each integer from each of those integer arrays:
for (int b : a) {
Note that you're getting each integer in a, not in myArray. Now you can reference each integer in the array as just b, not an array's value at index b:
p = p + b;
It looks like myArray is an array of arrays, not an array of ints. Maybe this is more what you need?
for (int[] a: myArray) {
for (int b: a) {
p = p + b;
}
}
Update: My original answer was posted before it was clear myArray is a multidimensional array. Given that, I agree with Vecna - who also correctly pointed out that using the for-each loop would allow you to get the integer itself instead of referencing it by index.
Original answer:
It looks like you may have changed something else when you converted the for loops.
The expression myArray[a][b] would be valid if myArray were a multi-dimensional array. The problem is that you are attempting to access a two-dimensional array, when the array itself is one-dimensional.
If you are attempting to multiply the entries at a and b, you'd need to do this:
p = p + myArray[a] * myArray[b];
or in shorthand:
p += myArray[a] * myArray[b];
You mentioned that you had 60 elements in your Array, so I simply created a sample 2 x 30 Array as an example:
int[][] myArray = new int[2][30];
int increment = 0;
for(int x = 0; x < myArray.length; x++) {
for(int y = 0; y < myArray[x].length; y++) {
myArray[x][y] = increment;
increment++;
}
}
Next, if you are using a for-each loop, your error is occurring because each individual row of the Array as an INDEX IN IT OF ITSELF. So your for-each loop should represent be of the type (int[]) an int Array:
for(int[] x: myArray) {
Within each individual Array (x) there is an int primitive value so we run another for-each-loop in order to extract each individual value:
for(int y: x) {
And here is your complete code:
for(int[] x: myArray) {
for(int y: x) {
totalVal += y;
}
}
System.out.println(totalVal);
And the output is the sum of each int in the Array:
1770

multiply a 2d array by a 1d array

I've initialized a 1d and 2d array and now I basically just want to be able to perform matrix multiplication on them. However, I'm not quite getting the proper answer. I think I've mixed up the for loop where I try to ensure I only multiply the correct values, but can't quite get the hang of it.
edit: I've fixed it, I was misunderstanding what the length method of a 2D array returned (thought it returned columns and not rows). The below code is my corrected code. Thanks everyone.
public static double[] getOutputArray(double[] array1D, double[][] array2D) {
int oneDLength = array1D.length;
int twoDLength = array2D[0].length;
double[] newArray = new double[array2D[0].length]; // create the array that will contain the result of the array multiplication
for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
double c = 0;
for (int j = 0; j < oneDLength; j++) {
double l = array1D[j];
double m = array2D[j][i];
c += l * m; // sum the products of each set of elements
}
newArray[i] = c;
}
return newArray; // pass newArray to the main method
} // end of getOutputArray method
There are some problems, first of all, you should decide how the vectors represented, are you multiplying from left or right.
For the maths: vector 1xn times matrix nxm will result in 1xm, while matrix mxn times nx1 result in mx1.
I think the following would work for you:
public static double[] getOutputArray(double[] array1D, double[][] array2D) {
int oneDLength = array1D.length;
int twoDLength = array2D.length;
double[] newArray = new double[twoDLength]; // create the array that will contain the result of the array multiplication
assert twoDLength >0 && array2D[0].length == oneDLength;
for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
double c = 0;
for (int j = 0; j < oneDLength; j++) {
double l = array1D[j];
double m = array2D[i][j];
c += l * m; // sum the products of each set of elements
}
newArray[i] = c;
}
return newArray; // pass newArray to the main method
} // end of getOutputArray method
I hope I did not make a mistake, while trying to fix.

finding sums in 2 dimentional arrays java

A project I am doing requires me to find horizontal and vertical sums in 2 dimensional arrays. So pretty much its a word search (not using diagonals) but instead of finding words, the program looks for adjacent numbers that add up to int sumToFind. The code below is what I have come up with so far to find horizontal sums, and we are supposed to implement a public static int[][] verticalSums as well. Since I have not yet completed the program I was wondering, first of all, if what I have will work and, secondly, how the array verticalSums will differ from the code below. Thank you
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int i;
int start;
int sum = 0;
int copy;
int [][] b = new int [a[0].length] [a.length];
for (int row = 0; row < a.length; row++) {
for ( start = 0; start < a.length; start++) {
i = start;
sum = i;
do {
i++;
sum = sum + a[row][start];
}
while (sum < sumToFind);
if(sum == sumToFind) {
for (copy = start; copy <= i; copy++) {
b[copy] = a[copy];
}
}
for (i = 0; i < a[0].length; i++) {
if (b[row][i] != a[row][i])
b[row][i] = 0;
}
}
}
return b;
}
Your code won't work.... (and your question is "if what I have will work?" so this is your answer).
You declare the int[][] b array as new int [a[0].length] [a.length] but I think you mean: new int [a.length] [a[0].length] because you base the row variable off a.length, and later use a[row][i].
So, if your array is 'rectangular' rather than square, you will have index-out-of-bounds problems on your b array.
Your comments are non-existent, and that makes your question/code hard to read.
Also, you have the following problems:
you set sum = i where i = start and start is the index in the array, not the array value. So, your sum will never be right because you are summing the index, not the array value.
in the do..while loop you increment i++ but you keep using sum = sum + a[row][start] so you just keep adding the value to itself, not the 'next' value.
At this point it is obvious that your code is horribly broken.
You need to get friendly with someone who can show you how the debugger works, and you can step through your problems in a more contained way.
Test is very simple
public static void main(String[] args) {
int[][] a = {{1, 2}, {1, 0}};
int[][] result = Stos.horizontalSums(a, 1);
System.out.println(Arrays.deepToString(result));
}
Result
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
When you fix this problem, then this should print something like this
[[1, 2], [1, 0]]

Transposing Values in Java 2D ArrayList

Good evening all,
I'm trying to write a method that creates and returns a 2D array whose elements in each location are the same as the elements in the mirror image location of the parameter array. Unfortunately, no matter what pair of numbers I enter into the method call I get an "out of bounds" error in my compiler. Below is my program. Tell me where I've gone wrong! Thanks!
public static int[][] transpose(int [][] a) {
int r = a.length;
int c = a[r].length;
int [][] t = new int[c][r];
for(int i = 0; i < r; ++i) {
for(int j = 0; j < c; ++j) {
t[j][i] = a[i][j];
}
}
return t;
}
}
Arrays in java are 0 based, change your assignment to c to :
int c = a[r - 1].length;
#Suraj is correct, however you must assume the 2D array is rectangular, in which case it is sightly more efficient to change line 3 to:
int c = a[0].length;
#Kris answer text is correct however code sample is wrong line.
Note this error is a reproduction of a broken "answer" posted in "Yahoo Answers": http://answers.yahoo.com/question/index?qid=20080121204551AAn62RO
Your problem lies in line two: a[r].length returns the number of columns, but arrays are indexed from 0. You should adjust accordingly:
int r = a.length - 1;

Categories

Resources