Function in a function in java - java

Is there a way to use the first function in the second one to create a double array with random numbers?
public static int[] build1(int size) {
int[] arr = new int[size];
for (int i=0 ; i < arr.length ; i++)
arr[i] = (int)(Math.random() * 127);
return arr;
}
public static int[][] build2(int row, int col) {
int[][] arr2 = new int[row][col];
for (int i = 0; i < arr2.length; i++) {
for (int j = 0; j < arr2[i].length; j++) {
arr2[i][j] = (int)(Math.random() * 127);
}
}
return arr2;
}

I would assume the following should work.
public static int[][] build2(int row, int col) {
int[][] arr2 = new int[row][col];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = build1(col);
}
return arr2;
}

Related

Matrix multiply in Java

I created a function to multiply a matrix by itself which gets 2 parameters, one is the matrix, the other one is an int n. The problem is that I cant figure out where should I use the n in my code so that it multiplies the matrix by itself an n number of times (in other words matrix^n). At current stage it only does matrix^2;
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * array[x][j];
}
newArray[i][j] = sum;
}
}
return newArray;
}
Add a third for loop that goes from 1 < k < n . You will need to remain array untouched in order to maintain the values of the initial matrix, will also need a matrix newArray to keep the values of the previous multiplication and a temporary matrix tmp that just hold values during the multiplication itself and then is copied to newArray.
Take a look in the sample below.
FULL CODE
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Just holds values during multiplication between two matrices
int[][] tmp = new int[array.length][array.length];
// Initialize newArray to be equal to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
// Outer loop that multiplies as many times as you want
for (int k = 1; k < n; k++) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
tmp[i][j] = sum;
}
}
// Copy the result from multiplication to newArray and restart tmp
System.arraycopy(tmp, 0, newArray, 0, tmp.length);
tmp = new int[array.length][array.length];
}
return newArray;
}
Hope it helped!
You can create two methods for clarity: the first to multiply a square matrix, and the second to call the first n number of times.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = array;
for (int i = 0; i < n; i++) {
newArray = squareMatrixMultiplication(newArray);
}
return newArray;
}
public static int[][] squareMatrixMultiplication(int[][] array) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
for (int x = 0; x < array.length; x++) {
newArray[i][j] += array[i][x] * array[x][j];
}
}
}
return newArray;
}
Initialize newArray to be equal to array, then
add a loop around the matrix multiplication and use newArray in your nested loops: multiply newArray by array.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Add loops to initialize newArray to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
for (int j = 0; j < n; j++) { // Add this loop
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
newArray[i][j] = sum;
}
}
} // and this
return newArray;
}
public class MyClass {
public static void main(String args[]) {
int array[][] = new int[2][2];
array[0][0] = 1;
array[0][1] = 2;
array[1][0] = 3;
array[1][1] = 4;
int newArray[][] = new int[2][2];
//initialize array with these elements
newArray[0][0] = 1;
newArray[0][1] = 0;
newArray[1][0] = 0;
newArray[1][1] = 1;
int n = 5;
for (int i = 0; i < n; i++) {
newArray = lungimeDrumuri(array, newArray, i);
}
}
public static int[][] lungimeDrumuri(int[][] array, int newArray[][], int n) {
int newArray1[][] = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * newArray[x][j];
}
newArray1[i][j] = sum;
}
}
return newArray1;
}
}
Hope this one will help you.

Java deepToString to array - matrix multiplication

