Gaussian Elimination Java - java

I have this example matrix:
[4,1,3]
[2,1,3]
[4,-1,6]
and i want to solve exuotions:
4x1+1x2+3x3=v
2x1+1x2+2x3=v
4x1-1x2+6x3=v
x1+x2+x3=1
it will be: 4x1+1x2+3x3 = 2x1+1x2+2x3 = 4x1-1x2+6x3
-2x1+x2-5x3 =0
and I use the code:
import java.util.*;
public class GaussianElimination {
// This is the problem we solved in class
private static double[][] problem1 = {
// x = 1, y = 2, z = 3
{ 1, 2, 3, 14 }, // 1x + 2y + 3z = 14
{ 1, -1, 1, 2 }, // 1x - 1y + 1z = 2
{ 4, -2, 1, 3 } // 4x - 2y + 1z = 3
};
public static void solve(double[][] c, int row) {
int rows = c.length;
int cols = rows + 1;
// 1. set c[row][row] equal to 1
double factor = c[row][row];
for (int col=0; col<cols; col++)
c[row][col] /= factor;
// 2. set c[row][row2] equal to 0
for (int row2=0; row2<rows; row2++)
if (row2 != row) {
factor = -c[row2][row];
for (int col=0; col<cols; col++)
c[row2][col] += factor * c[row][col];
}
}
public static void solve(double[][] c) {
int rows = c.length;
for (int row=0; row<rows; row++)
solve(c,row);
}
public static void print(double[][] c) {
int rows = c.length;
int cols = rows + 1;
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++)
System.out.printf("%5.1f ",c[row][col]);
System.out.println();
}
System.out.println();
}
public static void printSolution(double[][] c) {
int rows = c.length, cols = rows + 1;
char variable = (char)((rows > 3) ? ('z' - (rows-1)) : 'x');
System.out.println("Solution:\n");
for (int row=0; row<rows; row++)
System.out.printf(" %c = %1.1f\n",(char)variable++,c[row][cols-1]);
System.out.println();
}
public static void doProblem(double[][] problem, String description) {
System.out.printf("******* %s ********\n",description);
System.out.println("Original Equations:");
print(problem);
solve(problem);
System.out.println("Solved (reduced row echelon form):");
print(problem);
printSolution(problem);
}
public static void main(String[] args) {
doProblem(problem1,"Problem 1 (from class)");
}
}
How do I set the matrix in private static double[][] problem1 so that I get x1,x2,x3?

