[英]Java Sudoku help: How can i turn my sudoku string to a 2d int?
I am working on a code to check if a sudoku board is a winning board or not.我正在编写代码来检查数独板是否是获胜板。 I have the board as a file that i read and stored in a string.我将电路板作为文件读取并存储在字符串中。 That string is what I am passing through the methods to read it, print it, and then check if the board is a winning board or not.那个字符串就是我通过方法来读取它、打印它,然后检查板是否是获胜板。 It will print if it is or isn't.无论是否存在,它都会打印出来。 I am stuck with trying to convert the String to a 2d int array so it can be checked.我一直在尝试将 String 转换为 2d int 数组,以便对其进行检查。
import java.util.*;
import java.io.*;
public class lab{
public static void main(String args[])throws Exception{
File file = new File("sudoku.txt");
readSudoku("C:\\Users\\offda\\Desktop\\CS2 Week 1\\sudoku.txt");
}
public static void readSudoku(String str)throws Exception{
Scanner sc = new Scanner(new File("C:\\Users\\offda\\Desktop\\CS2 Week 1\\sudoku.txt"));
try{
FileReader fileR = new FileReader("sudoku.txt");
BufferedReader br = new BufferedReader(fileR);
while((str=br.readLine())!=null){
printSudoku(str);
}
br.close();
}catch(IOException e){
System.out.println("Error loading board...");
}
}
public static void printSudoku(String str){
System.out.println(str);
//checkSudoku(str);
}
/*
public static boolean checkSudoku(int[][] str){
for(int i=0; i<str.length;i++){
int[] r= new int[9];
int[] s = new int[9];
int[] c = str[i].clone();
for(int j=0;j<str[i].length;j++){
r[j]=str[j][i];
s[j]=str[(i/3)*3+j/3][i*3%9+j%3];
}
if(!(validate(c)&&validate(r)&&validate(s))){
System.out.println("losing board!");
return false;
}
else{
System.out.println("winning board!");
}
}
return true;
}
public static boolean validate(int[] val){
int v=0;
Arrays.sort(val);
for(int n = 0;n<val.length;n++){
if(n!= v++){
return false;
}
}
return true;
}
*/
}
/*heres my board (txt):
4 8 3 9 2 1 6 5 7
9 6 7 3 4 5 8 2 1
2 5 1 8 7 6 4 9 3
5 4 8 1 3 2 9 7 6
7 2 9 5 6 4 1 3 8
1 3 6 7 9 8 2 4 5
3 7 2 6 8 9 5 1 4
8 1 4 2 5 3 7 6 9
6 9 5 4 1 7 3 8 2
*/
I am going to run this with 5 test cases, each of which should print the whole board along with if its winning sudoku or not.我将用 5 个测试用例运行它,每个测试用例都应该打印整个板以及它是否赢得数独。
int x = 0;
int[][] sudoku = new int[9][9];
while((str=br.readLine())!=null){
printSudoku(str);
for (int y=0;y<9;y++) {
sudoku[x][y] = Character.getNumericValue(str.charAt(x*9+y));
}
x++;
}
After this, the sudoku
variable will contain the sudoku (assuming your text file contains 9 lines of 9 numbers with no spaces or other text in it).在此之后, sudoku
变量将包含数独(假设您的文本文件包含 9 行 9 个数字,其中没有空格或其他文本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.