How can I speed up my n*n sudoku grid generator? - java

This is my code for a Sudoku-style grid generator. It generates every possible different n*n grid where there cannot be the same number in a certain column or row (like a sudoku) and also counts how many different combinations there are. E.g. one example of a 3*3 grid could be:
[ 3, 2, 1 ]
[ 1, 3, 2 ]
[ 2, 1, 3 ]
Unfortunately, for anything past 4*4 grids, it takes too long to do this, therefore, could anybody help me edit this slightly so that it is much faster?
import java.util.Arrays;
public class GridN {
public static final int SIZE = 3;
public static int count;
public static void main(String[] args) {
int[][] grid = new int[SIZE][SIZE];
count = 0;
bruteSolve(0, 0, grid);
}
public static void bruteSolve(int num1, int num2, int[][] grid) {
for (int i = 1; i < SIZE + 1; i++) {
grid[num1][num2] = i;
if (num2 == SIZE - 1 && num1 == SIZE - 1) {
if (isValid(grid)) {
count++;
System.out.println(Arrays.deepToString(grid));
System.out.println(count);
}
} else if (num2 == SIZE - 1) {
bruteSolve(num1 + 1, 0, grid);
} else {
bruteSolve(num1, num2 + 1, grid);
}
}
}
public static boolean isValid(int[][] grid) {
int factorial = 1;
int fibonacci = 0;
int totalX1 = 1;
int totalY1 = 1;
int totalX2 = 0;
int totalY2 = 0;
for (int i = SIZE; i > 0; i--) {
factorial = factorial * i;
}
for (int i = SIZE; i > 0; i--) {
fibonacci = fibonacci + i;
}
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
totalY1 = totalY1 * grid[i][j]; // checks all columns
totalX1 = totalX1 * grid[j][i]; // checks all rows
totalX2 = totalX2 + grid[j][i];
totalY2 = totalY2 + grid[i][j];
}
if (totalX1 != factorial || totalY1 != factorial
|| totalX2 != fibonacci || totalY2 != fibonacci) {
return false;
}
totalX1 = 1;
totalY1 = 1;
totalX2 = 0;
totalY2 = 0;
}
return true;
}
}

Related

Issues with calculating the determinant of a matrix (in Java). It is alwys 0

