I am trying this simple sudoku - java

I am trying a simple sudoku program. i started by taking the values in a 3D
array and then copied them into a 1D array by using mr.serpardum's method.
i know that there is an error at the point where i am trying to find
duplicate elements,because even if i give same numbers as input the output
says "its a sudoku" but i can't to find it...apparently i can't add any
image coz i dont have enough credits
public class SecondAssignment {
#SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
int i = 0, j = 0, k = 0;
boolean result = false;
int arr1[][];
arr1 = new int[3][3];
int arr2[];
arr2 = new int[9];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the elements in the sudoku block");
//getting elements into array
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr1[i][j] = Integer.parseInt(br.readLine());
}
}
//printing it in matrix form
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
System.out.print(arr1[i][j] + "\t");
}
System.out.println(" ");
}
//copying array1 elements into array 2
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr2[i * 3 + j] = arr1[i][j];
}
}
//finding duplicate elements
for (i = 0; i < arr2.length; i++) {
for (int m = i + 1; m < arr2.length; m++) {
if (arr2[i] == (arr2[m])) {
System.out.println("Not a sudoku");
//result = true;
} else {
System.out.println("Its a sudoku");
//result = false;
}
}
}
}
}

You can update your code to following
//finding duplicate elements
for( i = 0; i < arr2.length; i++){
for(int m = i+1; m < arr2.length; m++){
if(arr2[i] == (arr2[m])){
result = true;
break;
}
}
}
if(result){
System.out.println("\nNot a sudoku");
}
else{
System.out.println("\nIts a sudoku");
}
You should have used break as soon as the match was found.
This code just checks if duplicate element is present in the array (of size 9) or not.

Related

Sorting Two-Dimensional Array by Row

The requirement is to sort the rows of a two-dimensional array. I feel like my code is very close to being done, but I can't figure out why it isn't displaying the sorted array. I forgot to mention that we are not allowed to use the premade sorting methods. The problem is most likely in the sortRows method. Anyways, here's my code:
public class RowSorting
{
public static void main(String[] args)
{
double[][] numbers = new double[3][3];
double[][] number = new double[3][3];
int run = 0;
String answer = "";
while (run == 0)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3-by-3 matrix row by row: ");
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
numbers[row][column] = input.nextDouble();
}
}
for(int row = 0; row < numbers.length; row++)
{
for(int column = 0; column < numbers[row].length; column++)
{
System.out.print(numbers[row][column] + " ");
}
System.out.print("\n");
}
System.out.println("The sorted array is: \n");
number = sortRows(numbers);
for(int row = 0; row < number.length; row++)
{
for(int column = 0; column < number[row].length; column++)
{
System.out.print(number[row][column] + " ");
}
System.out.print("\n");
}
System.out.print("\nWould you like to continue the program (y for yes or anything else exits): ");
answer = input.next();
if(answer.equals("y"))
{
continue;
}
else
break;
}
}
public static double[][] sortRows(double[][] m)
{
for(int j = 0; j < m[j].length - 1; j++)
{
for(int i = 0; i < m.length; i++)
{
double currentMin = m[j][i];
int currentMinIndex = i;
for(int k = i + 1; k < m[j].length; k++)
{
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
}
if(currentMinIndex != i)
{
m[currentMinIndex][j] = m[j][i];
m[j][i] = currentMin;
}
}
}
return m;
}
}
It looks like this block:
if(currentMin > m[j][i])
{
currentMin = m[j][i];
currentMinIndex = k;
}
Will never happen. Because you just assigned currentMin to m[j][i] two lines before it. I believe you want to use k in that if check. Something like
if (currentMin > m[j][k]){
currentMin = m[j][k];
currentMinIndex = k;
}
As cited per ergonaut, you have a problem with the codeblock
if(currentMin > m[j][i]) ...
and also
m[currentMinIndex][j] = m[j][i];
However, you also have a problem with your for-loops.
for(int j = 0; j < m[j].length - 1; j++) ...
for(int i = 0; i < m.length; i++) ...
Both of these are oddly structured. You probably want to swap these for-loops so that you don't throw index exceptions. This will also cause you address the indices in your code. And modify your j-index for-loop to include the entire range.

How to create public array accessible by all methods, but have user input determine the size of it?

