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.
Related
I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
for(j=0;j
{
if(j>i)
d1+=a[i][j];. // Above the diagon
else
if(i>j)
d2+=a[i][j];. // Below the diagonal
}
Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.
For example, if I have the following 2d array:
int [][] array = {4,5,6},{3,4,5},{2,3,4};
I would want it to output an array as so:
{2 3 4}, {3 4 5}, {4 5 6}
Methodology:
a.) take the sums of each row and make a 1D array of the sums
b.) do a bubble sort on rowSum array
c.) swap the rows of the original array based on the bubble sort swaps made
d.) then print the newly row sorted array.
Here's my code so far:
public void sortedArrayByRowTot() {
int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
int [] rowSums = new int [tempArray2.length];
int sum = 0;
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
sum += tempArray2[i][j];
}
rowSums[i] = sum;
sum = 0;
}
int temp;
int i = -1;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
}
}
if(!isSwap){
break;
}
}
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
}
Not sure if I am doing part c of my methodology correctly?
It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"
As #shmosel said, you can do it like this:
public static void sortedArrayByRowTot() {
int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}
I was able to solve my question. Thanks.
public void sortedArrayByRowTot() {
//Creates tempArray2 to copy salaryArray into
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
//Copies salaryArray into tempArray2
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
//Creates rowSum array to store sum of each row
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Modified Bubble Sort of rowSum array (highest to lowest values)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] < rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
//Prints sorted array
System.out.println("Sorted array: ");
for (i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
System.out.print("$"+ tempArray2[i][j] + " ");
}
System.out.println();
}
}
You may try this way. That I have solved.
public class Solution{
public static void sortedArrayByRowTot() {
int [][] salaryArray = { {4,5,6},{3,4,5},{2,3,4} };
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
// Buble Sort to store rowSums
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Buble Sort by Rows Sum (Lowest Value to Highest)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
/** No Need.
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
*/
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
public static void main(String[] args) {
sortedArrayByRowTot();
}
}
How would i transfer a 2d array into a 1d array in java. I have the code for the 2d array but dont know where to start.
The output of the 2d array is a 8 by 10 grid with the numbers going from 1-80.
public class move
{
public static void main (String[] args)
{
int[][] twoarray = new int[8][10];
int i ;
int j ;
for(i =0; i < 8; i++)
{
for(j = 0; j < 10; j++)
twoarray[i][j] = (i * 10 + j+1);
}
for(i = 0; i < 8; i++)
{
for(j = 0; j < 10; j++)
{
System.out.print(twoarray[i][j]);
System.out.print(" ");
}
System.out.println();
}
int[] array = new int[80];
}
}
Using Java 8
int[] array = Stream.of(twoarray)
.flatMapToInt(IntStream::of)
.toArray();
Using Java 7 or older
int[] array = new int[80];
int index = 0;
for (int[] row : twoarray) {
for (int val : row)
array[index++] = val;
}
You can do in your for loop:
int[] array = new int[80];
int k=0;
for(i = 0; i < 8; i++){
for(j = 0; j < 10; j++){
array[k++]=twoarray[i][j];
}
}
I was wondering how it was possible to fill a ragged array with a loop in Java.
In my example I want to put Pascals Triangle in the Array. When I try to do it ragged, (
// int [][] hako = new int [n][]; -> as I understand it; it gives a java.lang.NullPointerException.
Thanks
int n = 12, r = 1;
int [][] hako = new int [n][];
for(int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
hako[i][j] = newton(i, j);
}
r++;
}
static int factorial(int n){
int k = 1;
if(n == 0)
return 1;
while(n>1){
k*=n;
n--;
}
return k;
}
static int newton(int i, int j){
return factorial(i)/((factorial(j))*(factorial(i-j)));
}
You need to initialize hako[i] as an array before you can assign a variable to an index within it i.e. hako[i][j].
int n = 12, r = 1;
int [][] hako = new int [n][];
for(int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
// need to initialize hako[i]
hako[i] = new int[r];
hako[i][j] = newton(i, j);
}
r++;
}
your hako, is a matrix, but you initialize only one dimension thus your NullPointerException
to fix it try
for(int i = 0; i < n; i++){
hako[i] = new int[r];
for(int j = 0; j < r; j++){
hako[i][j] = newton(i, j);
}
r++;
}
public static void main(String[] args) {
int y[][] = new int[4][];
int four =4;
for (int row = 0; row < y.length; row++) {
y[row] = new int[four--];
}
RaggedArray(y);
for (int row = 0; row < y.length; row++) {
for (int column = 0; column < y[row].length; column++) {
System.out.print(y[row][column] + " ");
}
System.out.println();
}
}
public static void RaggedArray(int x[][]) {
int j;
for (int i = 0; i < x.length; i++) {
int k=1;
for (j = 0;j<x[i].length ; j++) {
x[i][j] = k++;
}
}
}}
You can change the size and fill it with any data. I wish it will be useful for u and anyone see this code.
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++)