I don't really understand your question or problem. However I see some bugs in the row reduction echelon form solving method. I recently wrote this method as well. Mine works. Since I don't suspect this to be a Java homework assignment but rather an interest in programming mathematical algorithms, I will just throw in my code. I recommend taking a look at how the rref method is actually defined in the world of maths.
The bug I spotted is that the factor you use is wrong. Take a look at my code (note that it doesn't put zero rows to the bottom of the matrix):
public static double[][] rref(double[][] mat)
{
double[][] rref = new double[mat.length][mat[0].length];
/* Copy matrix */
for (int r = 0; r < rref.length; ++r)
{
for (int c = 0; c < rref[r].length; ++c)
{
rref[r][c] = mat[r][c];
}
}
for (int p = 0; p < rref.length; ++p)
{
/* Make this pivot 1 */
double pv = rref[p][p];
if (pv != 0)
{
double pvInv = 1.0 / pv;
for (int i = 0; i < rref[p].length; ++i)
{
rref[p][i] *= pvInv;
}
}
/* Make other rows zero */
for (int r = 0; r < rref.length; ++r)
{
if (r != p)
{
double f = rref[r][p];
for (int i = 0; i < rref[r].length; ++i)
{
rref[r][i] -= f * rref[p][i];
}
}
}
}
return rref;
}

The following code adapted from Rosettacode.org takes into account moving rows up/down as well:
static public void rref(double [][] m)
{
int lead = 0;
int rowCount = m.length;
int colCount = m[0].length;
int i;
boolean quit = false;
for(int row = 0; row < rowCount && !quit; row++)
{
print(m);
println();
if(colCount <= lead)
{
quit = true;
break;
}
i=row;
while(!quit && m[i][lead] == 0)
{
i++;
if(rowCount == i)
{
i=row;
lead++;
if(colCount == lead)
{
quit = true;
break;
}
}
}
if(!quit)
{
swapRows(m, i, row);
if(m[row][lead] != 0)
multiplyRow(m, row, 1.0f / m[row][lead]);
for(i = 0; i < rowCount; i++)
{
if(i != row)
subtractRows(m, m[i][lead], row, i);
}
}
}
}
// swaps two rows
static void swapRows(double [][] m, int row1, int row2)
{
double [] swap = new double[m[0].length];
for(int c1 = 0; c1 < m[0].length; c1++)
swap[c1] = m[row1][c1];
for(int c1 = 0; c1 < m[0].length; c1++)
{
m[row1][c1] = m[row2][c1];
m[row2][c1] = swap[c1];
}
}
static void multiplyRow(double [][] m, int row, double scalar)
{
for(int c1 = 0; c1 < m[0].length; c1++)
m[row][c1] *= scalar;
}
static void subtractRows(double [][] m, double scalar, int subtract_scalar_times_this_row, int from_this_row)
{
for(int c1 = 0; c1 < m[0].length; c1++)
m[from_this_row][c1] -= scalar * m[subtract_scalar_times_this_row][c1];
}
static public void print(double [][] matrix)
{
for(int c1 = 0; c1 < matrix.length; c1++)
{
System.out.print("[ ");
for(int c2 = 0; c2 < matrix[0].length-1; c2++)
System.out.print(matrix[c1][c2] + ", ");
System.out.println(matrix[c1][matrix[c1].length-1] + " ]");
}
}
static public void println()
{
System.out.println();
}

Related

is there any way to simplify my code for matrix multiplication?

public class J1_LAB08_1 {
public static void main(String[] args) {
int r1 = 5, c1 = 3;//rows and column for matrix a
int r2 = 3, c2 = 4;//rows and column for matrix b
int matrixA[][] = new int[5][3];//initialize matrix a
System.out.println("Matrix A");
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {//create random single integer matrix
matrixA[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixA[i][j]);//print matrix a
}
System.out.println();
}
System.out.println();
System.out.println("Matrix B");
int matrixB[][] = new int[3][4];
for (int i = 0; i < matrixB.length; i++) {
for (int j = 0; j < matrixB[i].length; j++) {//create random single integer matrix
matrixB[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixB[i][j]);//print matrix b
}
System.out.println();
}
System.out.println();
int[][] matrixC = multiplyMatrices(matrixA, matrixB, r1, c1, c2);//pass variables to multiply matrices function
printC(matrixC);//print matrix c
}
public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB, int r1, int c1, int c2){//multiply the 2 given matrices and return the product
int[][] matrixC = new int[r1][c2];//initialize the product matrix using row a and column 2 as its parameters
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];//multiply using textbook formula
}
}
}
return matrixC;
}
public static void printC(int[][] matrixC) {//print the matrix
System.out.println("A x B is: ");
for(int[] row : matrixC) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
is there any way to simplify my code for matrix multiplication?
the resulting matrix should be 3 x 5 after multiplication
any help would be greatly appreciated, thank you for your time and consideration.

Knight's Tour code runs into infinite loop, does not reach a solution

My Recursive Backtracking approach to Knight's Tour runs into an infinite loop. At first, I thought the problem might be taking this much time in general but some solutions do it in an instant. Please tell what is wrong with my code.
package io.github.thegeekybaniya.InterviewPrep.TopTopics.Backtracking;
import java.util.Arrays;
public class KnightsTour {
private static int counter=0;
public static void main(String[] args) {
knightsTour(8);
}
private static void knightsTour(int i) {
int[][] board = new int[i][i];
for (int[] arr :
board) {
Arrays.fill(arr, -1);
}
board[0][0] = 0;
knightsTour(board,0,1);
}
private static boolean knightsTour(int[][] board, int cellno, int stepno) {
if (stepno == board.length * board.length) {
printBoard(board);
return true;
}
int[][] dirs = {
{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}
};
int row = cellno / board.length, col = cellno % board.length;
for (int i = 0; i < dirs.length; i++) {
int r = dirs[i][0] + row;
int c = dirs[i][1] + col;
if (isSafe(board, r, c)&&board[r][c]==-1) {
int ncell = r * board.length + c;
board[r][c] = stepno;
if (knightsTour(board, ncell, stepno + 1)) {
return true;
} else {
board[r][c] = -1;
}
}
}
return false;
}
private static boolean isSafe(int[][] board, int r, int c) {
return r >= 0 && c >= 0 && r < board.length && c < board.length;
}
private static void printBoard(int[][] board) {
System.out.println(++counter);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j]+" ");
}
System.out.println();
}
}
}
There's no bug in your code, it's just that the brute force approach is slow because the search space is enormous. You can speed up the search by implementing Warnsdorf's Rule. This is a heuristic for choosing the next move, where you always try the move that results in the fewest available moves for the next move after that. It can be done in a couple of simple loops:
int row = cellno / board.length, col = cellno % board.length;
// find move with fewest moves available for the next move:
int minMovesAvailable = 8;
int minMovesDir = 0;
for (int i = 0; i < dirs.length; i++) {
int r = dirs[i][0] + row;
int c = dirs[i][1] + col;
if (isSafe(board, r, c)&&board[r][c]==-1)
{
board[r][c] = stepno;
int movesAvailable = 0;
for (int j = 0; j < dirs.length; j++) {
int r2 = dirs[j][0] + r;
int c2 = dirs[j][1] + c;
if (isSafe(board, r2, c2)&&board[r2][c2]==-1)
{
movesAvailable++;
}
}
board[r][c] = -1;
if(movesAvailable < minMovesAvailable)
{
minMovesAvailable = movesAvailable;
minMovesDir = i;
}
}
}
// now recurse this move first:
// int r = dirs[minMovesDir][0] + row;
// int c = dirs[minMovesDir][1] + col;

