Grid and adjacency matrix in java - 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;
}

Related

How to sort 2D array by columns and by diagonal using Selection Sort in Java

Firsly, I have a Matrix which I need to sort in such way (shown on the picture) using Selection Sort:
the way to sort the Matrix
Thus, the array should be sorted in increasing way from up to down. What's more, we have to sort elements of the right diagonal of Matrix.
Here's my code, but it doesn't work properly because I take diagonal into account.
public class PAS {
public static void main(String[] args) {
int n = 5; int max = 25; int minimL = 0; int MinRow, Temp;
int[][] array = new int [n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
array[i][j] = (int) (Math.random() * (max - minimL + 1) + minimL);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(" " + array[i][j]);
System.out.println();
}
System.out.println();
for (int NumCol = n - 1; NumCol >= 0; NumCol --) {
for (int NumRow = 0; NumRow < n; NumRow++) {
if (NumCol >= n - NumRow - 1) // Getting the right diagonal of Matrix changing position of columns to rows in order to sort them
{
MinRow = NumRow;
for (int j = NumRow + 1; j < n; j++)
if (array[(n - 1) - NumCol][NumCol] > array[MinRow][(n - 1) - NumCol])
MinRow = j;
Temp = array[NumRow][(n - 1) - NumCol];
array[(n - 1) - NumCol][NumCol] = array[MinRow][(n - 1) - NumCol];
array[MinRow][(n - 1) - NumCol] = Temp;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(" " + array[i][j]);
}
System.out.println();
}
}
}
Is it possible to sort it properly in the way shown on the picture taking O(n^3) notation?

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

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));
}
}
}

Java: Sudoku- increase number of empty spaces causes my code to throw an exception

