Sudoku Checker java - java

public class Sudoku {
public static void main(String[] args) {
// Row and column Latin but with invalid subsquares
String config1 = "1234567892345678913456789124567891235678912346" + "78912345789123456891234567912345678";
String[][] puzzle1 = makeSudoku(config1);
if (isValidSudoku(puzzle1)) {
System.out.println("This puzzle is valid.");
} else {
System.out.println("This puzzle is invalid.");
}
System.out.println(getPrintableSudoku(puzzle1));
System.out.println("--------------------------------------------------");
// Row Latin but column not Latin and with invalid subsquares
String config2 = "12345678912345678912345678912345678912345678" + "9123456789123456789123456789123456789";
String[][] puzzle2 = makeSudoku(config2);
if (isValidSudoku(puzzle2)) {
System.out.println("This puzzle is valid.");
} else {
System.out.println("This puzzle is invalid.");
}
System.out.println(getPrintableSudoku(puzzle2));
System.out.println("--------------------------------------------------");
// A valid sudoku
String config3 = "25813764914698532779324685147286319558149273663" + "9571482315728964824619573967354218";
String[][] puzzle3 = makeSudoku(config3);
if (isValidSudoku(puzzle3)) {
System.out.println("This puzzle is valid.");
} else {
System.out.println("This puzzle is invalid.");
}
System.out.println(getPrintableSudoku(puzzle3));
System.out.println("--------------------------------------------------");
}
public static String[][] makeSudoku(String s) {
int SIZE = 9;
int k = 0;
String[][] x = new String[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
x[i][j] = s.substring(k, k + 1);
k++;
}
}
return x;
}
public static String getPrintableSudoku(String[][] x) {
int SIZE = 9;
String temp = "";
for (int i = 0; i < SIZE; i++) {
if ((i == 3) || (i == 6)) {
temp = temp + "=================\n";
}
for (int j = 0; j < SIZE; j++) {
if ((j == 3) || (j == 6)) {
temp = temp + " || ";
}
temp = temp + x[i][j];
}
temp = temp + "\n";
}
return temp;
}
//sudoku validation
public static boolean isValidSudoku(String[][] x) {
return rowsAreLatin(x) && colsAreLatin(x) && goodSubsquares(x);
}
public static boolean rowsAreLatin(String[][] x) {
// fill in your code here
boolean result = true; // Assume rows are latin
for (int i = 0; i < 9; i++) {
result = result && rowIsLatin(x, i); // Make sure each row is latin
}
return result;
}
public static boolean rowIsLatin(String[][] x, int i) {
boolean[] found = new boolean[9];
for (int j = 0; j < 9; j++) {
found[Integer.parseInt(x[i][j])] = true;
}
for (int j = 0; j < 9; j++) {
if (!found[j]) {
return false;
}
}
return true;
}
public static boolean colsAreLatin(String[][] x) {
// fill in your code here
boolean result = true; // Assume cols are latin
for (int j = 0; j < 9; j++) {
result = result && colIsLatin(x, j); // Make sure each row is latin
}
return result;
}
public static boolean colIsLatin(String[][] x, int j) {
// fill in your code here
boolean[] found = new boolean[9];
for (int i = 0; i < 9; i++) {
found[Integer.parseInt(x[i][j])] = true;
}
for (int i = 0; i < 9; i++) {
if (!found[i]) {
return false;
}
}
return true;
}
public static boolean goodSubsquares(String[][] x) {
return true;
}
public static boolean goodSubsquare(String[][] x, int i, int j) {
boolean[] found = new boolean[9];
// We have a 3 x 3 arrangement of subsquares
// Multiplying each subscript by 3 converts to the original array subscripts
for (int p = i * 3, rowEnd = p + 3; p < rowEnd; p++) {
for (int q = j * 3, colEnd = q + 3; q < colEnd; q++) {
found[Integer.parseInt(x[p][q])] = true;
}
}
for (int p = 0; p < 9; p++) {
if (!found[p]) {
return false;
}
}
return true;
}
}
This the error I am getting. Help!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at Sudoku.rowIsLatin(Sudoku.java:104)
at Sudoku.rowsAreLatin(Sudoku.java:93)
at Sudoku.isValidSudoku(Sudoku.java:85)
at Sudoku.main(Sudoku.java:8)
Java Result: 1

