All the possible path to reach bottom of a m*n matrix - java

public static int printStepsToReachBottom(int rows, int columns, String[] array) {
if (rows == 1) {
array[0] = "";
for (int i = 0; i < columns - 1; i++) {
array[0] += "H";
}
return 1;
}
if (columns == 1) {
array[0] = "";
for (int i = 0; i < rows - 1; i++) {
array[0] += "V";
}
return 1;
}
String[] temporary = new String[1000];
int k = 0;
int firstTypeMove = printStepsToReachBottom(rows - 1, columns, array);
for (int i = 0; i < firstTypeMove; i++) {
temporary[k] = array[i] + "V";
k++;
}
int secondTypeMove = printStepsToReachBottom(rows, columns - 1, array);
for (int i = 0; i < secondTypeMove; i++) {
temporary[k] = array[i] + "H";
k++;
}
for (int i = 0; i < secondTypeMove + firstTypeMove; i++) {
array[i] = temporary[i];
}
return secondTypeMove + firstTypeMove;
}
public static void main(String[] args) {
String[] array = new String[1000];
int outputSize = printStepsToReachBottom(2, 2, array);
for (int i = 0; i < outputSize; i++) {
System.out.println(array[i]);
}
}
I can't figure out how this code snippet is working. I didn't understand the logic. It prints All the possible paths to reach the bottom of an m*n matrix
It prints "HV" and "VH" for the 2x2 matrix. Help me.

You can breakdown the code into three parts;
if (rows == 1) {
array[0] = "";
for (int i = 0; i < columns - 1; i++) {
array[0] += "H";
}
return 1;
}
if (columns == 1) {
array[0] = "";
for (int i = 0; i < rows - 1; i++) {
array[0] += "V";
}
return 1;
}
This part is the end case of the recursion. It says that there is no more rows or columns to go and return an array with size 1 either containing H(or H's) or V(or V's)
String[] temporary = new String[1000];
int k = 0;
int firstTypeMove = printStepsToReachBottom(rows - 1, columns, array);
for (int i = 0; i < firstTypeMove; i++) {
temporary[k] = array[i] + "V";
k++;
}
int secondTypeMove = printStepsToReachBottom(rows, columns - 1, array);
for (int i = 0; i < secondTypeMove; i++) {
temporary[k] = array[i] + "H";
k++;
}
The second part executes the recursion through both H and V directions for any given step which adds two more recursive calls to the stack (Although, in execution it performs a depth-first search rather than a breadth-first one, the idea is easier to grasp that way)
int secondTypeMove = printStepsToReachBottom(rows, columns - 1, array);
for (int i = 0; i < secondTypeMove; i++) {
temporary[k] = array[i] + "H";
k++;
}
for (int i = 0; i < secondTypeMove + firstTypeMove; i++) {
array[i] = temporary[i];
}
return secondTypeMove + firstTypeMove;
And the last part collects the outputs from both H and V directions into the global array and returns the number of outputs to the upper stack.

Here is a simpler recursive Depth First Search that will do the same:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
dfsPrintAllPathesTopToBottom(3,3);
}
//performs dfs to map all possible paths on a rows x columns matrix
//from top left to bottom right by moving right (R) or down (R)
public static void dfsPrintAllPathesTopToBottom(int rows, int columns){
List<String> path = new ArrayList<>();
dfsPrintAllPathesTopToBottom(0, 0,rows,columns,path);
}
public static void dfsPrintAllPathesTopToBottom(int row, int col, int rows, int columns, List<String> path ){
if(row == rows -1 && col == columns -1){//bottom left reached
System.out.println(path);
return;
}
//move right
int newCol = col +1;
if(newCol < columns ){
List<String>newPath = new ArrayList<>(path);
newPath.add("R");//or newPath.add("H")
dfsPrintAllPathesTopToBottom(row, newCol, rows, columns, newPath);
}
//move down
int newRow = row +1;
if(newRow < rows ){
List<String>newPath = new ArrayList<>(path);
newPath.add("D"); //or newPath.add("V")
dfsPrintAllPathesTopToBottom(newRow, col, rows, columns, new ArrayList<>(newPath));
}
}
}

Related

How to find duplicates in a submatrices of 2d matrix and compare them

I have a question. Can anyone help me with finding duplicates in submatrices?
I have a code which finds submatrices in 2d matrix, but I can't find duplicates. I thought to push the values onto the Stack (because in assignment I should use Stack), find all duplicates in each submatrix, and then compare them, but I don't really know how to do it. I'll be very gratefull, if anyone help me to finish this program.
My code:
public static void main(String[] args) throws Exception {
int[][] data = new int[3][3];
Random random = new Random();
for(int i=0; i<data.length;i++)
{
for(int j=0; j<data.length; j++)
{
data[i][j] = random.nextInt(10);
}
}
printSubMatrix(data);
}
private static void printSubMatrix(int[][] mat) {
int rows=mat.length;
int cols=mat[0].length;
Stack _stack = new Stack();
//prints all submatrix greater than or equal to 2x2
for (int subRow = rows; subRow >= 2; subRow--) {
int rowLimit = rows - subRow + 1;
for (int subCol = cols; subCol >= 2; subCol--) {
int colLimit = cols - subCol + 1;
for (int startRow = 0; startRow < rowLimit; startRow++) {
for (int startCol = 0; startCol < colLimit; startCol++) {
for (int i = 0; i < subRow; i++) {
for (int j = 0; j < subCol; j++) {
System.out.print(mat[i + startRow][j + startCol] + " ");
_stack.push(mat[i+startRow][j+startCol]);
}
System.out.print("\n");
}
System.out.print("\n");
}
}
}
}
System.out.printf(_stack.toString().replaceAll("\\[", "").replaceAll("]", ""));
}