I'm trying to make a Sudoku game for my project but if i increase the number of empty spaces in the Sudoku Grid the code just throws an exception arrayoutofbounds but can't figure out where it's coming from. k is the number of empty spaces in the grid.
I haven't tried anything because can't figure out what can be done at this kind of problem
Here is the code:
package sudoku.puzzle;
import java.util.*;
public class SudokuPuzzle {
int[] mat[];
int N; // number of columns/rows.
int SRN; // square root of N
int K; // No. Of missing digits
// Constructor
SudokuPuzzle(int N, int K) {
this.N = N;
this.K = K;
// Compute square root of N
Double SRNd = Math.sqrt(N);
SRN = SRNd.intValue();
mat = new int[N][N];
}
// Driver code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Select Level Of Difficulty \n 1.Easy\n 2.Medium\n 3.Hard");
String Choice = in .next(); in .close();
if ("1".equals(Choice) || "Easy".equals(Choice) || "easy".equals(Choice) || "e".equals(Choice) || "E".equals(Choice)) {
int N = 9, K = 40;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
if ("2".equals(Choice) || "Medium".equals(Choice) || "medium".equals(Choice) || "m".equals(Choice) || "M".equals(Choice)) {
int N = 9, K = 60;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
if ("3".equals(Choice) || "Hard".equals(Choice) || "hard".equals(Choice) || "h".equals(Choice) || "H".equals(Choice)) {
int N = 9, K = 72;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
}
// Sudoku Generator
public void fillValues() {
// Fill the diagonal of SRN x SRN matrices
fillDiagonal();
// Fill remaining blocks
fillRemaining(0, SRN);
// Remove Randomly K digits to make game
removeKDigits();
}
// Fill the diagonal SRN number of SRN x SRN matrices
void fillDiagonal() {
for (int i = 0; i < N; i = i + SRN)
// for diagonal box, start coordinates->i==j
fillBox(i, i);
}
// Returns false if given 3 x 3 block contains num.
boolean unUsedInBox(int rowStart, int colStart, int num) {
for (int i = 0; i < SRN; i++)
for (int j = 0; j < SRN; j++)
if (mat[rowStart + i][colStart + j] == num)
return false;
return true;
}
// Fill a 3 x 3 matrix.
void fillBox(int row, int col) {
int num;
for (int i = 0; i < SRN; i++) {
for (int j = 0; j < SRN; j++) {
do {
num = randomGenerator(N);
}
while (!unUsedInBox(row, col, num));
mat[row + i][col + j] = num;
}
}
}
// Random generator
int randomGenerator(int num) {
return (int) Math.floor((Math.random() * num + 1));
}
// Check if safe to put in cell
boolean CheckIfSafe(int i, int j, int num) {
return (unUsedInRow(i, num) &&
unUsedInCol(j, num) &&
unUsedInBox(i - i % SRN, j - j % SRN, num));
}
// check in the row for existence
boolean unUsedInRow(int i, int num) {
for (int j = 0; j < N; j++)
if (mat[i][j] == num)
return false;
return true;
}
// check in the row for existence
boolean unUsedInCol(int j, int num) {
for (int i = 0; i < N; i++)
if (mat[i][j] == num)
return false;
return true;
}
// A recursive function to fill remaining
// matrix
boolean fillRemaining(int i, int j) {
// System.out.println(i+" "+j);
if (j >= N && i < N - 1) {
i = i + 1;
j = 0;
}
if (i >= N && j >= N)
return true;
if (i < SRN) {
if (j < SRN)
j = SRN;
} else if (i < N - SRN) {
if (j == (int)(i / SRN) * SRN)
j = j + SRN;
} else {
if (j == N - SRN) {
i = i + 1;
j = 0;
if (i >= N)
return true;
}
}
for (int num = 1; num <= N; num++) {
if (CheckIfSafe(i, j, num)) {
mat[i][j] = num;
if (fillRemaining(i, j + 1))
return true;
mat[i][j] = 0;
}
}
return false;
}
// Remove the K no. of digits to
// complete game
public void removeKDigits() {
int count = K;
while (count != 0) {
int cellId = randomGenerator(N * N);
// System.out.println(cellId);
// extract coordinates i and j
int i = (cellId / N);
int j = cellId % 9;
if (j != 0)
j = j - 1;
// System.out.println(i+" "+j);
if (mat[i][j] != 0) {
count--;
mat[i][j] = 0;
}
}
}
// Print sudoku
public void printSudoku() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
System.out.println();
}
}
What you got is probably a ArrayIndexOutOfBoundsException. That means at some point you try to access a field of an array outside its boundaries.
But I can´t see where K could be responsible for that. Can you provide more information about the error? E.g. at which value you get it or in which line.
EDIT: The variable i int the removeKDigits() function exceeds the boundaries of the array if the random generator spits out the value 81.

different output in conways game of life

I have to create a Java program for Conway's Game Of Life in procedural manner and I'm only one step away from finishing - all I have left to do is figure out how to make the output change itself(something like a GIF). Instead, my program outputs all the results one by one. I'm figuring it should be some kind of a loop, but I'm not sure. Here's the code:
import java.util.Random;
import java.util.Scanner;
class gameOfLife {
public static void main(String[] args) {
//User input
Scanner in = new Scanner(System.in);
System.out.println("How many rows?");
int rows = in.nextInt();
System.out.println("How many columns?");
int cols = in.nextInt();
//Declaring variables and grids
int[][] grid = new int[rows][cols];
int[][] nextGrid = new int[rows][cols];
int[][] temp = new int [rows][cols];
//Initializing first generation
initiateGrid(grid);
printGameBoard(grid);
//Looping through 10 generations
for (int x = 0; x < 20; x++) {
applyTheRules(grid, rows, cols, nextGrid);
temp = nextGrid;
nextGrid = grid;
grid = temp;
printGameBoard(grid);
}
}
//Initiating first generation grid randomly
static void initiateGrid(int[][] grid) {
Random r = new Random();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = r.nextInt(2);
}
}
}
//Printing out the game board
static void printGameBoard(int[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 0)
System.out.print(" . ");
else
System.out.print(" ■ ");
}
System.out.println();
}
System.out.println();
}
//Applying the rules of the game
static void applyTheRules(int [][] grid, int rows, int cols, int [][] nextGrid) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int count = 0;
if(i-1>=0 && i+1<grid.length && j-1>=0 && j+1<grid[i].length) {
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += grid[i + x][j + y];
}
}
count -= grid[i][j];
} else{
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
count += 0;
}
}
}
//Alive cell becomes dead, if there are more than
//3 or less than 2 neighbouring cells
if((grid[i][j]==1)&&(count<2)||(count>3))
nextGrid[i][j]=0;
//Dead cell becomes alive if there are exactly 3 neighbouring cells
else if((grid[i][j]==0)&&(count==3))
nextGrid[i][j]=1;
//State stays the same
else
nextGrid[i][j]=grid[i][j];
}
}
}
}