The problem is with the line:
Integer.parseInt(x[i][j])
Sudoku numbers range from [1, 9], but indices for an array (of length 9) range from [0, 8]. So, when the (i, j) element is a 9, the index is 9 and therefore the IndexOutOfBoundsException is being thrown.
You'll have to change it to
found[Integer.parseInt(x[i][j]) - 1] = true;
Note that you also make the same mistake in the column's respective method.

Related

search palindrome number in a list of array. if there exist palindrome number in the list, return its size

Check if there exists a Palindrome Number in the list.
If found return its size, else return -1.
public class Program{
public static boolean palindrome(String list){
String reversedString = "";
for (int i = list.length() -1; i >=0; i--){
reveresedString += list.charAt(i)
}
return list.equals(revereseString);
}
}
sample input: [3,5,2,6,3,6,2,1]
palindrome number found: [2,6,3,6,2]
sample output: 5
Here is a pseudo code.
output = -1;
for (i = 0; i < list.length; i++){
num = list[i];
indices[] = \\ get all the indices which the "num" value appears, only include those indices that are greater than "i"
for (j = 0; j < indices.length; j++){
flag = true;
k = i;
for (l = indices[j]; l >= k; l--, k++){
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag){
length = (indices[j] - i) + 1;
if (length != 1 && length > output) { // checking of length != 1 will exclude those palindromes of length 2
output = length;
}
}
}
}
return output;
Here is the full code.
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
int[] list = { 3, 5, 2, 2, 6, 3, 6, 3, 6, 3, 6, 2, 2, 1 };
System.out.print(palindrome(list));
}
public static int palindrome(int[] list) {
int output = -1;
for (int i = 0; i < list.length; i++) {
int num = list[i];
ArrayList<Integer> indices = getIndices(list, i, num);
for (int j = 0; j < indices.size(); j++) {
boolean flag = true;
int k = i;
for (int l = indices.get(j); l >= k; l--, k++) {
if (list[k] != list[l]) {
flag = false;
break;
}
}
if (flag) {
int length = (indices.get(j) - i) + 1;
if (length != 1 && length > output) {
output = length;
}
}
}
}
return output;
}
public static ArrayList<Integer> getIndices(int[] list, int start, int num) {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = start + 1; i < list.length; i++) {
if (list[i] == num) {
result.add(i);
}
}
return result;
}
}

how can i determine all prime numbers smaller than a given input value? [duplicate]