I have multiple arrays whose sizes need to be determined by the user input. These arrays should be accessible in the main method as well as the stepTwo() method. However, I am stuck. The user input doesn't come until the main method, but if I declare the arrays in the main method, then I can't access the arrays in the stepTwo() method. I would prefer not to pass the arrays as parameters to stepTwo() as I tried that before but came up with multiple errors. Any suggestions? See below for complete code:
public class AssignmentIII
{
public static int numProcesses; // Represents the number of processes
public static int numResources; // Represents the number of different types of resources
public static int[] available = new int[numResources]; // Create an emptry matrix for available processes
public static int[][] allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
public static int[][] request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
public static int[] work = new int[numResources]; // Create an empty work matrix
public static Boolean[] finish = new Boolean[numProcesses]; // Create an empty finish matrix
public static void main(String[] args) throws FileNotFoundException
{
try
{
Scanner scan = new Scanner(System.in);
Scanner fileScan = new Scanner(new File("input1.txt")); // Create file scanner
System.out.println("Please enter the total number of processes: ");
numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
numResources = scan.nextInt();
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
// Begin deadlock detection algorithm
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
stepTwo();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
}
public static void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
}
Declare the array as you do - "above main", but initialize it after reading in the appropriate size.
Declaration:
public static int[] available;
Initialization:
available = new int[numResources];
you must initialize the array into de main block, something like this.
public class AssignmentIII
{
public static int numProcesses; // Represents the number of processes
public static int numResources; // Represents the number of different types of resources
public static int[] available ;
public static int[][] allocation ;
public static int[][] request ;
public static int[] work ;
public static Boolean[] finish ;
public static void main(String[] args) throws FileNotFoundException
{
try
{
Scanner scan = new Scanner(System.in);
Scanner fileScan = new Scanner(new File("input1.txt")); // Create file scanner
System.out.println("Please enter the total number of processes: ");
numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
numResources = scan.nextInt();
available = new int[numResources]; // Create an emptry matrix for available processes
allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
work = new int[numResources]; // Create an empty work matrix
finish = new Boolean[numProcesses]; // Create an empty finish matrix
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
// Begin deadlock detection algorithm
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
stepTwo();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
}
public static void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
}
but this, is not a recommended way. Because is not the right way for use the static method and static attribute. Furthermore you should use encapsulation.
Using a better design and encapsulation method, your code can be improved something like this.
public class AssignmentIII
{
int numProcesses; // Represents the number of processes
int numResources; // Represents the number of different types of resources
String filepath;
int[] available = new int[numResources]; // Create an emptry matrix for available processes
int[][] allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
int[][] request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
int[] work = new int[numResources]; // Create an empty work matrix
Boolean[] finish = new Boolean[numProcesses]; // Create an empty finish matrix
public AssignmentIII(int numResources,int numProcesses, String filepath){
this.numProcesses = numProcesses;
this.numResources = numResources;
this.filepath = filepath;
available = new int[numResources]; // Create an emptry matrix for available processes
allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
work = new int[numResources]; // Create an empty work matrix
finish = new Boolean[numProcesses]; // Create an empty finish matrix
}
public void initilizeMatrix() throws FileNotFoundException{
Scanner fileScan = new Scanner(new File(filepath)); // Create file scanner
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
fileScan.close();
}
public void print(){
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
}
// Begin deadlock detection algorithm
public void deadLockdetecter(){
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
}
public void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
public static void main(String[] args) throws FileNotFoundException
{
AssignmentIII assignment;
String p_filepath;
int p_numProcesses;
int p_numResources;
p_filepath = "inpu1t.txt";
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the total number of processes: ");
p_numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
p_numResources = scan.nextInt();
scan.close();
assignment = new AssignmentIII(p_numResources, p_numProcesses, p_filepath);
try
{
assignment.initilizeMatrix();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
assignment.stepTwo();
}
}

How to generate unique chars when populating a 2D array?

How do I make it so that when I output the grid when I run the code, no two numbers or letters will be the same? When I currently run this code I could get 3x "L" or 2x "6", how do I make it so that they only appear once?
package polycipher;
import java.util.ArrayList;
public class Matrix {
private char[][] matrix = new char[6][6];
private int[] usedNumbers = new int[50];
{for(int x = 0; x < usedNumbers.length; x++) usedNumbers[x] = -1;}
private final char[] CIPHER_KEY = {'A','D','F','G','V','X'};
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public Matrix() {
int random;
for(int i = 0; i < CIPHER_KEY.length; i++) {
for(int j = 0; j < CIPHER_KEY.length; j++) {
validation: while(true) {
random = (int)(Math.random()*validChars.length()-1);
for(int k = 0; k < usedNumbers.length; k++) {
if(random == usedNumbers[k]) continue validation;
else if(usedNumbers[k]==-1) usedNumbers[k] = random;
}
break;
}
matrix[i][j] = validChars.split("")[random].charAt(0);
}
}
}
public String toString() {
String output = " A D F G V X\n";
for(int i = 0; i < CIPHER_KEY.length; i++) {
output += CIPHER_KEY[i] + " ";
for(int j = 0; j < CIPHER_KEY.length; j++) {
output += matrix[i][j] + " ";
}
output += "\n";
}
return output;
}
}
This should be much faster than validating each random choice:
Store your valid chars into an array;
char[] valid = validChars.toCharArray();
Shuffle the array;
shuffle(valid)
Go through the positions in the matrix, storing the elements in the same order they appear in the shuffled array.
assert (CIPHER_KEY.length * CIPHER_KEY.length) <= valid.length;
int k = 0;
for (int i = 0; i < CIPHER_KEY.length; i++) {
for (int j = 0; j < CIPHER_KEY.length; j++) {
matrix[i][j] = valid[k++];
}
}
Use a set and generate a new random if the old random number is in the map:
Pseudocode:
Set<Integer> set = new HashSet<Integer>();
for () {
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
while (!set.contains(random)){
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
}
//If we exit this loop it means the set doesn't contain the number
set.add(random);
//Insert your code here
}

extract different number in two array in java

Here i come with to extract different number in two array in java .different number are to be store in third list of array i am new to java could some one guide me in right Direction
which i tried upto now??
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int [] list2 =null;
for (int i = 0; i < list.length; i++)
{
for (int j = 0; j < list1.length; j++)
{
if(list[i]!=list1[j])
{
System.out.println(list2[]);
}
}
}
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int [10] list2 =null;
boolean flag=false;
int k=0;
for (int i = 0; i < list.length; i++)
{
for (int j = 0; j < list1.length; j++)
{
if(list[i]!=list1[j])
{
flag=false;
}
else
{
flag=true;
}
if(flag==true)
{
list2[k]=list[i];
k++;
}
}
}
Now I am pretty sure about answer.
Well the problem is that in java you need to specify the size of the array.
What you can do :
int[] list={1,2,3,4,5,6,7};
int[] list1={1,2,3,4,5,6,7,8,9,10};
int size = list1.length;
boolean found = false;
int[] list2=new int[size];
for (int i = 0; i < list1.length; i++)
{
for (int i = 0; i < list1.length; i++){
if(list[i]==list1[i])
{
found = true;
}
}
if(found)
found = false;
else
list2[i]=list1[i];
}
System.print.out("List2={");
for(int k = 0; k < list2.length; k++){
if(list2[k] != 0)
System.print.out(list2[k] + ", ");
}
System.print.out("}");
(c.f. : JavaDoc)

How to generate combinations obtained by permuting 2 positions in Java

I have this problem, I need to generate from a given permutation not all combinations, but just those obtained after permuting 2 positions and without repetition. It's called the region of the a given permutation, for example given 1234 I want to generate :
2134
3214
4231
1324
1432
1243
the size of the region of any given permutation is , n(n-1)/2 , in this case it's 6 combinations .
Now, I have this programme , he does a little too much then what I want, he generates all 24 possible combinations :
public class PossibleCombinations {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Entrer a mumber");
int n=s.nextInt();
int[] currentab = new int[n];
// fill in the table 1 TO N
for (int i = 1; i <= n; i++) {
currentab[i - 1] = i;
}
int total = 0;
for (;;) {
total++;
boolean[] used = new boolean[n + 1];
Arrays.fill(used, true);
for (int i = 0; i < n; i++) {
System.out.print(currentab[i] + " ");
}
System.out.println();
used[currentab[n - 1]] = false;
int pos = -1;
for (int i = n - 2; i >= 0; i--) {
used[currentab[i]] = false;
if (currentab[i] < currentab[i + 1]) {
pos = i;
break;
}
}
if (pos == -1) {
break;
}
for (int i = currentab[pos] + 1; i <= n; i++) {
if (!used[i]) {
currentab[pos] = i;
used[i] = true;
break;
}
}
for (int i = 1; i <= n; i++) {
if (!used[i]) {
currentab[++pos] = i;
}
}
}
System.out.println(total);
}
}
the Question is how can I fix this programme to turn it into a programme that generates only the combinations wanted .
How about something simple like
public static void printSwapTwo(int n) {
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n - 1;i++)
for(int j = i + 1; j < n; j++) {
// gives all the pairs of i and j without repeats
sb.setLength(0);
for(int k = 1; k <= n; k++) sb.append(k);
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, tmp);
System.out.println(sb);
count++;
}
System.out.println("total=" + count+" and should be " + n * (n - 1) / 2);
}

Categories

Resources