java - Java Sudoku 帮助:如何将我的数独字符串转换为 2d int?
问题描述
我正在编写代码来检查数独板是否是获胜板。我将电路板作为文件读取并存储在字符串中。该字符串是我通过方法读取它,打印它,然后检查板是否是获胜板。如果是或不是,它将打印。我一直在尝试将 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
*/
我将使用 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++;
}
在此之后,sudoku
变量将包含数独(假设您的文本文件包含 9 行,每行 9 个数字,其中没有空格或其他文本)。
推荐阅读
- apache - 如何在 ubuntu 18.04 服务器的 apache2 下使用 SSL 保护 Jenkins 端口 8080?
- r - 在R中按名称简单循环列
- javascript - javascript构建表中的图像和单元格间距
- c++ - 从旋转矩形中检索中心
- windows - 如何获取文件资源管理器窗口的开始时间?
- sublimetext3 - ST3底部的状态栏怎么去掉
- c# - Get first row of an ordered Gtk TreeView(Gtk#)
- python - 我试图将三个不同大小的数组打印到表格中
- html - 如何在类型文本框上方放置文本
- javascript - React 和 Redux 错误 - 第一次使用 Redux