Sudoku Generator Algorithm Malfunction

I have a project at school where I have to create a Sudoku Program. I have managed to get a Solver algorithm working but not a Generator. I spent a lot of time online to see if people had found ways to make a working one and I found a man named Mark Fredrick Graves, Jr. (https://www.youtube.com/user/mfgravesjr) who provided a very detailed code on the creation of a sudoku grid on his GitHub (https://github.com/mfgravesjr/finished-projects/tree/master/SudokuGridGenerator). However, I felt that using a one dimensional array was unnecessarily difficult in terms of finding the equations to access lines, columns and boxes. I therefore tried to translate his code into a two dimensional array but I am running into issues with some of his sorting methods and what some variables represent like "int step = (a%2==0? rowOrigin + j: colOrigin + j*9);". What I would like to know is how to translate the methods he uses from one dimensional arrays into two dimensional arrays. Below are the methods (code snippets) in question and my half attempt at translating it myself.
public int[] generateGrid(){
ArrayList<Integer> arr = new ArrayList<Integer>(9);
solvedGrid = new int[81];
for(int i = 1; i <= 9; i++) arr.add(i);
//loads all boxes with numbers 1 through 9
for(int i = 0; i < 81; i++){
if(i%9 == 0) {
Collections.shuffle(arr);
}
int perBox = ((i / 3) % 3) * 9 + ((i % 27) / 9) * 3 + (i / 27) * 27 + (i % 3);
solvedGrid[perBox] = arr.get(i%9);
}
//tracks rows and columns that have been sorted
boolean[] sorted = new boolean[81];
for(int i = 0; i < 9; i++){
boolean backtrack = false;
//0 is row, 1 is column
for(int a = 0; a<2; a++){
//every number 1-9 that is encountered is registered
boolean[] registered = new boolean[10]; //index 0 will intentionally be left empty since there are only number 1-9.
int rowOrigin = i * 9;
int colOrigin = i;
ROW_COL: for(int j = 0; j < 9; j++){
//row/column stepping - making sure numbers are only registered once and marking which cells have been sorted
int step = (a%2==0? rowOrigin + j: colOrigin + j*9);
int num = solvedGrid[step];
if(!registered[num]) {
registered[num] = true;
}else {
//if duplicate in row/column
//box and adjacent-cell swap (BAS method)
//checks for either unregistered and unsorted candidates in same box,
//or unregistered and sorted candidates in the adjacent cells
for(int y = j; y >= 0; y--){
int scan = (a%2==0? i * 9 + y: i + 9 * y);
if(solvedGrid[scan] == num){
//box stepping
for(int z = (a%2==0? (i%3 + 1) * 3: 0); z < 9; z++){
if(a%2 == 1 && z%3 <= i%3) {
continue;
}
int boxOrigin = ((scan % 9) / 3) * 3 + (scan / 27) * 27;
int boxStep = boxOrigin + (z / 3) * 9 + (z % 3);
int boxNum = solvedGrid[boxStep];
if((!sorted[scan] && !sorted[boxStep] && !registered[boxNum]) || (sorted[scan] && !registered[boxNum] && (a%2==0? boxStep%9==scan%9: boxStep/9==scan/9))){
solvedGrid[scan] = boxNum;
solvedGrid[boxStep] = num;
registered[boxNum] = true;
continue ROW_COL;
}else if(z == 8) {
//if z == 8, then break statement not reached: no candidates available
//Preferred adjacent swap (PAS)
//Swaps x for y (preference on unregistered numbers), finds occurence of y
//and swaps with z, etc. until an unregistered number has been found
int searchingNo = num;
//noting the location for the blindSwaps to prevent infinite loops.
boolean[] blindSwapIndex = new boolean[81];
//loop of size 18 to prevent infinite loops as well. Max of 18 swaps are possible.
//at the end of this loop, if continue or break statements are not reached, then
//fail-safe is executed called Advance and Backtrack Sort (ABS) which allows the
//algorithm to continue sorting the next row and column before coming back.
//Somehow, this fail-safe ensures success.
for(int q = 0; q < 18; q++){
SWAP: for(int b = 0; b <= j; b++){
int pacing = (a%2==0? rowOrigin+b: colOrigin+b*9);
if(solvedGrid[pacing] == searchingNo){
int adjacentCell = -1;
int adjacentNo = -1;
int decrement = (a%2==0? 9: 1);
for(int c = 1; c < 3 - (i % 3); c++){
adjacentCell = pacing + (a%2==0? (c + 1)*9: c + 1);
//this creates the preference for swapping with unregistered numbers
if((a%2==0 && adjacentCell >= 81)
|| (a%2==1 && adjacentCell % 9 == 0)) {
adjacentCell -= decrement;
}else {
adjacentNo = solvedGrid[adjacentCell];
if(i%3!=0
|| c!=1
|| blindSwapIndex[adjacentCell]
|| registered[adjacentNo]) {
adjacentCell -= decrement;
}
}
adjacentNo = solvedGrid[adjacentCell];
//as long as it hasn't been swapped before, swap it
if(!blindSwapIndex[adjacentCell]){
blindSwapIndex[adjacentCell] = true;
solvedGrid[pacing] = adjacentNo;
solvedGrid[adjacentCell] = searchingNo;
searchingNo = adjacentNo;
if(!registered[adjacentNo]){
registered[adjacentNo] = true;
continue ROW_COL;
}
break SWAP;
}
}
}
}
}
//begin Advance and Backtrack Sort (ABS)
backtrack = true;
break ROW_COL;
}
}
}
}
}
}
if(a%2==0) {
for(int j = 0; j < 9; j++) {
sorted[i*9+j] = true; //setting row as sorted
}
}else if(!backtrack) {
for(int j = 0; j < 9; j++) {
sorted[i+j*9] = true; //setting column as sorted
}
}else {//reseting sorted cells through to the last iteration
//backtrack = false;
for(int j = 0; j < 9; j++) {
sorted[i*9+j] = false;
}
for(int j = 0; j < 9; j++) {
sorted[(i-1)*9+j] = false;
}
for(int j = 0; j < 9; j++) {
sorted[i-1+j*9] = false;
}
for(int j = 0; j < 81; j++) {
sorted[j] = false;
}
i-=2;
}
}
}
if(!isPerfect(solvedGrid)) {
throw new RuntimeException("ERROR: Imperfect grid generated.");
}
return solvedGrid;
}
My code (unfinished)
public int[][] generateGrid(){
ArrayList<Integer> arr = new ArrayList<Integer>(9);
ArrayList<Integer> values = new ArrayList<Integer>(9);
solvedGrid = new int[9][9];
for(int i = 1 ; i <= 9; i++) {
arr.add(i);
values.add(i);
}
//Fill all boxes with number 1 to 9
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(j == 0) {
Collections.shuffle(arr);
}
solvedGrid[(i/3)*3+(j/3)][(i%3)*3+(j%3)] = arr.get(j);
}
}
//boolean[][] sorted = new boolean[9][9];
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
int[] rowColValues = new int[9];
rowColValues[j] = solvedGrid[0][j];
ArrayList<Integer> occurence = new ArrayList<Integer>();
for(int k = 0; k < rowColValues.length; k++) {
occurence.add((k+1), occurence.get(k+1)+1);
if(occurence.get(k+1) != 1) {
//swap with number in the box that isn't already in rowColValues
//Not sure how to do this...
//Create a method that takes the correct variables as parameters ?
break;
}
}
//Read the sudoku row then column wise and swap values that already exist in the column or row.
}
}
print2DGrid(solvedGrid);
return solvedGrid;
}

Categories