Sorting multidimensional array without sort method?

I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";

How to find the saddlePoint in IntMatrix [duplicate]

This question already has answers here:
How to find a saddle point of a matrix using Java? [closed]
(2 answers)
Closed 8 years ago.
This is my program in finding the Saddle Point of a Matrix (IntMatrix). Please help me make another method for IntMatrix m, for the Parameters inside the saddlePoints method?
public class SaddlePoint{
public void saddlePoints(IntMatrix m, int[] rows, int[] cols) {
int rows = m.length;
int cols = m[0].length;
boolean[][] flagArr = new boolean[rows][cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(m[i][j]==0){
flagArr[i][j]=true;
}
}
}
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(flagArr[i][j]==true){
/*for rows*/
for(int k=0; k<rows; k++){
m[k][j]=0;
}
/*for cols*/
for(int z=0; z<cols; z++){
m[i][z]=0;
}
}
}
}
}
}
this is the requirement
but i need the saddlePoint method only because I already have the other methods
IntMatrix Class:
//represents a 2-dimensional matrix of integers
Constructor Signature:
IntMatrix(int rows, int cols, int ... elements)
//elements are provided in row major order
IntMatrixUtilityClass
Static Methods:
IntMatrix sum(IntMatrix ... matrices)
//returns the sum of its arguments
IntMatrix product(IntMatrix m1, IntMatrix m2, IntMatrix ... others)
//returns the product of its arguments
boolean[] saddlePoints(IntMatrix m, int[] rows, int[] cols)
/*for each of the row and column pairs, returns true if the specified element of m is a saddle
point for the matrix; returns false otherwise*/
this is my program, I only need the saddlePoints
public class IntMatrix {
private int[][] matrix;
private int rows;
private int cols;
private int[] elements;
public IntMatrix(int r, int c, int... e) {
this.rows = r;
this.cols = c;
this.elements = e;
matrix = new int[rows][cols];
int l = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
this.matrix[i][j] = elements[l];
l++;
}
}
}
public static IntMatrix sum(IntMatrix... matrices) {
int[] result = new int[matrices[0].rows * matrices[0].cols];
for (IntMatrix matrix : matrices) {
int l = 0;
for (int i = 0; i < matrix.rows; i++) {
for (int j = 0; j < matrix.cols; j++) {
result[l] += matrix.matrix[i][j];
l++;
}
}
}
IntMatrix m3 = new IntMatrix(matrices[0].rows, matrices[0].cols, result);
return m3;
}
public static IntMatrix product(IntMatrix m1, IntMatrix m2,
IntMatrix... others) {
int[] result = new int[m1.rows * m2.cols];
int l = 0;
for (int i = 0; i < m1.rows; i++) {
for (int j = 0; j < m2.cols; j++) {
for (int k = 0; k < m1.cols; k++) {
result[l] += (m1.matrix[i][k] * m2.matrix[k][j]);
}
l++;
}
}
IntMatrix m3 = new IntMatrix(m1.rows, m2.cols, result);
for (IntMatrix other : others) {
int length = others.length;
l = 0;
int[] result2 = new int[(m3.rows * others[length - 1].cols)];
for (int i = 0; i < m3.rows; i++) {
for (int j = 0; j < other.cols; j++) {
for (int k = 0; k < m3.cols; k++) {
result2[l] += (m3.matrix[i][k] * other.matrix[k][j]);
}
l++;
}
}
m3 = new IntMatrix(m3.rows, others[length - 1].cols, result2);
}
return m3;
}
public String toString() {
return String.valueOf(rows) + " " + " " + String.valueOf(cols)
+ Arrays.toString(elements);
}
}// end of Matrix Class
First I want to say please do some research on your own before asking. From Here How to find a saddle point of a matrix using Java? you can find accepted ans but here I tell you that is not according to Wikipedia definition
Sadle Point:
A saddle point is an element of the matrix which is both the largest element in its
column and the smallest element in its row.
OR in simple words A matrix is said to have a saddle point if some entry a[x][y] is the smallest value in the x'th row and the largest value in the y'th column. A matrix may have more than one saddle point.
This Code is according to wikipedia defination
package com.mubasher.main;
import java.util.Random;
public class SaddlePoint {
private int[][] intMatrix;
private int[] colMaxima;
private int[] rowMinima;
public SaddlePoint(int col, int row){
intMatrix = new int[row][col];
colMaxima = new int[col];
rowMinima = new int[row];
fillMatrix();
}
private void fillMatrix() {
Random random = new Random();
for(int row = 0; row<intMatrix.length;row++){
for(int col = 0;col<intMatrix[0].length;col++){
intMatrix[row][col] = random.nextInt(21) - 10;
}
}
printMatrix();
}
private void printMatrix(int[][] intMatrix) {
for(int row = 0;row<intMatrix.length;row++){
for(int col = 0; col<intMatrix[0].length;col++){
System.out.print(intMatrix[row][col]+" ");
}
System.out.println("");
}
for(int i=0;i<intMatrix[0].length;i++)
System.out.print("----");
System.out.println("");
}
public void printMatrix() {
printMatrix(intMatrix);
}
public void printArray(int[] array,boolean isHorizontaly) {
for(int i = 0;i<array.length;i++){
if(isHorizontaly){
System.out.print(array[i]+" ");
} else {
System.out.println(array[i]);
}
}
if(isHorizontaly){System.out.println("");
for(int i=0;i<array.length;i++)
System.out.print("----");
} else {
System.out.println("----");
}
System.out.println("");
}
public void run(){
int maxVal = 0,minVal=0;
//minimum in each row
for(int row = 0; row<intMatrix.length;row++){
for(int col = 0;col<intMatrix[0].length;col++){
if(col == 0 ) {
rowMinima[row]=intMatrix[row][col]; // assume first val at (row,0) is minimum
} else {
if(intMatrix[row][col]<rowMinima[row]){
rowMinima[row]=intMatrix[row][col]; // assign new minimum val
}
}
}
}
//maximum in each column
for(int col = 0; col<intMatrix[0].length;col++){
for(int row = 0;row<intMatrix.length;row++){
if(row == 0 ) {
colMaxima[col]=intMatrix[row][col]; // for
} else {
if(intMatrix[row][col]>colMaxima[col]){
colMaxima[col]=intMatrix[row][col]; // assign new max val
}
}
}
}
printArray(colMaxima,true);
printArray(rowMinima,false);
int colIndx=0,rowIndx=0;
for(int i =0;i<colMaxima.length;i++){
if(i == 0 ) {
minVal= colMaxima[i];
colIndx=i;
} else {
if(colMaxima[i]<minVal){
minVal= colMaxima[i];
colIndx=i;
}
}
}
for(int i =0;i<rowMinima.length;i++){
if(i == 0 ) {
maxVal= rowMinima[i];
rowIndx = i;
} else {
if(rowMinima[i]>maxVal){
maxVal= rowMinima[i];
rowIndx = i;
}
}
}
if(minVal == maxVal){
System.out.println("We Have Saddle Point "+maxVal+" at ("+(rowIndx+1)+","+(colIndx+1)+")");
} else {
System.out.println("There is no saddle point");
}
}
public static void main(String[] args) {
SaddlePoint sp = new SaddlePoint(3, 4);
sp.run();
}
}
you can modify run method according to your needs. run method is calculating saddle point