How to escape infinite loop in this recursive code?

I am implementing N-Queen problem solver with backjumping algorithm and I have caught infinite loop error in recursive call.
I have mainly caused trouble in returning function.I think I have error in designing recursive calls.
package Backjumping;
import org.python.google.common.primitives.Ints;
import java.util.*;
public class Backjumping {
int size;
List<Integer> columns;
int numberofplaces;
int numberofbacktracks;
HashMap<Integer, List<Integer>> conflict;
boolean noBreak = true;
Backjumping(int size) {
this.size = size;
columns = new ArrayList();
conflict = new HashMap<>(size);
for (int i = 0; i < size; i++) {
conflict.put(i, new ArrayList<>());
}
}
List place(int startRow) {
if (columns.size() == size) {
System.out.println("Solution Found! The board size was :" + size);
System.out.println(numberofplaces + " total nodes assigned were made.");
System.out.println(numberofbacktracks + " total backtracks were executed.");
return this.columns;
} else {
for (int row = 0; row < size; row++) {
if (isSafe(columns.size(), row)) {
if (indexExists(columns, columns.size()))
columns.set(columns.size(), row);
else
columns.add(columns.size(), row);
numberofplaces += 1;
return place(startRow);
}
}
if (noBreak) {
List<Integer> max_check = conflict.get(columns.size());
int lastRow = Collections.min(max_check);
numberofbacktracks += 1;
conflict.replace(columns.size(), new ArrayList<>());
int previous_variable = columns.remove(lastRow);
return place(previous_variable);
}
}
return this.columns;
}
private boolean isSafe(int cols, int rows) {
for (int threatrow : columns) {
int threatcol = columns.indexOf(threatrow);
if (rows == threatrow || cols == columns.indexOf(threatrow)) {
(conflict.get(cols)).add(threatcol);
return false;
} else if ((threatrow + threatcol) == (rows + cols) || (threatrow - threatcol) == (rows - cols)) {
(conflict.get(cols)).add(threatcol);
return false;
}
}
return true;
}
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
public static void main(String[] args) {
System.out.println("Enter the size of board");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Backjumping bj = new Backjumping(n);
double start = System.currentTimeMillis();
List cols = bj.place(0);
double end = System.currentTimeMillis();
System.out.println("Time to solve in second = " + (end - start) * 0.001 + " s");
System.out.print("Ths solution is : ");
cols.forEach(i -> System.out.print(((int) i + 1) + ", "));
System.out.println("\n\nPlotting CSP result on N_Queens board");
System.out.println("......................................\n");
bj.getBoardPic(n, cols);
}
public void getBoardPic(int size, List columns) {
int[] cols = Ints.toArray(columns);
int[][] matrix = new int[size][size];
for (int a = 0; a < size; a++) {
int j = cols[a];
matrix[a][j] = 1;
}
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
if (matrix[b][a] == 1)
System.out.print(" Q ");
else
System.out.print(" - ");
}
System.out.println();
}
}
}
The main errors are that when I assign row=0 in for (int row = 0; row < size; row++) the input size of n=6 goes wrong and other values are right.
When I assign row=startrow in for (int row = startrow; row < size; row++) the input size of n=6 goes right and other values are wrong.

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; "-";

Grid and adjacency matrix in java

Need little help with my programming.
I'd like to create a grid with n columns and n rows. A also would like to show or print adjacency matrix.For start I did create some code, but the results are not correct, and I don't know hot to fix it. I need this grid to calculate shortest path, mutation of this grid, ...
The first for loop create a nice grid size n*n, but I don't know how to create links between naighbour nodes. The second code (which is in comment, create a adjacency matrix, but is not correnct -> node 3-4,7-8, 11-12 shouldn't be connected (if we have 4x4 grid), and in this code is missing last 4 nodes (if n=4).
Can someone tell me where did I fail in my coding :)?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Network_1 {
public static void main(String[] args) throws Exception {
BufferedReader input1 = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter the number of columns/rows");
int cols = Integer.parseInt(input1.readLine());
input1.close();
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
if (i > 1
&& ((cols == 0 && N % i == 0) || (cols > 0 && i % cols == 0))) {
if (cols == 0) {
cols = i;
}
System.out.print("\n");
}
System.out.format("%3d", i);
}
System.out.println("\nAdjacency matrix:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println();
}
/*
// If I try to create my "grid" with this code, I do not get true results
// The Matrix is incorrect
for(int i=0; i<N-cols; i++){
for(int j=0; j<N-cols; j++){
if((cols > 0) && (i % cols == 0)){
A[i][i+1] = 0;
A[i + 1][i] = 0;
}else{
A[i][i+1] = 1;
A[i + 1][i] = 1;
A[i][i+cols] = 1;
A[i + cols][i] = 1;
}
}
}
System.out.println("Adjacency matrix2:");
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.print(A[i][j] + " ");
}
System.out.println("");
}
*/
}
}
Helo. I did some other approach and this work quite well for me right now. I know tis isn't the best solution, but it wokrs for now. Now I will etst if realy works...
public static int[][] make_grid(int cols) {
int N = cols * cols;
int[][] A = new int[N][N];
for (int i = 0; i < N; i++) {
A[i][i] = 0;
int left= i - 1;
int right= i + 1;
int upper= i - cols;
int bottom= i + cols;
if (left> 0)
A[i][left] = 1;
if (rigft% cols != 0) {
if (right< N)
A[i][right] = 1;
}
if (upper> 0)
A[i][upper] = 1;
if (bottom< N)
A[i][bottom] = 1;
}
return A;
}

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