This is what I want to do when A is a square matrix.
P - is power.
A & B are square matrices.
User will be asked to enter size of matrix A, and elements of matrix A and to what power they want to raise the matrix to.
Once they input what power, and what elements my program is supposed to calculate this:
(Assuming P = 5)
A^5 + A^4 + A^3 + A^2 + A
I have written a method that adds matrices a method that multiplies them, and a method that raises them to the power and they all work correctly.
The problem I am having is the final step which I showed above A^5 + A^4 + A^ 3...
This is where the problem gets even weirder, my program works when the elements in the matrix are all the same... such that a
2 2 2
2 2 2
2 2 2
matrix will give me the CORRECT output, BUT
1 2 3
4 5 6
7 8 9
matrix will give me the WRONG output and I have no idea why.
This is the method in which the problem is occuring
public static void addPowers(int [][] a, int[][] b, int p) {
while( p != 1){
b = addMatrices(powerMatrix(a,p), b) ;
addPowers(a,b,p-1) ;
return ;
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++)
System.out.print(b[i][j] + "\t") ;
System.out.println();
}
}
Just in case you ask, reason I have the recursive under a while loop is so it won't print over and over and over again.
Thanks for your time! :)
Edit: More clarifying information.
addMatrices is a method that adds matrices with an two int[][] arguments.
powerMatrix is a method that finds the power of a matrix with (int[][], int) arguments.
EDIT Methods being called...
public static int[][] multiplyMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int matrix[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++)
{
for (int l = 0; l < matrixA.length; l++)
{
sum += matrixA[i][l] * matrixB[l][j] ;
}
temp[i][j] = sum ;
sum = 0 ;
}
}
matrix = temp;
return matrix ;
}
public static int[][] addMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++) {
{
sum = matrixA[i][j] + matrixB[i][j] ;
}
temp[i][j] = sum ;
}
}
return temp ;
}
public static int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; n++)
result = multiplyMatrices(result, a);
return result;
}
In your addMatrices method, you should remove the third loop.
Like this:
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {
temp[i][j] = matrixA[i][j] + matrixB[i][j] ;
}
}
Related
This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
Closed 3 years ago.
I am working with 2-D arrays and I require help on this topic. My task is to create a 2-D array such that it is n by n (i.e. the number of rows and columns are equal). Fill the array with alternating 0's and 1's
void setup()
{
int n=3;
// code to populate the array
// code to display the output of array in a table format
/* output should be as follows:
The expected result when n=3 should be as the following:
1 0 1
0 1 0
1 0 1
*/
}
Solution:
class test{
public static void main(String[] args) {
int n = 3;
int[][] arr = setup(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
static int[][] setup(int n){
int[][] arr = new int [n][n];
boolean even = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = even ? 1 : 0;
even = !even;
}
}
return arr;
}
}
Output:
0 1 0
1 0 1
0 1 0
This should work.
You can replace the 3 that is given to n with any number you want as the 2D-Array's length.
void setup(){
int n = 3;
int count = 0;
int[][] myArray = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(count % 2 == 0){
myArray[i][j] = 1;
}
else{
myArray[i][j] = 0;
}
System.out.print(myArray[i][j] + " ");
count++;
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
It's not complex, you just have to iterate two loops, that's it. Although you can get the solution on different ways.
public static void main(String[] args) {
int n = 3;
int [][] arr = new int[n][n];
int val = 1;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
arr[i][j] = val;
val = (val == 0) ? 1 : 0;
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
A simple implementation:
void setup()
{
int n=3;
final int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((n * i + j) % 2 == 0) {
array[i][j] = 1;
}
}
}
}
Here is how you can approach your logic , create a counter and negate each time after it prints value.
public static void main(String[] args) {
int counter = 0;
int n = 3;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(counter==0?1:0);
counter = ~counter;
}
System.out.println();
}
}
Output
101
010
101
Here is Online source code.
I want to create a 1D array that saves the min columns from my 2D array, but I get wrong the min values. My theseisLine array is a copy from my intP array that I store there the column numbers, so theseisLine shows the min from each column.
package themab2018;
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;
public class THEMAB2018 {
static void displayP(int intP[][]) {
System.out.println("intP2D");
for(int i = 0; i < intP.length; i++) {
for(int j = 0; j < intP[i].length; j++)
System.out.print(intP[i][j] + " ");
System.out.println();
}
}
static void findMinCol(int intP[][] ,int n) {
int theseisLine[] = new int[n];
if(theseisLine.length < intP.length)
for(int i = 0; i < theseisLine.length; i++)
theseisLine[i] = intP[0][i];
else
for(int i = 0; i < intP.length; i++)
theseisLine[i] = intP[0][i];
int min = theseisLine[0];
System.out.println();
System.out.println("Min Array");
for(int i = 0; i < theseisLine.length; i++) {
if(theseisLine[i] < min) {
min = theseisLine[i];
}
System.out.print(min + " ");
}
}
public static void main(String[] args){
int m , n;
System.out.println("Import m , n");
do {
System.out.print("Give m ");
m = scannerUserInput.getInteger();
System.out.print("Give n ");
n = scannerUserInput.getInteger();
} while (m < 1 && n < 1);
int intP2D[][] = new int [m][n];
int theseisLine[] = new int[n];
for(int i = 0; i < intP2D.length; i++){
for(int j = 0; j < intP2D[i].length; j++) {
intP2D[i][j] = (int) (Math.random() * (10 - 1)+1)+1;
}
}
displayP(intP2D);
findMinCol(intP2D, m);
}
}
The result that I get example :
Import m , n
Give m 3
Give n 4
intP2D
3 9 7 2
8 9 7 6
5 8 8 7
Min Array
3 3 3
The result that i want in this example :
Import m , n
Give m 3
Give n 4
intP2D
3 9 7 2
8 9 7 6
5 8 8 7
Min Array
3 8 7 2
Firstly, while calling findMinCol(intP2D, m); you need to pass the count of column i.e. n and not count of row.
Secondly, while calculating the min element in the column, you are comparing all element with int min = theseisLine[0]; which might not be correct.
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;
public class THEMAB2018 {
static void displayP(int intP[][]) {
System.out.println("intP2D");
for(int i = 0; i < intP.length; i++) {
for(int j = 0; j < intP[i].length; j++)
System.out.print(intP[i][j] + " ");
System.out.println();
}
}
static void findMinCol(int intP[][] ,int n) {
int theseisLine[] = new int[n];
for(int i = 0; i < theseisLine.length; i++)
theseisLine[i] = intP[0][i];
System.out.println();
System.out.println("Min Array");
for(int i = 0; i < theseisLine.length; i++) {
for (int j = 1; j < intP.length; j++) {
if (intP[j][i] < theseisLine[i]) {
theseisLine[i] = intP[j][i];
}
}
System.out.print(theseisLine[i] + " ");
}
}
public static void main(String[] args){
int m , n;
System.out.println("Import m , n");
m = 3; n = 4;
int intP2D[][] = new int [m][n];
int theseisLine[] = new int[n];
for(int i = 0; i < intP2D.length; i++){
for(int j = 0; j < intP2D[i].length; j++) {
intP2D[i][j] = (int) (Math.random() * (10 - 1)+1)+1;
}
}
displayP(intP2D);
findMinCol(intP2D, **n**);
}
}
the output I am getting:
intP2D
2 5 8 7
10 6 9 3
7 9 3 8
Min Array
2 5 3 3
I don't know what you want to check in your finding method with the if-else block. You don't need it anyway to find the minimum of each column, that's why I removed it. A simple nested for loop solves your problem.
Additionally, you don't need to pass the number of columns as a parameter, because it can be easily queried from the matrix. I still left it in to avoid having to change the method call.
static void findMinCol(int intP[][] ,int n) {
int rows = intP.length;
int cols = intP[0].length;
int[] result = new int[cols];
for(int i = 0; i < cols; i++){
int min = Integer.MAX_VALUE;
for(int j = 0; j < rows; j++){
if(min > intP[j][i]){
min = intP[j][i];
}
}
result[i] = min;
}
for(int i = 0; i < result.length; i++) {
System.out.print(result[i] + " ");
}
}
I am using this loop structure but it fails to generate all the submatrix that are possible for any given 2D matrix with n rows and m columns.
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
System.out.println("sub-MATRIX:");
for(k=i;k<n;k++)
{
for(p=j;p<m;p++)
{
System.out.print(arr[k][p]+" ");
}
System.out.println();
}
}
}
Ex: Given matrix 3X3 : [[1 2 3],[4 5 6],[7 8 9]]
Then its submatrix will be:
for size 1:
[1],[2],[3],[4],[5],[6],[7],[8],[9]
for size 4:
[[1,2],[4,5]],[[2,3],[5,6]],[[4,5],[7,8]] and [[5,6],[8,9]]
and so on
You are missing a couple more loops to cover all cases. PrintMatyrix() should have 2 nested loops for printing contents.
for (i = 1; i < n; ++i)
{
for (j = 1; j < m; ++j)
{
// we are at each sub matrix of size(i,j)
for (k = 0; k <= (n - i); ++k)
{
for (p = 0; p <= (m - j); ++p)
{
// we are at submatrix of size(i,j) starting at (k,p)
// assuming PrintMatrix(Matrix&, int rows, int cols, int r0, int c0);
PrintMatrix(arr, i, j, k, p);
}
}
}
}
If we have a matrix with dimensions M x N, and the sub matrix we are looking for is with K x L dimensions. If there is more optimized solution, please share.
for (int i = 0; i < m-k+1; i++) {
for (int j = 0; j < n-l+1; j++) {
for (int p = 0; p < k; p++) {
for(int q = 0; q < l; q++) {
System.out.print(arr[i+p][j+q] + " ");
}
System.out.println();
}
System.out.println("*****************");
}
}
You should not loops, you should use some recursions.
Think about this way, for each row or column, you either take it or throw away it. So you can select rows first and then columns and based on the rows and columns selected you construct the submatrix.
Some code,
bool rowTaken[N], columnTaken[M];
void constructSubMatrixRow(int i)
{
if (i >= N) constructSubMatrixCol(0);
rowTaken[i] = true;
constructSubMatrix(i+1);
rowTaken[i] = false;
constructSubMatrix(i+1);
}
void constructSubMatrixCol(int i)
{
if (i >= M) printSubMatrix();
columnTaken[i] = true;
constructSubMatrixCol(i+1);
columnTaken[i] = false;
constructSubMatrixCol(i+1);
}
void printSubMatrix()
{
for (unsigned i = 0; i < N; i++)
if (rowTaken[i]){
for (unsigned j = 0; j < M; j++)
if (columnTaken[j])
print matrix[i][j]
}
}
I want to enter 2 dimensional arrays by joptionpane and display the multiplication of it by java,
I tried do this but I don't no why the result always is (0 0 0),I think that the result arrays is empty! could anyone help me ....!!??
System.out.print("can not multiply");
}
public static double[][] multiplyMatrix(double[][] x, double[][] z) {
double[][] result = new double[x.length][z[0].length];
for (int i = 0; i < x.length; i++)
for ( int j = 0; j <z[0].length; j++){
result[i][j]=0;
for (int k = 0; k < z.length; k++)
result[i][j] += x[i][k] * z[k][j];}
return result;
}
You populate your A array in both of your for loops. You have to populate B in the second for loop.
double[][] B = new double[n2][m2];
int k;
int l;
for (k = 0; k < n2; k++) {
for (l = 0; l < m2; l++) {
String s1 = JOptionPane.showInputDialog("Enter B" + "[" + (k) + (l) + "]" + " element ");
//A[k][l] = Integer.parseInt(s1); //This should be populating B
B[k][l] = Integer.parseInt(s1); //Change it to this
}
}
After fixing that issue, you still have some bugs in your multiplication method. But now that you actually get a result array, you can debug it pretty easily.
Hope this helps.
So I have been working on this problem for a while now. I keep getting an ArrayIndexOutOfBoundsException but I am unable to locate where the issue lies. If someone could point me in the right direction, I would really appreciate it! Thanks!
public class Answer {
public static void main(String[] args){
double[] y = {23, 11.1, 50.4};
double[] x = {22.2, 46, 100.0};
Answer answer = new Answer();
answer.answer(y, x);
}
public static int answer(double[] y, double[] x) {
int result = 0;
double percent_1, percent_2;
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
// Calculate percent of first 2 x value array items with y
// all y values. Store the results in a seperate list.
for(int i = 0; i < x.length; i++){
percent_1 = compare(y[i], x[0]);
percent_2 = compare(y[i], x[1]);
compareList_1[i] = percent_1;
compareList_2[i] = percent_2;
}
// Compare those lists to find common number
// There you have your answer.
result = (int)compareLists(compareList_1, compareList_2);
return result;
}
// Calculates percentage from x and y values
public static double compare(double y, double x){
double result = 1 - (y/x);
return result;
}
// Finds common value in lists
public static double compareLists(double[] list_1, double[] list_2){
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
if(list_1[i] == list_2[j]){
return list_1[i];
}
}
}
// Just cus this shouldn't ever return.
return 100;
}
}
In your iteration (compareLists), you should use 'length' (not length + 1)
for(int i = 0; i < list_1.length; i++)
for(int j = 0; j < list_2.length; i++)
I think the problerm is in
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
i < list_1.length + 1 or j < list_2.length + 1 change it to
for(int i = 0; i < list_1.length; i++){
for(int j = 0; j < list_2.length ; j++){
remove +1 from each condition.For j < list_2.length + 1 the list_2.length will give you length of array ie lastIndex +1 and you are adding another +1 in it causing loop condition to be j<lastIndex +1 giving you index error on the last iteration of loop in the line if(list_1[i] == list_2[j]){ for list_2[j]
Also in answer method you declare array by
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
and in the loop you are iterating upto x.length if x.length is greater than y.length the you can get the Index error in compareList_2[i] = percent_2;(inside the loop) because its length is y.length.