Can someone help me with something?
I'm trying to convert a string which was initially created using the deepToString() method, back to an array. I've tried pretty much anything I could find on Stack Overflow… but no luck.
This is what I have right now:
import java.util.*;
public class Test3 {
static int matrix [][] = new int[2][2];
public static int[][] matrixGenerator() {
Random r = new Random( );
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt( 10000 );
}
}
return matrix;
}
public static void main(String args[]){
String matrix1 = Arrays.deepToString(matrixGenerator());
String matrix2 = Arrays.deepToString(matrixGenerator());
System.out.println(matrix1 + '\n' + matrix2);
}
}
This outputs
[[6030, 3761], [6605, 5582]]
and
[[1799, 461], [1197, 1012]]
Which is exactly what I need. Now I'm trying to do a matrix multiplication using this piece of code.
int m1rows = matrix1.length;
int m1cols = matrix1[0].length;
int m2cols = matrix2[0].length;
int[][] result = new int[m1rows][m2cols];
for (int i = 0; i < m1rows; i++) {
for (int j = 0; j < m2cols; j++) {
for (int k = 0; k < m1cols; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
The problem is that I cannot loop through the array because it's not actually an array, it's a string. Which makes sense. Can someone tell me how can I loop, though? I've tried to convert the string back to array - but no luck
Why do you need convertion of matrix to String and then back to matrix?
Can you simply use
public static void main(String[] args) {
int matrix1 [][] = matrixGenerator();
int matrix2 [][] = matrixGenerator();
int matrix3 [][] = matrixMultiplication(matrix1, matrix2);
String matrix1Str = Arrays.deepToString(matrix1);
String matrix2Str = Arrays.deepToString(matrix2);
String matrix3Str = Arrays.deepToString(matrix3);
System.out.println(matrix1Str+'\n'+matrix2Str+'\n'+matrix3Str);
}
public static int[][] matrixGenerator(){
int matrix [][] = new int[2][2];
Random r = new Random( );
for(int i=0; i < matrix.length; i++){
for(int j=0; j < matrix[i].length; j++){
matrix[i][j] = r.nextInt( 10000 );
}
}
return matrix;
}
public static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) {
int m1rows = matrix1.length;
int m1cols = matrix1[0].length;
int m2cols = matrix2[0].length;
int[][] result = new int[m1rows][m2cols];
for (int i=0; i< m1rows; i++){
for (int j=0; j< m2cols; j++){
for (int k=0; k< m1cols; k++){
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}

transpose double[][] matrix with a java function?

Do anybody have a function with which I can transpose a Matrix in Java which has the following form:
double[][]
I have function like this:
public static double[][] transposeMatrix(double [][] m){
for (int i = 0; i < m.length; i++) {
for (int j = i+1; j < m[0].length; j++) {
double temp = m[i][j];
m[i][j] = m[j][i];
m[j][i] = temp;
}
}
return m;
}
but its wrong somewhere.
public static double[][] transposeMatrix(double [][] m){
double[][] temp = new double[m[0].length][m.length];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[0].length; j++)
temp[j][i] = m[i][j];
return temp;
}
If you would like to use an external library, Apache Commons Math provides the utility to transpose a matrix. Please refer to it official site.
First, you have to create a double array double[][] arr, as you have already done. Then, the transposed 2d matrix can be achieved like this
MatrixUtils.createRealMatrix(arr).transpose().getData()
Since Java 8, you can do this:
public static double[][] transposeMatrix(final double[][] matrix) {
return IntStream.range(0, matrix[0].length)
.mapToObj(i -> Stream.of(matrix).mapToDouble(row -> row[i]).toArray())
.toArray(double[][]::new);
}
Java Class to Transpose a matrix :-
import java.util.Scanner;
public class Transpose {
/**
* #param args
*/
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
col = m;
int n = sc.nextInt();
row = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
int[][] trans_arr = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
trans_arr[j][i] = arr[i][j];
}
}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans_arr[i][j] + " ");
}
System.out.println();
}
}
}
Here is the method
public static double[][] transpose(double arr[][]){
int m = arr.length;
int n = arr[0].length;
double ret[][] = new double[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ret[j][i] = arr[i][j];
}
}
return ret;
}
Here is a code to transpose a two dimensional matrix "In Place" (not using another data structure to save output) and hence is more memory efficient:
Same below algorithm can be used for int or char or string data types as well.
public static double[][] transposeDoubleMatrix(double[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
double tmp = matrix[j][i];
matrix[j][i] = matrix[i][j];
matrix[i][j] = tmp;
}
}
return matrix;
}
Here's a small change!
for (int j = i; j < m[0].length; j++)

Debugging Mergesort Implementation