This question already has answers here:
Return all prime numbers smaller than M
(9 answers)
Closed 3 years ago.
Can anyone help me to determine all prime numbers smaller than a given input value using scanner with java8 .
Input: N integer> 0
Output: the table with prime numbers.
Example: for N = 10 the Output is : 2 3 5 7
this is my work so far:
class Main {
public static void main(String[] args) {
int N;
int[] result = null;
try (Scanner scanner = new Scanner(new File(args[0]))) {
N = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < (N/2)+1; i++) {
if (N%i==0)
result[i]=i;
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
}
System.out.println();
}
catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
}
your code problem is int i = 0 start with 0 and next line if (N%i==0) so 10/0 is not possible throw a error something like java.lang.ArithmeticException: / by zero is not possible
and you loop through result.length, you need to loop through i your parent loop and put condition inside if (N%i==0) and you need many changes saw my below answer and debug where you get unexpected output and follow.
brute Force
public static void main(String[] args) {
int N = 50;
List<Integer> result = new ArrayList<>();
for (int i = 1; i < N; i++) {
boolean isPrime = true;
for (int j = 2; j < i - 1; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
optimize one using Math.sqrt reason
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
using BigInteger.isProbablePrime see
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (long i = 1; i <= N; i++) {
BigInteger integer = BigInteger.valueOf(i);
if (integer.isProbablePrime(1)) {
result.add((int) i);
}
}
result.forEach(System.out::println);
}
Updated 1:- that something you want
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] result = new int[N];
int resultIncreamenter = 0;
// here for loop logic can be replaced with above 3 logic
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result[resultIncreamenter++] = i;
}
}
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
You lost the overview, though you have all functionality within reach.
public static boolean isPrime(int n) {
for (int i = 0; i < (n/2)+1; i++) {
if (n%i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
Simply use abstractions like isPrime.
Now for improvements (your results array): use the already found primes instead of all numbers in testing:
public static boolean isPrime(int n, int[] priorPrimes, int primesCount) {
for (int p : priorPrimes) {
if (n%p == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] primes = new int[N];
int primesCount = 0;
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
primes[primesCount] = j;
++primesCount;
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
The algorithm using the Sieve of Eratosthenes taken from here:
private static int findNumberOfPrimes(int length) {
int numberOfPrimes = 1;
if (length == 2) {
return 1;
}
int[] arr = new int[length];
//creating an array of numbers less than 'length'
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
//starting with first prime number 2, all the numbers divisible by 2(and upcoming) is replaced with -1
for (int i = 2; i < arr.length && arr[i] != -1; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[j] % arr[i] == 0) {
arr[j] = -1;
numberOfPrimes += 1;
}
}
}
return numberOfPrimes;
}
Update :
and this is how you list them :
package primelessthanN;
public class Main {
public static void main(String[] args) {
int j;
int n;
n = 10;
for (j = 2; j <=n; j++) {
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int m) {
for (int i = 2; i <= sqrt(m); i++) {
if (m % i == 0)
return false;
}
return true;
}
}

Check whether this matrix is symmetric in relation to the main diagonal

Given the number n, not exceeding 10, and a matrix of size n × n.
Check whether this matrix is symmetric in relation to the main diagonal. Output the word “YES”, if it is symmetric and the word “NO” otherwise.
This is my code, it unfortunately does not work. Please, explain to me how to do it correctly :)
public class Main { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
int unevenchecker = (n% 2);
if (unevenchecker != 0) {
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] == number[l][k]) {
ismatch = true;
}
}
}
if (ismatch) {
System.out.print("YES");
}
} else {
System.out.print("NO");
}
}
}
The matrix is not symmetric if you find at least 1 symmetric couple where the 2 parts are not equal, so instead of checking for equality inside the loop, check for inequality:
ismatch = true;
for (int k = 0; k < number.length - 1; k++) {
for (int l = 0; l < number.length - 1; l++) {
if (number[k][l] != number[l][k]) {
ismatch = false;
break;
}
}
}
public class Main {
static boolean isSymmetric(int mat[][], int size) {
for (int i = 0; i < size; i++)
for (int j = i + 1; j < size - i; j++)
if (mat[i][j] != mat[j][i])
return false;
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
int[][] number = new int[n][n];
boolean ismatch = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
number[i][j] = scanner.nextInt();
}
}
if (isSymmetric(number, n)) {
System.out.print("YES");
} else {
System.out.print("NO");
}
}
}
Notice that the nested loop into isSymmetric starts from j = i + 1, for not checking twice same condition.

n Queens Java not working for 4 by 4

My n Queens variation with an input seems to work for all inputs except 4x4 boards. It takes a board size and a starting position for 1 queen. Is there a reason why it isn't working for that size? I tried inputting 4 1 2 and it doesn't create a board properly
import java.io.*;
public class nQueens {
public static int N;
public static int skipCol;
public static int permaRow;
public static void printSolution(int board[][]) {
PrintWriter file = null;
try {
file = new PrintWriter("solution.txt");
// Prints Board to solution.txt
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1) {
// If board = 1 then there is a Queen, 0 then empty
file.println((i + 1) + " " + (j + 1));
}
}
}
file.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean isSafe(int board[][], int row, int col) {
// Returns True if safe, returns False if not safe
// Checks all columns in the row
int i,j;
for (i = 0; i < col; i++) {
if (board[row][i] == 1) {
return false;
}
}
// Check Diagonals (upper then lower)
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}
for (i = row, j = col; j >= 0 && i < N; i++, j--) {
if (board[i][j] == 1) {
return false;
}
}
return true;
}
public static boolean solveNQueensCol(int board[][], int col) {
if (col >= N) { // Base Case, checks if all queens are placed
return true;
}
if (col != skipCol) {
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1; // Changes that board space to Queen
if (solveNQueensCol(board, col + 1) == true) {
// Recursively places all the Queens onto the board
return true;
}
// If placing queen at i, col doesn't work, remove it
board[i][col] = 0;
}
}
} else {
board[permaRow][skipCol] = 1; // One Preset Queen
return solveNQueensCol(board,col+1);
}
return false;
}
public static boolean solveNQueens(int x, int y) {
// Creates new board with size N
int board[][] = new int[N][N];
for (int i = 0; i < N; i++) { // Fills board with 0s
for (int j = 0; j < N; j++) {
board[i][j] = 0;
}
}
permaRow = x;
skipCol = y;
if (solveNQueensCol(board, 0) == false) {
PrintWriter file = null;
try {
file = new PrintWriter("solution.txt");
// Prints Board to solution.txt
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1) {
// If board = 1 then there is a Queen, 0 then empty
file.println((i + 1) + " " + (j + 1));
}
}
}
file.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
printSolution(board);
return true;
}
public static void main(String[] args) {
N = Integer.parseInt(args[0]);
solveNQueens(Integer.parseInt(args[1]) - 1, Integer.parseInt(args[2]) - 1);
}
}
If rows and columns are counted from 0 to 3, there is no solution when a queen starts in position 1,2.