I want to calculoate the determinant of a given NxN Matrix using the Laplace-Method. I already tried differnt approaches which always return a 0.
The class I used:
package Matrix;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Matrix
{
double[][] array;
public static void init(Matrix a,int row , int column)
{
a.array = new double [row] [column];
for (int i = 0; i < row; i++)
{
for(int k = 0; k < column; k++)
{
a.array[i][k] = 0;
}
}
}
public static int getNRows(Matrix a)
{
return a.array.length;
}
public static int getNColumns(Matrix a)
{
return a.array[0].length;
}
public static void print(Matrix a)
{
for(int i = 0; i < getNRows(a);i++ )
{
for (int k = 0; k < getNColumns(a); k++)
{
System.out.print(a.array[i][k] + "\t");
}
System.out.println();
}
}
public static double det(Matrix a)
{
double det = 0;
det = a.array[0][0] * a.array[1][1] * a.array[2][2] + a.array[1][0] * a.array[2][1] * a.array[0][2] + a.array[2][0] * a.array[0][1] * a.array[1][2] - a.array[2][0] * a.array[1][1] * a.array[0][2] - a.array[1][0] * a.array[0][1] * a.array[2][2] - a.array[0][0] * a.array[2][1] * a.array[1][2];
return det;
public static Matrix transpose(Matrix a)
{
Matrix transposed = new Matrix();
Matrix.init(transposed, getNRows(a), getNColumns(a));
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
transposed.array[j][i] = a.array[i][j];
}
}
return transposed;
}
public static Matrix subMatrix(Matrix a, int exclRow, int exclCol)
{
Matrix subMatrix = new Matrix();
Matrix.init(subMatrix, getNRows(a) - 1, getNColumns(a) - 1);
for(int i = 0; i < getNRows(a) - 1; i++)
{
for(int j = 0; j < getNColumns(a) - 1; j++)
{
if(i != exclRow && j != exclCol)
{
subMatrix.array[i][j] = a.array[i][j];
}
}
}
return subMatrix;
}
public static Matrix loadMatrix(String filename) throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
Matrix result = new Matrix();
int row = 0;
int col = 0;
String[] line = sc.nextLine().trim().split("\t");
row = Integer.parseInt(line[0]);
col = Integer.parseInt(line[1]);
init(result, row, col);
int currentRow = 0;
while(sc.hasNextLine())
{
String[] line2 =sc.nextLine().trim().split("\t");
for(int i = 0; i < col; i++)
{
result.array[currentRow][i] = Double.parseDouble(line2[i]);
}
currentRow++;
}
return result;
}
/*public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
double value = 1;
if(colOfA != rowOfA)
{
return 0;
}
if(colOfA == 1 && rowOfA == 1)
{
return a.array[0][0];
}
else
{
for(int row = 0; row < rowOfA; row++)
{
value += Math.pow(-1, row) * a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}*/
public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
if(colOfA != rowOfA)
{
return 0;
}
if(rowOfA <= 3)
{
return det(a);
}
double value = 0;
for(int row = 0; row < rowOfA; row++)
{
if(row % 2 == 0)
{
value += a.array[row][0] * detN(subMatrix(a, row, 0));
}
else
{
value -= a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}
public static Matrix adjointN(Matrix a)
{
int rowOfA = getNRows(a);
int colOfA = getNColumns(a);
Matrix ret = new Matrix();
Matrix.init(ret, rowOfA, colOfA);
for(int row = 0; row < rowOfA; row++)
{
for(int col = 0; col < colOfA; col++)
{
ret.array[row][col] = detN(subMatrix(a, row, col));
}
ret = transpose(ret);
return ret;
}
return ret;
}
public static Matrix inverseN(Matrix a)
{
Matrix inverse = new Matrix();
Matrix.init(inverse, getNRows(a), getNColumns(a));
double pre = 1/detN(a);
inverse = adjointN(a);
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
inverse.array[j][i] = inverse.array[i][j] * pre;
}
}
return inverse;
}
}
I have two versions for detN, which both yield the same result.
This isn't the entire class, because there are some functions that don't belong to this particular question
Here is an approach you could consider(the code is not fully debugged so take with a grain of salt). Finding the determinant is a recursive concept since you are always finding the determinant of a smaller matrix to get the final answer.
//Recursive base function
public static double det(int[][] matrix) {
if(matrix.length == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]));
double determinant = 0;
int mlength = matrix.length - 1;
int[][] newM = new int[mlength][mlength];
for(int i = 0; i < mlength + 1; i++) {
newM = newMatrix(matrix, i);
determinant = determinant + (Math.pow(-1, i) * matrix[0][i]) * det(newM);
}
return determinant;
}
//Format smaller matrix to use in further iteration of above det(int[][]) function
public static int[][] newMatrix(int[][] m, int column) {
int length = m.length - 1;
int[][] newMat = new int[length][length];
for(int i = 1; i < m.length; i++) {
for(int j = 0; j < column; j++)
newMat[i - 1][j] = m[i][j];
for(int k = column + 1; k < m.length; k++)
newMat[i - 1][k - 1] = m[i][k];
}
return newMat;
}
You can adapt to however your Matrix class works.
subMatrix is not really excluding the given row and column - it is just making them zero (not copying) and removing the last row and column...
Printing the matrix will help debug that.
one way: use additional indices for the destination matrix (the sub matrix). Only increment this if a value is really copied. Example: sub.array[k++][l++] = a.array[i][j] inside the if
loop over original matrix
Alternative: if one index is greater than or equal to the index that must be skipped, add 1 to the reading index:
var k = (i>=exclRow) ? i+1 : i;
var l = (j>=exclCol) ? j+1 : j;
sub.array[i][j = a.array[k][l];
code not intended to be complete, just ideas how to solve the problem

Java parallel for loop with parametr passing

i want this code in Java 1.8 to run parallel on more processors:
// Make iterations
for(int i = 0; i < numberOfIterations; i++) {
for(int m = 0; m < gridsize; m++) {
for(int n = 0; n < gridsize; n++) {
one_cell_generation(grid, grid2, m, n);
}
int n = 0;
}
}
It's part of the code from the game of life implementation. How can i make it parallel so the function one_cell_generation will run multiple times on more processors (perhaps threads?). I am new in Java. Thanks. Here is my whole code of the Game of Life implementation:
package gameoflife;
public class GameOfLife {
public static int gridsize = 5;
public static int numberOfIterations = 100;
public static String liveCell = "x";
public static String deadCell = "o";
public static void main(String[] args) {
// Probability that cell is live in random order
double p = 0.1;
Boolean[][] grid = new Boolean[gridsize][gridsize];
Boolean[][] grid2 = new Boolean[gridsize][gridsize];
// Set up grid
for(int m = 0; m < gridsize; m++) {
for(int n = 0; n < gridsize; n++) {
grid[m][n] = false;
if(Math.random() < p) {
grid[m][n] = true;
}
// Copy grid
grid2[m][n] = grid[m][n];
}
}
// Make iterations
for(int i = 0; i < numberOfIterations; i++) {
for(int m = 0; m < gridsize; m++) {
for(int n = 0; n < gridsize; n++) {
one_cell_generation(grid, grid2, m, n);
}
int n = 0;
}
}
print_grid(grid);
}
public static void print_grid(Boolean[][] grid) {
for(int m = 0; m < gridsize; m++) {
for(int n = 0; n < gridsize; n++) {
if(grid[m][n] == false) {
System.out.print(deadCell);
} else {
System.out.print(liveCell);
}
}
System.out.println();
}
}
public static void one_cell_generation(Boolean[][] oldGrid, Boolean[][] newGrid, int m, int n) {
// count live and dead neighbors
int liveNeighbours = 0;
// iterate over neighbors
// check borders
if(m > 0) {
if(oldGrid[m-1][n] == true) {
liveNeighbours += 1;
}
if (n > 0) {
if(oldGrid[m-1][n-1] == true) {
liveNeighbours += 1;
}
}
if(n < (gridsize - 1)) {
if (oldGrid[m-1][n+1] == true) {
liveNeighbours += 1;
}
}
}
if (m < (gridsize - 1)) {
if (oldGrid[m+1][n] == true) {
liveNeighbours += 1;
}
if(n > 0) {
if(oldGrid[m+1][n-1] == true) {
liveNeighbours += 1;
}
}
if(n < (gridsize - 1)) {
if(oldGrid[m+1][n+1] == true) {
liveNeighbours += 1;
}
}
}
if (n > 0) {
if (oldGrid[m][n-1] == true) {
liveNeighbours += 1;
}
}
if(n < (gridsize - 1)) {
if(oldGrid[m][n+1] == true) {
liveNeighbours += 1;
}
}
// conway's game of life rules
// apply rules to new grid
if(liveNeighbours < 2 || liveNeighbours > 3) {
newGrid[m][n] = false;
}
if(liveNeighbours == 3) {
newGrid[m][n] = true;
}
}
}
The outer loop is a time series looping over the different generations, so that can not be parallelized without affecting the final results.
The two inner loops calculate the state of the current generation based on the state of the previous generation, and can easily be parallelized.
Here's an approach using a parallel IntStream:
static int numberOfIterations = 100;
static int gridSize = 5;
public static void main(String[] args) {
Boolean[][] grid1 = new Boolean[gridSize][gridSize];
Boolean[][] grid2 = new Boolean[gridSize][gridSize];
// initialize grids here
for(int i = 0; i < numberOfIterations; i++) {
// parallel processing
IntStream.range(0, gridSize * gridSize).parallel().forEach(mn -> {
int m = mn / gridSize;
int n = mn % gridSize;
oneCellGeneration(grid1, grid2, m, n);
});
// copy new grid to old grid here
}
}
public static void oneCellGeneration(Boolean[][] grid1, Boolean[][] grid2,
int m, int n) {
// your cell generation logic here
}
Note 1: I renamed some methods and variables to be in line with Java naming conventions.
Note 2: You forgot to copy the new grid to the old grid after finishing (or before starting) a generation in your original code.
You can do like this. I can't add coment to answer so I create my own answer.
static int gridSize = 5;
public static void main(String[] args) {
Boolean[][] grid1 = new Boolean[gridSize][gridSize];
Boolean[][] grid2 = new Boolean[gridSize][gridSize];
// initialize grids here
IntStream
.range(0, gridSize * gridSize)
.limit(numberOfIterations)
.parallel().forEach(mn -> {
int m = mn / gridSize;
int n = mn % gridSize;
oneCellGeneration(grid1, grid2, m, n);
});
}
public static void oneCellGeneration(Boolean[][] grid1, Boolean[][] grid2,
int m, int n) {
// your cell generation logic here
}
```

Manipulating adjacent matrix

I have a network graph with nodes and edges and i managed to construct an adjacent matrix of my graph.
sample adjacent matrix with edge weight
Nodes -> {A, B, C, D}
Edges -> {[A->B = 2] , [A->D = 5] , [C->A = 1] , [C->B = 4] , [D->B = ] , [D->C = 2]}
my adjacent network is like this
0 2 0 2
0 0 0 0
4 4 0 0
0 6 6 0
so i want to change the adjacent matrix to be like this with labels of the nodes and average of each column by considering non zero cells
A B C D
A 0 2 0 2
B 0 0 0 0
C 4 4 0 0
D 0 6 6 0
X 4 4 6 2 <- Mean of non zero column
here is my the code i used to create adjacent matrix,
Node.java
public class Node
{
public char label;
public Node(char l)
{
this.label=l;
}
}
Graph.java
public class Graph
{
public ArrayList nodes=new ArrayList();
public double[][] adjacentMatrix;
int size;
public void addNode(Node n)
{
nodes.add(n);
}
public void addEdge(Node start,Node end,int weight)
{
if(adjacentMatrix==null)
{
size=nodes.size();
adjacentMatrix=new double[size][size];
}
int startIndex=nodes.indexOf(start);
int endIndex=nodes.indexOf(end);
adjacentMatrix[startIndex][endIndex]=weight;
}
public static void printAdjacentMatrix(double matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
}
Main.java
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Defining nodes
Node nA=new Node('A');
Node nB=new Node('B');
Node nC=new Node('C');
Node nD=new Node('D');
//Creating adjacent matrix
Graph g=new Graph();
g.addNode(nA);
g.addNode(nB);
g.addNode(nC);
g.addNode(nD);
g.addEdge(nA, nB, 2);
g.addEdge(nA, nD, 2);
g.addEdge(nC, nA, 4);
g.addEdge(nC, nB, 4);
g.addEdge(nD, nB, 6);
g.addEdge(nD, nC, 6);
g.printAdjacentMatrix(g.adjacentMatrix);
}
}
so i ask for help to display the second matrix with average and labels...Thank you in advance
Not a very nice solution but that will do.
public class Graph {
public ArrayList nodes = new ArrayList();
public int[][] adjacentMatrix;
int size;
public void addNode(Node n) {
nodes.add(n);
}
public void addEdge(Node start, Node end, int weight) {
if (adjacentMatrix == null) {
size = nodes.size();
adjacentMatrix = new int[size][size];
}
int startIndex = nodes.indexOf(start);
int endIndex = nodes.indexOf(end);
adjacentMatrix[startIndex][endIndex] = weight;
}
public static void printAdjacentMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
public static void convertMatrix(int matrix[][]) {
int row = matrix.length + 2;
int column = matrix[0].length + 1;
String newMatrix[][] = new String[row][column];
initializeFirstRow(newMatrix);
initializeFirstColumn(newMatrix);
copyMatrix(matrix, newMatrix);
addMean(matrix, newMatrix);
printAdjacentMatrix(newMatrix);
}
private static void initializeFirstColumn(String[][] newMatrix) {
newMatrix[1][0] = "A";
newMatrix[2][0] = "B";
newMatrix[3][0] = "C";
newMatrix[4][0] = "D";
newMatrix[5][0] = "X";
}
private static void printAdjacentMatrix(String[][] newMatrix) {
for (int row = 0; row < newMatrix.length; row++) {
for (int column = 0; column < newMatrix[row].length; column++) {
System.out.print(newMatrix[row][column] + " ");
}
System.out.println();
}
}
private static void addMean(int[][] matrix, String[][] newMatrix) {
int mean = 0;
int sum = 0;
int divident = 0;
for (int j = 0; j < matrix[0].length; j++) {
sum = 0;
divident = 0;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][j] != 0) {
sum += matrix[i][j];
divident++;
}
}
if (sum != 0) {
mean = sum / divident;
}
newMatrix[5][j + 1] = "" + mean;
}
}
private static void copyMatrix(int[][] matrix, String[][] newMatrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
newMatrix[i + 1][j + 1] = "" + matrix[i][j];
}
}
}
private static void initializeFirstRow(String[][] newMatrix) {
newMatrix[0][0] = " ";
newMatrix[0][1] = "A";
newMatrix[0][2] = "B";
newMatrix[0][3] = "C";
newMatrix[0][4] = "D";
}
}
Also add following line in Main.java
g.convertMatrix(g.adjacentMatrix);

Calculating matrix determinant

I am trying to calculate the determinant of a matrix (of any size), for self coding / interview practice. My first attempt is using recursion and that leads me to the following implementation:
import java.util.Scanner.*;
public class Determinant {
double A[][];
double m[][];
int N;
int start;
int last;
public Determinant (double A[][], int N, int start, int last){
this.A = A;
this.N = N;
this.start = start;
this.last = last;
}
public double[][] generateSubArray (double A[][], int N, int j1){
m = new double[N-1][];
for (int k=0; k<(N-1); k++)
m[k] = new double[N-1];
for (int i=1; i<N; i++){
int j2=0;
for (int j=0; j<N; j++){
if(j == j1)
continue;
m[i-1][j2] = A[i][j];
j2++;
}
}
return m;
}
/*
* Calculate determinant recursively
*/
public double determinant(double A[][], int N){
double res;
// Trivial 1x1 matrix
if (N == 1) res = A[0][0];
// Trivial 2x2 matrix
else if (N == 2) res = A[0][0]*A[1][1] - A[1][0]*A[0][1];
// NxN matrix
else{
res=0;
for (int j1=0; j1<N; j1++){
m = generateSubArray (A, N, j1);
res += Math.pow(-1.0, 1.0+j1+1.0) * A[0][j1] * determinant(m, N-1);
}
}
return res;
}
}
So far it is all good and it gives me a correct result. Now I would like to optimise my code by making use of multiple threads to calculate this determinant value.
I tried to parallelize it using the Java Fork/Join model. This is my approach:
#Override
protected Double compute() {
if (N < THRESHOLD) {
result = computeDeterminant(A, N);
return result;
}
for (int j1 = 0; j1 < N; j1++){
m = generateSubArray (A, N, j1);
ParallelDeterminants d = new ParallelDeterminants (m, N-1);
d.fork();
result += Math.pow(-1.0, 1.0+j1+1.0) * A[0][j1] * d.join();
}
return result;
}
public double computeDeterminant(double A[][], int N){
double res;
// Trivial 1x1 matrix
if (N == 1) res = A[0][0];
// Trivial 2x2 matrix
else if (N == 2) res = A[0][0]*A[1][1] - A[1][0]*A[0][1];
// NxN matrix
else{
res=0;
for (int j1=0; j1<N; j1++){
m = generateSubArray (A, N, j1);
res += Math.pow(-1.0, 1.0+j1+1.0) * A[0][j1] * computeDeterminant(m, N-1);
}
}
return res;
}
/*
* Main function
*/
public static void main(String args[]){
double res;
ForkJoinPool pool = new ForkJoinPool();
ParallelDeterminants d = new ParallelDeterminants();
d.inputData();
long starttime=System.nanoTime();
res = pool.invoke (d);
long EndTime=System.nanoTime();
System.out.println("Seq Run = "+ (EndTime-starttime)/100000);
System.out.println("the determinant valaue is " + res);
}
However after comparing the performance, I found that the performance of the Fork/Join approach is very bad, and the higher the matrix dimension, the slower it becomes (as compared to the first approach). Where is the overhead? Can anyone shed a light on how to improve this?
Using This class you can calculate the determinant of a matrix with any dimension
This class uses many different methods to make the matrix triangular and then, calculates the determinant of it. It can be used for matrix of high dimension like 500 x 500 or even more. the bright side of the this class is that you can get the result in BigDecimal so there is no infinity and you'll have always the accurate answer. By the way, using many various methods and avoiding recursion resulted in much faster way with higher performance to the answer. hope it would be helpful.
import java.math.BigDecimal;
public class DeterminantCalc {
private double[][] matrix;
private int sign = 1;
DeterminantCalc(double[][] matrix) {
this.matrix = matrix;
}
public int getSign() {
return sign;
}
public BigDecimal determinant() {
BigDecimal deter;
if (isUpperTriangular() || isLowerTriangular())
deter = multiplyDiameter().multiply(BigDecimal.valueOf(sign));
else {
makeTriangular();
deter = multiplyDiameter().multiply(BigDecimal.valueOf(sign));
}
return deter;
}
/* receives a matrix and makes it triangular using allowed operations
on columns and rows
*/
public void makeTriangular() {
for (int j = 0; j < matrix.length; j++) {
sortCol(j);
for (int i = matrix.length - 1; i > j; i--) {
if (matrix[i][j] == 0)
continue;
double x = matrix[i][j];
double y = matrix[i - 1][j];
multiplyRow(i, (-y / x));
addRow(i, i - 1);
multiplyRow(i, (-x / y));
}
}
}
public boolean isUpperTriangular() {
if (matrix.length < 2)
return false;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < i; j++) {
if (matrix[i][j] != 0)
return false;
}
}
return true;
}
public boolean isLowerTriangular() {
if (matrix.length < 2)
return false;
for (int j = 0; j < matrix.length; j++) {
for (int i = 0; j > i; i++) {
if (matrix[i][j] != 0)
return false;
}
}
return true;
}
public BigDecimal multiplyDiameter() {
BigDecimal result = BigDecimal.ONE;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (i == j)
result = result.multiply(BigDecimal.valueOf(matrix[i][j]));
}
}
return result;
}
// when matrix[i][j] = 0 it makes it's value non-zero
public void makeNonZero(int rowPos, int colPos) {
int len = matrix.length;
outer:
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (matrix[i][j] != 0) {
if (i == rowPos) { // found "!= 0" in it's own row, so cols must be added
addCol(colPos, j);
break outer;
}
if (j == colPos) { // found "!= 0" in it's own col, so rows must be added
addRow(rowPos, i);
break outer;
}
}
}
}
}
//add row1 to row2 and store in row1
public void addRow(int row1, int row2) {
for (int j = 0; j < matrix.length; j++)
matrix[row1][j] += matrix[row2][j];
}
//add col1 to col2 and store in col1
public void addCol(int col1, int col2) {
for (int i = 0; i < matrix.length; i++)
matrix[i][col1] += matrix[i][col2];
}
//multiply the whole row by num
public void multiplyRow(int row, double num) {
if (num < 0)
sign *= -1;
for (int j = 0; j < matrix.length; j++) {
matrix[row][j] *= num;
}
}
//multiply the whole column by num
public void multiplyCol(int col, double num) {
if (num < 0)
sign *= -1;
for (int i = 0; i < matrix.length; i++)
matrix[i][col] *= num;
}
// sort the cols from the biggest to the lowest value
public void sortCol(int col) {
for (int i = matrix.length - 1; i >= col; i--) {
for (int k = matrix.length - 1; k >= col; k--) {
double tmp1 = matrix[i][col];
double tmp2 = matrix[k][col];
if (Math.abs(tmp1) < Math.abs(tmp2))
replaceRow(i, k);
}
}
}
//replace row1 with row2
public void replaceRow(int row1, int row2) {
if (row1 != row2)
sign *= -1;
double[] tempRow = new double[matrix.length];
for (int j = 0; j < matrix.length; j++) {
tempRow[j] = matrix[row1][j];
matrix[row1][j] = matrix[row2][j];
matrix[row2][j] = tempRow[j];
}
}
//replace col1 with col2
public void replaceCol(int col1, int col2) {
if (col1 != col2)
sign *= -1;
System.out.printf("replace col%d with col%d, sign = %d%n", col1, col2, sign);
double[][] tempCol = new double[matrix.length][1];
for (int i = 0; i < matrix.length; i++) {
tempCol[i][0] = matrix[i][col1];
matrix[i][col1] = matrix[i][col2];
matrix[i][col2] = tempCol[i][0];
}
} }
This Class Receives a matrix of n x n from the user then calculates it's determinant. It also shows the solution and the final triangular matrix.
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Scanner;
public class DeterminantTest {
public static void main(String[] args) {
String determinant;
//generating random numbers
/*int len = 300;
SecureRandom random = new SecureRandom();
double[][] matrix = new double[len][len];
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
matrix[i][j] = random.nextInt(500);
System.out.printf("%15.2f", matrix[i][j]);
}
}
System.out.println();*/
/*double[][] matrix = {
{1, 5, 2, -2, 3, 2, 5, 1, 0, 5},
{4, 6, 0, -2, -2, 0, 1, 1, -2, 1},
{0, 5, 1, 0, 1, -5, -9, 0, 4, 1},
{2, 3, 5, -1, 2, 2, 0, 4, 5, -1},
{1, 0, 3, -1, 5, 1, 0, 2, 0, 2},
{1, 1, 0, -2, 5, 1, 2, 1, 1, 6},
{1, 0, 1, -1, 1, 1, 0, 1, 1, 1},
{1, 5, 5, 0, 3, 5, 5, 0, 0, 6},
{1, -5, 2, -2, 3, 2, 5, 1, 1, 5},
{1, 5, -2, -2, 3, 1, 5, 0, 0, 1}
};
*/
double[][] matrix = menu();
DeterminantCalc deter = new DeterminantCalc(matrix);
BigDecimal det = deter.determinant();
determinant = NumberFormat.getInstance().format(det);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
System.out.printf("%15.2f", matrix[i][j]);
}
System.out.println();
}
System.out.println();
System.out.printf("%s%s%n", "Determinant: ", determinant);
System.out.printf("%s%d", "sign: ", deter.getSign());
}
public static double[][] menu() {
Scanner scanner = new Scanner(System.in);
System.out.print("Matrix Dimension: ");
int dim = scanner.nextInt();
double[][] inputMatrix = new double[dim][dim];
System.out.println("Set the Matrix: ");
for (int i = 0; i < dim; i++) {
System.out.printf("%5s%d%n", "row", i + 1);
for (int j = 0; j < dim; j++) {
System.out.printf("M[%d][%d] = ", i + 1, j + 1);
inputMatrix[i][j] = scanner.nextDouble();
}
System.out.println();
}
scanner.close();
return inputMatrix;
}}
The main reason the ForkJoin code is slower is that it's actually serialized with some thread overhead thrown in. To benefit from fork/join, you need to 1) fork all instances first, then 2) wait for the results. Split your loop in "compute" into two loops: one to fork (storing instances of ParallelDeterminants in, say, an array) and another to collect the results.
Also, I suggest to only fork at the outermost level and not in any of the inner ones. You don't want to be creating O(N^2) threads.
There is a new method of calculating the determinant of the matrix you can read more from here
and I've implemented a simple version of this with no fancy optimization techniques or library in plain simple java and I've tested against methods described previously and it was faster on average by a factor of 10
public class Test {
public static double[][] reduce(int row , int column , double[][] mat){
int n=mat.length;
double[][] res = new double[n- 1][n- 1];
int r=0,c=0;
for (int i = 0; i < n; i++) {
c=0;
if(i==row)
continue;
for (int j = 0; j < n; j++) {
if(j==column)
continue;
res[r][c] = mat[i][j];
c++;
}
r++;
}
return res;
}
public static double det(double mat[][]){
int n = mat.length;
if(n==1)
return mat[0][0];
if(n==2)
return mat[0][0]*mat[1][1] - (mat[0][1]*mat[1][0]);
//TODO : do reduce more efficiently
double[][] m11 = reduce(0,0,mat);
double[][] m1n = reduce(0,n-1,mat);
double[][] mn1 = reduce(n-1 , 0 , mat);
double[][] mnn = reduce(n-1,n-1,mat);
double[][] m11nn = reduce(0,0,reduce(n-1,n-1,mat));
return (det(m11)*det(mnn) - det(m1n)*det(mn1))/det(m11nn);
}
public static double[][] randomMatrix(int n , int range){
double[][] mat = new double[n][n];
for (int i=0; i<mat.length; i++) {
for (int j=0; j<mat[i].length; j++) {
mat[i][j] = (Math.random()*range);
}
}
return mat;
}
public static void main(String[] args) {
double[][] mat = randomMatrix(10,100);
System.out.println(det(mat));
}
}
there is a little fault in the case of the determinant of m11nn if happen to be zero it will blow up and you should check for that. I've tested on 100 random samples it rarely happens but I think it worth mentioning and also using a better indexing scheme can also improve the efficiency
This is a part of my Matrix class which uses a double[][] member variable called data to store the matrix data.
The _determinant_recursivetask_impl() function uses a RecursiveTask<Double> object with the ForkJoinPool to try to use multiple threads for calculation.
This method performs very slow compared to matrix operations to get an upper/lower triangular matrix. Try to compute the determinant of a 13x13 matrix for example.
public class Matrix
{
// Dimensions
private final int I,J;
private final double[][] data;
private Double determinant = null;
static class MatrixEntry
{
public final int I,J;
public final double value;
private MatrixEntry(int i, int j, double value) {
I = i;
J = j;
this.value = value;
}
}
/**
* Calculates determinant of this Matrix recursively and caches it for future use.
* #return determinant
*/
public double determinant()
{
if(I!=J)
throw new IllegalStateException(String.format("Can't calculate determinant of (%d,%d) matrix, not a square matrix.", I,J));
if(determinant==null)
determinant = _determinant_recursivetask_impl(this);
return determinant;
}
private static double _determinant_recursivetask_impl(Matrix m)
{
class determinant_recurse extends RecursiveTask<Double>
{
private final Matrix m;
determinant_recurse(Matrix m) {
this.m = m;
}
#Override
protected Double compute() {
// Base cases
if(m.I==1 && m.J==1)
return m.data[0][0];
else if(m.I==2 && m.J==2)
return m.data[0][0]*m.data[1][1] - m.data[0][1]*m.data[1][0];
else
{
determinant_recurse[] tasks = new determinant_recurse[m.I];
for (int i = 0; i <m.I ; i++) {
tasks[i] = new determinant_recurse(m.getSubmatrix(0, i));
}
for (int i = 1; i <m.I ; i++) {
tasks[i].fork();
}
double ret = m.data[0][0]*tasks[0].compute();
for (int i = 1; i < m.I; i++) {
if(i%2==0)
ret += m.data[0][i]*tasks[i].join();
else
ret -= m.data[0][i]*tasks[i].join();
}
return ret;
}
}
}
return ForkJoinPool.commonPool().invoke(new determinant_recurse(m));
}
private static void _map_impl(Matrix ret, Function<Matrix.MatrixEntry, Double> operator)
{
for (int i = 0; i <ret.I ; i++) {
for (int j = 0; j <ret.J ; j++) {
ret.data[i][j] = operator.apply(new Matrix.MatrixEntry(i,j,ret.data[i][j]));
}
}
}
/**
* Returns a new Matrix that is sub-matrix without the given row and column.
* #param removeI row to remove
* #param removeJ col. to remove
* #return new Matrix.
*/
public Matrix getSubmatrix(int removeI, int removeJ)
{
if(removeI<0 || removeJ<0 || removeI>=this.I || removeJ>=this.J)
throw new IllegalArgumentException(String.format("Invalid element position (%d,%d) for matrix(%d,%d).", removeI,removeJ,this.I,this.J));
Matrix m = new Matrix(this.I-1, this.J-1);
_map_impl(m, (e)->{
int i = e.I, j = e.J;
if(e.I >= removeI) ++i;
if(e.J >= removeJ) ++j;
return this.data[i][j];
});
return m;
}
// Constructors
public Matrix(int i, int j) {
if(i<1 || j<1)
throw new IllegalArgumentException(String.format("Invalid array dimensions: (%d,%d)", i, j));
I = i;
J = j;
data = new double[I][J];
}
}
int det(int[][] mat) {
if (mat.length == 1)
return mat[0][0];
if (mat.length == 2)
return mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1];
int sum = 0, sign = 1;
int newN = mat.length - 1;
int[][] temp = new int[newN][newN];
for (int t = 0; t < newN; t++) {
int q = 0;
for (int i = 0; i < newN; i++) {
for (int j = 0; j < newN; j++) {
temp[i][j] = mat[1 + i][q + j];
}
if (q == i)
q = 1;
}
sum += sign * mat[0][t] * det(temp);
sign *= -1;
}
return sum;
}

Find the largest span between the same number in an array

Merry Christmas and hope you are in great Spirits,I have a Question in Java-Arrays as shown below.Im stuck up with this struggling to get it rite.
Consider the leftmost and righmost appearances of some value in an array. We'll say that the "span" is the number of elements between the two inclusive. A single value has a span of 1. Write a **Java Function** that returns the largest span found in the given array.
**Example:
maxSpan({1, 2, 1, 1, 3}) → 4,answer is 4 coz MaxSpan between 1 to 1 is 4
maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6,answer is 6 coz MaxSpan between 4 to 4 is 6
maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6,answer is 6 coz Maxspan between 4 to 4 is 6 which is greater than MaxSpan between 1 and 1 which is 4,Hence 6>4 answer is 6.
I have the code which is not working,it includes all the Spans for a given element,im unable to find the MaxSpan for a given element.
Please help me out.
Results of the above Program are as shown below
Expected This Run
maxSpan({1, 2, 1, 1, 3}) → 4 5 X
maxSpan({1, 4, 2, 1, 4, 1, 4}) → 6 8 X
maxSpan({1, 4, 2, 1, 4, 4, 4}) → 6 9 X
maxSpan({3, 3, 3}) → 3 5 X
maxSpan({3, 9, 3}) → 3 3 OK
maxSpan({3, 9, 9}) → 2 3 X
maxSpan({3, 9}) → 1 1 OK
maxSpan({3, 3}) → 2 3 X
maxSpan({}) → 0 1 X
maxSpan({1}) → 1 1 OK
::Code::
public int maxSpan(int[] nums) {
int count=1;//keep an intial count of maxspan=1
int maxspan=0;//initialize maxspan=0
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i] == nums[j]){
//check to see if "i" index contents == "j" index contents
count++; //increment count
maxspan=count; //make maxspan as your final count
int number = nums[i]; //number=actual number for maxspan
}
}
}
return maxspan+1; //return maxspan
}
Since a solution has been given, here is a more efficient solution which uses one pass.
public static void main(String... args) {
int maxspan = maxspan(3, 3, 3, 2, 1, 4, 3, 5, 3, 1, 1, 1, 1, 1);
System.out.println(maxspan);
}
private static int maxspan(int... ints) {
Map<Integer, Integer> first = new LinkedHashMap<Integer, Integer>(); // use TIntIntHashMap for efficiency.
int maxspan = 0; // max span so far.
for (int i = 0; i < ints.length; i++) {
int num = ints[i];
if (first.containsKey(num)) { // have we seen this number before?
int span = i - first.get(num) + 1; // num has been found so what is the span
if (span > maxspan) maxspan = span; // if the span is greater, update the maximum.
} else {
first.put(num, i); // first occurrence of number num at location i.
}
}
return maxspan;
}
I see the following problems with your attempt:
Your count is completely wrong. You can instead calculate count from i and j: j - i + 1
You're overriding maxcount as soon as you get any span, so you're going to end up with the last span, not the maximum span. Fix it by going maxspan = Math.max(maxspan, count);.
You can remove the line int number = nums[i]; as you never use number.
Remove the +1 in the returnmaxspan+1;` if you follow my tips above.
Initial maxspan should be 1 if there are any values in the array, but 0 if the array is empty.
That should help you get it working. Note that you can do this in a single pass of the array, but that's probably stretching it too far for you. Concentrate on getting your code to work before considering efficiency.
Here is the solution of this problem:
public int maxSpan(int[] nums) {
int maxSpan=0;
int tempSpan=0;
if(nums.length==0){
return 0;
}
for(int i=0;i<nums.length;i++){
for(int j=nums.length-1;j>i;j--){
if(nums[i]==nums[j]){
tempSpan=j-i;
break;
}
}
if(tempSpan>maxSpan){
maxSpan=tempSpan;
}
}
return maxSpan+1;
}
I did it with a List. Easier way to do it.
The only problem is if the Array is too big, maybe it's gonna take a while..
import java.util.ArrayList;
import java.util.List;
public class StackOverflow {
public static void main(String[] args) {
List<Integer> listNumbers = new ArrayList<Integer>();
listNumbers.add(3);
listNumbers.add(3);
listNumbers.add(3);
listNumbers.add(2);
listNumbers.add(1);
listNumbers.add(4);
listNumbers.add(3);
listNumbers.add(5);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(1);
listNumbers.add(3);
int result = 0;
Integer key = null;
for(Integer i : listNumbers){
int resultDistance = returnDistance(listNumbers, i);
if (resultDistance > result){
result = resultDistance;
key = i;
}
}
System.out.println("MaxSpan of key " + key + " is: " + result);
}
private static int returnDistance(List<Integer> listNumbers, Integer term){
Integer startPosition = null;
Integer endPosition = null;
boolean bolStartPosition = false;
boolean bolResult = false;
int count = 1;
int result = 0;
for (Integer i : listNumbers){
if (i == term && !bolStartPosition){
startPosition = count;
bolStartPosition = true;
continue;
}
if (i == term && bolStartPosition){
endPosition = count;
}
count++;
}
if (endPosition != null){
// because it's inclusive from both sides
result = endPosition - startPosition + 2;
bolResult = true;
}
return (bolResult?result:-1);
}
}
public int maxSpan(int[] nums) {
int b = 0;
if (nums.length > 0) {
for (int i = 0; i < nums.length; i++) {
int a = nums[0];
if (nums[i] != a) {
b = nums.length - 1;
} else {
b = nums.length;
}
}
} else {
b = 0;
}
return b;
}
One brute force solution may like this, take one item from the array, and find the first occurance of item from the left most, and calculate the span, and then compare with the previous result.
public int maxSpan(int[] nums) {
int result = 0;
for(int i = 0; i < nums.length; i++) {
int item = nums[i];
int span = 0;
for(int j = 0; j<= i; j++) {//find first occurance of item from the left
if(nums[j]==item) {
span = i -j+1;
break;
}
}
if(span>result) {
result = span;
}
}
return result;
}
Here is the solution -
public int maxSpan(int[] nums) {
int span = 0;
for (int i = 0; i < nums.length; i++) {
for(int j = i; j < nums.length; j++) {
if(nums[i] == nums[j]) {
if(span < (j - i + 1)) {
span = j -i + 1;
}
}
}
}
return span;
}
public int maxSpan(int[] nums) {
int span = 0;
//Given the values at position i 0..length-1
//find the rightmost position of that value nums[i]
for (int i = 0; i < nums.length; i++) {
// find the rightmost of nums[i]
int j =nums.length -1;
while(nums[i]!=nums[j])
j--;
// j is at the rightmost posititon of nums[i]
span = Math.max(span,j-i+1);
}
return span;
}
public int maxSpan(int[] nums) {
//convert the numnber to a string
String numbers = "";
if (nums.length == 0)
return 0;
for(int ndx = 0; ndx < nums.length;ndx++){
numbers += nums[ndx];
}
//check beginning and end of string
int first = numbers.indexOf(numbers.charAt(0));
int last = numbers.lastIndexOf(numbers.charAt(0));
int max = last - first + 1;
int efirst = numbers.indexOf(numbers.charAt(numbers.length()-1));
int elast = numbers.lastIndexOf(numbers.charAt(numbers.length()-1));
int emax = elast - efirst + 1;
//return the max span.
return (max > emax)?max:emax;
}
public int maxSpan(int[] nums) {
int current = 0;
int currentcompare = 0;
int counter = 0;
int internalcounter = 0;
if(nums.length == 0)
return 0;
for(int i = 0; i < nums.length; i++) {
internalcounter = 0;
current = nums[i];
for(int x = i; x < nums.length; x++) {
currentcompare = nums[x];
if(current == currentcompare) {
internalcounter = x - i;
}
if(internalcounter > counter) {
counter = internalcounter;
}
}
}
return counter + 1;
}
public int maxSpan(int[] nums) {
if(nums.length<1){
return 0;
}
int compare=1;
for (int i=0; i<nums.length; i++){
for (int l=1; l<nums.length; l++){
if((nums[l]==nums[i])&&(Math.abs(l)-Math.abs(i))>=compare){
compare = Math.abs(l)-Math.abs(i)+1;
}
}
}
return compare;
}
public static int MaxSpan(int[] input1, int key)
{
int Span = 0;
int length = input1.length;
int i,j,k = 0;
int start = 0, end = 0 ;
k = key;
for (int l = 0; l < length; l++) {
if(input1[l] == k) { start = l;
System.out.println("\nStart = " + start);
break;
}
}
if(start == 0) { Span = 0; System.out.println("Key not found"); return Span;}
for (j = length-1; j> start; j--) {
if(input1[j] == k) { end = j;
System.out.println("\nEnd = " + end);
break;
}
}
Span = end - start;
System.out.println("\nStart = " + start + "End = " + end + "Span = " + Span);
return Span;
}
public int maxSpan(int[] nums) {
int length = nums.length;
if(length <= 0)
return 0;
int left = nums[0];
int rigth = nums[length - 1];
int value = 1;
//If these values are the same, then the max span is length
if(left == rigth)
return length;
// the last match is the largest span for any value
for(int x = 1; x < length - 1; x++)
{
if(nums[x] == left || nums[x] == rigth)
value = x + 1;
}
return value;
}
public int maxSpan(int[] nums) {
int count, largest=0;
for (int x=0; x< nums.length; x++)
{
for (int y=0; y< nums.length; y++)
{
if (nums[x]==nums[y])
{
count= y-x+1;
if (count > largest)
{
largest= count;
}
}
}
}
return largest;
}
import java.io.*;
public class maxspan {
public static void main(String args[])throws java.io.IOException{
int A[],span=0,pos=0;
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter the number of elements");
A=new int[Integer.parseInt(in.readLine())];
int i,j;
for(i=0;i<A.length;i++)
{
A[i]=Integer.parseInt(in.readLine());
}
for(i=0;i<A.length;i++)
{
for(j=A.length-1;j>=0;j--)
if(A[i]==A[j]&&(j-i)>span){span=j-i;pos=i;}
}
System.out.println("maximum span => "+(span+1)+" that is of "+A[pos]);
}
}
public static int maxSpan(int[] nums) {
int left = 0;
int right = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[0] == nums[nums.length - 1 - i]) {
left = nums.length - i;
break;
} else if (nums[nums.length - 1] == nums[i]) {
right = nums.length - i;
break;
}
}
return Math.max(left, right);
}
The above solutions are great, if your goal is to avoid using Arrays.asList and indexOf and LastIndexOf, the code below does the job as lazy as possible, while still being clear and concise.
public int maxSpan(int[] nums) {
if(nums.length < 2){ //weed out length 0 and 1 cases
return nums.length;
}
int maxSpan = 1; //start out as 1
for(int a = 0; a < nums.length; a++){
for(int b = nums.length - 1; b > a; b--){
if(nums[a] == nums[b]){
maxSpan = Math.max(maxSpan, (b + 1 - a));
//A little tricky getting those indices together.
break; //there's no reason to continue,
//at least for this single loop execution inside another loop
}
}
}
return maxSpan; //the maxSpan is here!
}
The Math.max method returns the larger of 2 values, one of them if they are equal.
This is how I did it:
public int maxSpan(int[] nums) {
for (int span=nums.length; span>0; span--) {
for (int i=0; i<nums.length-span+1; i++) {
if (nums[i] == nums[i+span-1]) return span;
}
}
return 0;
}
I am not sure, if I have to use 2 for-loops... or any loop at all?
If not, this version functions without any loop.
At first you check, if the length of the array is > 0. If not, you simply return the length of the array, which will correspond to the correct answer.
If it is longer than 0, you check if the first and last position in the array have the same value.
If yes, you return the length of the array as the maxSpan.
If not, you substract a 1, since the value appears twice in the array.
Done.
public int maxSpan(int[] nums) {
if(nums.length > 0){
if(nums[0] == nums[nums.length - 1]){
return nums.length;
}
else{
return nums.length - 1;
}
}
return nums.length;
}
public int maxSpan(int[] nums) {
Stack stack = new Stack();
int count = 1;
int value = 0;
int temp = 0;
if(nums.length < 1) {
return value;
}
for(int i = 0; i < nums.length; i++) {
for(int j = nums.length - 1; j >= i; j--) {
if(nums[i] == nums[j]) {
count = (j - i) + 1;
stack.push(count);
count = 1;
break;
}
}
}
if(stack.peek() != null) {
while(stack.size() != 0) {
temp = (Integer) stack.pop();
if(value <= temp) {
value = temp;
} else {
value = value;
}
}
}
return value;
}
public int maxSpan(int[] nums) {
int totalspan=0;
int span=0;
for(int i=0;i<nums.length;i++)
{
for (int j=nums.length-1;j>i-1;j--)
{
if(nums[i]==nums[j])
{
span=j-i+1;
if (span>totalspan)
totalspan=span;
break;
}
}
}
return totalspan;
}
public int maxSpan(int[] nums) {
int max_span=0, j;
for (int i=0; i<nums.length; i++){
j=nums.length-1;
while(nums[i]!=nums[j]) j--;
if (j-i+1>max_span) max_span=j-i+1;
}
return max_span;
}
Linear solution with a Map storing the first occurrence, and calculating the distance from it for the next occurrences:
public int maxSpan(int[] nums) {
int span = 0;
Map<Integer, Integer> first = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (!first.containsKey(nums[i]))
first.put(nums[i], i);
span = Math.max(span, (i - first.get(nums[i])) + 1);
}
return span;
}

Categories

Resources