Okay, I know this question doesn't show research effort, but I've been going through this code so many times and I couldn't figure out was I was doing wrong. I know there are many Mergesort implementation examples but I wanted to do it my way. Any help is appreciated, thanks.
import java.util.Scanner;
public class MergeSort
{
public static int[] mergeSort(int[] arr)
{
if (arr.length > 1)
{
int[] arr1 = splitLeft(arr);
int[] arr2 = splitRight(arr);
arr1 = mergeSort(arr1);
arr2 = mergeSort(arr2);
return merge(arr1, arr2);
}
else
return arr;
}
public static int[] splitLeft(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[middle];
for (int i = 0; i < middle; i++)
newarr[i] = arr[i];
return newarr;
}
public static int[] splitRight(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[arr.length - middle];
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
return newarr;
}
public static int[] merge(int[] arr1, int[] arr2)
{
int[] sorted = new int[arr1.length+arr2.length];
int i1 = 0;
int i2 = 0;
int i = 0;
while (i1 < arr1.length && i2 < arr2.length)
{
if (arr1[i1] < arr2[i2])
{
sorted[i] = arr1[i1];
i1++;
}
else
{
sorted[i] = arr2[i2];
i2++;
}
i++;
}
while (i1 < arr1.length)
{
sorted[i] = arr1[i1];
i1++;
i++;
}
while (i2 < arr2.length)
{
sorted[i] = arr1[i2];
i2++;
i++;
}
return sorted;
}
public static int getNum(int x)
{
int num = (int)(Math.random()*x + 1);
return num;
}
public static void printArr(int[] arr)
{
System.out.println();
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
static Scanner reader = new Scanner(System.in);
public static void main(String [ ] args)
{
int i;
System.out.println("Type the length of the array");
int n = reader.nextInt();
System.out.println("Type the range of the random numbers generator");
int range = reader.nextInt();
int[]arr = new int[n];
for (i = 0; i < n; i++)
arr[i] = getNum(range);
printArr(arr);
int[] sorted = new int[n];
sorted = mergeSort(arr);
printArr(sorted);
}
}
I think the problem is in your splitRight function. Consider this code:
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
This tries to copy the ith element from arr to the ith position of newarr, but this is incorrect. For example, if the array arr has ten elements, you want to copy element 5 of arr to position 0 of newArr, element 6 of arr to position 1 of newarr, etc.
To fix this, consider trying something like this:
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
Hope this helps!
When you do
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
You are surely asking for positions in the original array and at the same time looking for them in the new array (which happens to be shorter).

how to transfer elements from 2-d array in 1-d array in same sequence?

how to transfer elements from 2-d array in 1-d array in same sequence?
Here are the most likely scenarios I see.
class nikhil {
public static int[] firstIndex(int[][] arr2d) {
int rows = arr2d.length;
if(rows == 0) return new int[0];
int cols = arr2d[0].length;
if(cols == 0) return new int[0];
int[] arr1d = new int[rows * cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
arr1d[i * cols + j] = arr2d[i][j];
}
}
return arr1d;
}
public static int[] secondIndex(int[][] arr2d) {
int rows = arr2d.length;
if(rows == 0) return new int[0];
int cols = arr2d[0].length;
if(cols == 0) return new int[0];
int[] arr1d = new int[rows * cols];
for(int i = 0; i < cols; i++) {
for(int j = 0; j < rows; j++) {
arr1d[i * rows + j] = arr2d[j][i];
}
}
return arr1d;
}
public static int[] sorted(int[][] arr2d) {
int[] arr1d = firstIndex(arr2d);
java.util.Arrays.sort(arr1d);
return arr1d;
}
public static int[] scramble(int[][] arr2d) {
int[] arr1d = firstIndex(arr2d);
java.util.List<Integer> list = new java.util.ArrayList<Integer>();
for(int i : arr1d) list.add(i);
java.util.Collections.shuffle(list);
for(int i = 0; i < list.size(); i++) arr1d[i] = list.get(i).intValue();
return arr1d;
}
public static void main(String[] args) {
/*
5 4 6 10
3 1 9 12
8 2 7 0
*/
final int rows = 3;
final int cols = 4;
int[][] arr2d = new int[rows][cols];
arr2d[0][0] = 5;
arr2d[0][1] = 4;
arr2d[0][2] = 6;
arr2d[0][3] = 10;
arr2d[1][0] = 3;
arr2d[1][1] = 1;
arr2d[1][2] = 9;
arr2d[1][3] = 12;
arr2d[2][0] = 8;
arr2d[2][1] = 2;
arr2d[2][2] = 7;
arr2d[2][3] = 0;
int[] first = firstIndex(arr2d);
int[] second = secondIndex(arr2d);
int[] sorted = sorted(arr2d);
int[] scrambled = scramble(arr2d);
System.out.println(java.util.Arrays.toString(first));
System.out.println(java.util.Arrays.toString(second));
System.out.println(java.util.Arrays.toString(sorted));
// for oli
System.out.println(java.util.Arrays.toString(scrambled));
}
}
Though already answered here, I will post the solution here with an example.
Suppose you have a 2D array e.g originalArray [ ][ ]
int a [] = {1,2,6,7,2};
int b [] = {2,44,55,2};
int c [] = {2,44,511,33};
int originalArray [][] = new array[][]{a,b,c};
Case 1 :
If all the above 1D arrays have the same length, then you can proceed like this :
int[] newArray = new int[3 * a.length];
int index = 0;
for (int n = 0; n < a.length; n++) {
newArray[index++] = a[n];
newArray[index++] = b[n];
newArray[index++] = c[n];
}
Case 2 :
If all of the above 1D arrays are of different length, then you can procees in this way,
int[] newArray = new int[a.length + b.length + c.length];
System.arrayCopy(a, 0, newArray, 0, a.length);
System.arrayCopy(b, 0, newArray, a.length, b.length);
System.arrayCopy(c, 0, newArray, a.length + b.length, c.length);

Categories