Trouble printing chars thru a 2 dim java array

I tried to run this code as a score table where I have chars and ints as below for heading;
A B c
1
2 65 //this is where I'm stuck again!
3
In order to print the score like (65) above in a particular place (matrix) but as soon as I try to add the print statements the table falls apart. Any help would be appreciated;
public class Table3 {
static int[][] list = new int[4][4];
//private char column = 'A';
//private int row = 1;
private static int row = 1;
public Table3(){
//column = 'A';
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 4; j++)
list[i][j] = 0;
}
}
public static void table(char col, int row, int value) {
//System.out.printf("\n\n%s\n", "Table");
for (int i = 1; i < 4; i++) {
System.out.print(row + " ");
row++;
for (int j = 1; j < 4; j++)System.out.print(col + " ");
System.out.println("\n");
col++;
if (row >= 0 && row <= 4 && col >=0 && col <= 4)
System.out.print(list[col][row]=value);
System.out.println("\n");
}
}
}
Client
public class TableTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Table3 t = new Table3();
t.table('A', 5, 5);
}
}
Learn how to use System.out.printf. The docs are here.
public class Table3
{
static int numRows = 4;
static int numCols = 4;
static int[][] list = new int[numRows][numCols];
public Table3()
{
//column = 'A';
for (int i = 0; i < 4; i++)
{
//this is the row number so you don't have to print it manually
//just print the array
list[i][0] = i;
//initialize the list to 0
for (int j = 1; j < 4; j++)
{
list[i][j] = 0;
}
}
}
public static void table(char col, int row, int value)
{
list[row][col] = value;
int columnWidth = 5; //in characters
//empty space before first column header
for (int i = 0; i < columnWidth; i++)
{
System.out.print(" ");
}
//print the column headers (A through C)
for (int i = 1; i < numCols; i++)
{
System.out.printf("%-" + columnWidth" + "c", (char)(64 + i));
}
System.out.println(); //get off of the column header row
//print the rest of the table
for (int i = 1; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
if (list[i][j] == 0)
{
System.out.printf("%" + columnWidth + "s", " ");
}
else
{
System.out.printf("%-" + columnWidth + "d", list[i][j]);
}
}
System.out.println("\n");
}
}
}

Categories