I have a 2-d array of double numbers it's 48 by 48, I am trying to make a method that will allow the user to select a specific amount e.g. = 7 by 7 and then put that into a new 2d array.
public static double[][] amountOTP(double [][] a, int x){
a = new double[x][x];
return a;
}
thats all i have right now, this takes an 2d array as input however even though i specified x it doesn't work.
When you want to cut it ro a smaller size and copy the part of the original array, this should work:
public static double [][] cutArray (double [][] a, int newSize){
if (x > a.length)
throw new IllegalArgumentException ("Can only make array smaller");
double [][] b = new double [newSize][newSize];
for (int i = 0; i < newSize; i++){
for (int j = 0; j < newSize; j++){
b [i][j] = a [i][j];
}
}
return b;
}
The solution below considers situations in which the requested new two-dimensional array length is greater than the original in which case we simply return the original.
Example:
public static double[][] amountOTP(double [][] a, int x){
if(x > a.length) return a;
for (double[] arr : a)
if(arr.length < x)
return a;
double[][] newArray = new double[x][x];
for (int i = 0; i < x; i++)
for (int j = 0; j < x; j++)
newArray[i][j] = a[i][j];
return newArray;
}
Sorry if I'm wrong, but I'm assuming for now that you want your method to return a smaller 2d array which contains some of the values of the given array, in which case you would need to change your method to this:
public static double[][] amountOTP(double [][] a, int x) {
double[][] b = new double[x][x];
x = Math.min(x, a.length);
for(int i = 0;i < x; i++)
for(int j = 0;j < x; j++)
b[i][j] = a[i][j];
return b;
}
This should work fine but feel free to comment and inform me if I left anything out or it doesn't work; I'm here to help. Anyways, I hope this works for you. (Also, if this isn't the answer you were looking for, feel free to tell me.)
Note: This should avoid IndexOutOfBounds exceptions, so it will still work correctly if the user gives an x value bigger than the size of a. The 2d array that this method returns will just have some values of zero where it couldn't find any numbers.
I think it's something like that you're looking for :
public static double[][] amountOTP(double [][] a, int x){
double [][] ret = new double[x][x];
for(int i = 0; i < x; i++)
for(int j = 0; j < x; j++)
ret[i][j] = a[i][j];
return ret;
}
But you have to be careful with the parameters because it can cause an IndexOutOfBounds exception
I see you already have a lot of answers, but nobody was making use of the excellent Arrays.copyOf Java API method:
public static double[][] amountOTP(double [][] a, int x){
a = Arrays.copyOf(a, x);
for(int i=0; i<a.length; i++) {
if(a[i] != null) {
a[i] = Arrays.copyOf(a[i], x);
} else {
a[i] = new double[x]; // allows growth
}
}
return a;
}
you are actually not yet initializing the array so the method should be like this
public static void main(String[] args)
{
double[][] a=amountOTP(3);
for(int j=0;j<a.length;++j)
{
for(int i=0;i<a[j].length;++i)
{
a[j][i]=2;
}
}
for(int j=0;j<a.length;++j)
{
for(int i=0;i<a[j].length;++i)
{
System.out.println(a[j][i]);
}
}
}
public static double[][] amountOTP(int x)
{
return new double[x][x];
}
Related
Full disclosure; I needed to know this for an assignment. I wanted to return a single array to a multidimensional array from a method. I circumvented the issue with the below code by returning it to another 1-dimensional array then using a for loop to transfer values.
public class test
{
public static void main ( String args[] )
{
int[][] array1 = new int [100][5];
int[] temp = new int [5];
int num = 0;
temp = setValue();
for (int i = 0; i<=4; i++) // cycle 1
{
array1[num][i]= temp[i];
}
System.out.format("\n\n");
}
public static int[] setValue()
{
int[] array3 = new int [5];
for (int i = 0; i<=4; i++)
{
array3[i]= 2;
}
return array3;
}
}
Is there a more conventional way to return array3 to array1 without cycle 1? Something along the lines of
array1[num][] = setValue();
Comments:
The method returns a new array, so no need to initialize temp, or better yet, initialize it to return value:
int[] temp = setValue();
Java doesn't have 2D arrays, just arrays of arrays, so the entire inner array can be replaced, instead of copying values:
for (int i = 0; i <= 4; i++) // cycle 1
{
array1[num] = temp;
}
When you do that, you shouldn't allocate the inner arrays, i.e. replace [5] with []:
int[][] array1 = new int[100][];
Now there is actually no need for temp anymore, leaving main as just:
int[][] array1 = new int[100][];
int num = 0;
array1[num] = setValue();
Since you probably want to fill the entire 2D array:
int[][] array1 = new int[100][];
for (int num = 0; num < array1.length; num++) {
array1[num] = setValue();
}
As #VinceEmigh hinted above you can simply do array1[num] = setValue();
see
int arr[][] = new int[5][];
for (int x = 0; x < arr.length; x++) {
arr[x] = setValue();
}
for (int x = 0; x < arr.length; x++) {
for (int y = 0; y < arr[x].length; y++) {
System.out.println(arr[x][y]);
}
}
Currently I'm trying to implement a way to be able to use vector- and matrix-multiplication in java, right now I have the code:
package ai2;
public class MyMatrix {
int[][] alpha;
int a;
int b;
int rowsB;
int colsB;
public MyMatrix(int a, int b) {
this.a = a;
this.b = b;
alpha = new int[a][b];
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
alpha[k][l] = 0;
}
}
}
public void insertValue(int o, int q, int z) {
this.alpha[o][q] = z;
}
public void print() {
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
System.out.print(this.alpha[k][l] + " ");
}
System.out.println();
}
}
public void multiplyMatrix(MyMatrix B) {
MyMatrix created = new MyMatrix(this.a, B.b);
for (int m = 0; m < a; m++) {
for (int k = 0; k < b; k++) {
for (int l = 0; k < this.a; l++) {
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
}
}
}
}
public static void main(String[] args) {
MyMatrix a = new MyMatrix(2, 2);
a.insertValue(0, 0, 1);
a.insertValue(1, 1, 1);
a.print();
MyMatrix b = new MyMatrix(2, 2);
b.insertValue(0, 0, 1);
b.insertValue(1, 0, 1);
// System.out.println(a);
}
}
The problem is my multiplyMatrix method, it takes a MyMatrix object but I cant reach the values using for example:
MyMatrixA[k][l]
I need some sort of idea to reach those values or perhaps a smarter implementation, I cannot use packages outside of java, thankful for any help!
Square brackets in Java are only for accessing array elements.
Your syntax there will not compile, and you cannot access your matrix elements that way.
Why don't you just implement a getAlpha getter in your MyMatrix class that returns the value for alpha (or better, a copy thereof, to ensure immutability)?
You could then reference it with theMatrixInstance.getAlpha()[k][l].
You could also simplify a bit and implement a get method taking two indices.
That would allow you to check whether the given indices are within the bounds of your two-dimensional array and throw a custom exception (or return some default value) rather than the ArrayIndexOutOfBoundsException you'd otherwise get.
Replace this line
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
with
created.alpha[i][j] += this.alpha[i][k] * B.alpha[k][j];
Or better yet, replace
MyMatrix created = new MyMatrix(this.a, B.b);
with
MyMatrix A = this;
MyMatrix C = new MyMatrix(this.a, B.b);
then you can do
C.alpha[i][j] += A.alpha[i][k] * B.alpha[k][j];
Which reads a little more clearly.
Finally, no need to initialize alpha with 0's in your constructor, this happens automatically.
I am trying to concatenate two two-dimensional arrays of different sizes. I have no idea why my method doesn't work. Java tells me, when I mouse over the "return xx": "Type mismatch: cannot convert from int[][] to int[]". When I mouse over "concatenateArr2d..." I get: "Illegal modifier for parameter concatenateArr2d: only final is permitted".
I don't understand why I am getting this error.
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int[][] xx = new int[t.length + s.length][];
for(i = 0; i < xx.length; i++)
{
xx[i] = new int[t[i].length + s[i].length];
}
return xx;
}
I still have to do the code to fill the entries but that should not be a problem.
Any help please? Thank you.
It looks to me that the code before the bit you pasted does not have aligned braces. You're probably inside a method when you try to declare this method.
public class HelloWorld{
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int jLength=0;
// The below line of code is to determine second dimension size of new array
jLength=Math.max(s[0].length, t[0].length);
int sIterate=0;
//new array created using size of first+second array for First dimension and maximum size for second dimension
int[][] xx = new int[t.length + s.length][jLength];
//first array copy
for(int i = 0; i < t.length; i++)
{
for(int j = 0; j < t[0].length; j++)
{
xx[i][j] =t[i][j];
}
}
//second array copy
for(int i = t.length; i < xx.length; i++)
{
for(int j = 0; j < s[0].length; j++)
{
xx[i][j] =s[sIterate][j];
}
sIterate++;
}
return xx;
}
public static void main(String []args){
int a[][]={{1,2},{2,3},{1,1}};
int b[][]={{1,2,3},{2,3,4}};
int c[][]=HelloWorld.concatenateArr2d(a,b);
//Output iteration
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c[0].length; j++)
{
System.out.print(c[i][j]);
}
System.out.println();
}
}
}
note : The blanks filled by 'primitive type default value' like, for int its 0.
Output :
120
230
110
123
234
I need to multiply two matrices. I understand pretty well how matrices work however in Java I am finding this a bit complex, so I researched a bit and found this.
public static int[][] multiply(int a[][], int b[][]) {
int aRows = a.length,
aColumns = a[0].length,
bRows = b.length,
bColumns = b[0].length;
int[][] resultant = new int[aRows][bColumns];
for(int i = 0; i < aRows; i++) { // aRow
for(int j = 0; j < bColumns; j++) { // bColumn
for(int k = 0; k < aColumns; k++) { // aColumn
resultant[i][j] += a[i][k] * b[k][j];
}
}
}
return resultant;
This code works fine. However the problem with this is that I need to multiply a single dimension matrix (1*5) by a multidimensional matrix (5*4), so the result will be (1*4) matrix and later on in the same program multiply a (1*4) matrix by a (4*3) matrix resulting in (1*3).
And I need to store the single dimension matrix in a normal array (double []) not multidimensional one!
I altered this code to the following but it still doesn't resolve the correct results.
public static double[] multiplyMatrices(double[] A, double[][] B) {
int xA = A.length;
int yB = B[0].length;
double[] C = new double[yB];
for (int i = 0; i < yB; i++) { // bColumn
for (int j = 0; j < xA; j++) { // aColumn
C[i] += A[j] * B[j][i];
}
}
return C;
Thanks in advance for any tips you may give :)
You can use RealMatrix to make it easier.
RealMatrix result = MatrixUtils.createRealMatrix(a).multiply(MatrixUtils.createRealMatrix(b));
double[] array = result.getRow(0);
class RotateMat {
static Integer[] swap(int x, int y) {
int a=x;
int b=y;
a=a^b;
b=a^b;
a=a^b;
return new Integer[]{a,b};
}
static int[][] rotate(int[][] arr) {
assert arr.length == arr[0].length;
int m = arr.length;
for (int i=0; i<m;i++) {
for (int k=0; k<m;k++) {
//int[] temp_arr = swap(arr[i][k], arr[k][i]);
//arr[i][k] = temp_arr[0];
//arr[k][i] = temp_arr[1];
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
}
}
print(arr);
return arr;
}
static void print(int[][] arr) {
int n=arr[0].length;
int m=arr.length;
assert m==n;
//System.out.println(m + " " + n);
for (int i=0; i<m;i++) {
for (int j=0; j<n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
int arr[][] = { {1,2,3}, {4,5,6}, {7,8,9}};
print(arr);
arr = rotate(arr);
print(arr);
}
}
I am a C user and trying to practice more java programming. I understand pass by value in java and that is the reason I try to return rotated array from rotate() function and assign it again to arr variable.
I get the same array printed even after I rotate....What am I doing wrong here?
In your second for loop, you are using the wrong variable. Change this:
for (int i=0; i<m;i++) {
for (int k=0; k<m;k++) {
^
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
To this:
for (int i=0; i<m;i++) {
for (int k=i; k<m;k++) {
^
int temp = arr[i][k];
arr[i][k] = arr[k][i];
arr[k][i] = temp;
This will produce output:
123
456 < First print statement in main method
789
147
258 < Print statement inside rotate method
369
147
258 < Second print statement in main method
369
(Note: I added the spaces between the print statements)
As you originally start with k = 0, you actually rotate the whole way round (which can be seen if you add debugging print statements).
You are actually rotating it twice, since you inner loop in rotate method works through the entire length.
Try for (int k=0; k<i; k++) instead.
You need to swap elements beneath the diagonal with those that are above.