How do I avoid getting NullPointerException in my Matrix sum?

I want to check if the sum of each row in any matrix is equal. How should I rewrite this to avoid NPE?
I can make it work for "normal" matrices like int[][] a = {{1,2,3}, {4,5,6}}, but I want it to work even when testing with null and empty matrices.
public static boolean allRowSumsEqual(int[][] m) {
boolean a = false;
int x = 0;
int total = rowSum(m[0]);
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
x += m[i][j];
}
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}
public static int rowSum(int[] v) {
int vSum = 0;
for (int i = 0; i < v.length; i++) {
vSum += v[i];
}
return vSum;
}
As you said, this does work for most matrices. There are a few places I might check for null, see modified code below:
public static boolean allRowSumsEqual(int[][] m){
if(m == null) return true;
if(m.length == 0) return true;
boolean a = false;
int x = 0;
int total = rowSum(m[0]);
for (int i = 1; i < m.length; i++){
// You can use your own function instead of the inner for loop
x = rowSum(m[i]);
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}
public static int rowSum(int[] v){
int vSum = 0;
// Assume a null row has sum 0
if(v == null) return 0;
for (int i = 0 ; i < v.length ; i++){
vSum += v[i];
}
return vSum;
}
You need to define a result or an exception if you want to check for "null" parameter. You can return true if null is valid or false otherwise.
if(m == null) return true;
Empty or one lined matrices can return true all the time and does not require any calculation:
if(m.length < 2) return true;
The line test is more simple, I think:
// expect a positiv result
boolean result = true;
// calculate first line
int firstLine = rowSum(m[0]);
// loop remaining lines
for (int i = 1 ; i < m.length ; i++){
// compare first line with current line
if (firstLine != rowSum(m[i]))
{
// not equal -> change result
result = false;
// break loop
break;
}
}
return result;
public class Snippet {
public static boolean allRowSumsEqual(int[][] m) {
if (null == m || 0 == m.length)
return true;
boolean a = false;
int x = 0;
int total = 0;
if (null != m[0])
total = rowSum(m[0]);
for (int i = 1; i < m.length; i++) {
if (null != m[i]) {
for (int j = 0; j < m[i].length; j++) {
x += m[i][j];
}
} else
x = 0;
if (x != total) {
a = false;
break;
} else {
x = 0;
a = true;
}
}
return a;
}
public static int rowSum(int[] v) {
int vSum = 0;
for (int i = 0; i < v.length; i++) {
vSum += v[i];
}
return vSum;
}
public static void main(String[] args) {
int[][] a = { { 1, 2, 3 }, { 3, 2, 1 }, null };
System.out.println(allRowSumsEqual(a));
int[][] b = { null, null, null };
System.out.println(allRowSumsEqual(b));
}
}
What do you think of this solution:
public static boolean allRowSumsEqual(int[][] m) {
if(m == null) { return false; }
int sum = 0;
for(int i = 0; i < m.length; i++) {
int temp = 0;
if(m[i] == null) { continue; }
for(int j = 0; j < m[i].length; j++) {
temp += m[i][j];
}
if(i == 0) { //is the first row
sum = temp;
}
else if(sum != temp) {
return false;
}
}
return true;
}

Categories