打印一个简单的数独板阵列



所以我的代码当前缺少数组的第 8 个索引并将其向下推 1 行。我是 kotlin 的新手,但老实说,我不知道它为什么要这样做。

fun main() {
val board = arrayOf(
arrayOf(7, 8, 0, 4, 0, 0, 1, 2, 0),
arrayOf(6, 0, 0, 0, 7, 5, 0, 0, 9),
arrayOf(0, 0, 0, 6, 0, 1, 0, 7, 8),
arrayOf(0, 0, 7, 0, 4, 0, 2, 6, 0),
arrayOf(0, 0, 1, 0, 5, 0, 9, 3, 0),
arrayOf(9, 0, 4, 0, 6, 0, 0, 0, 5),
arrayOf(0, 7, 0, 3, 0, 0, 0, 1, 2),
arrayOf(1, 2, 0, 0, 0, 7, 4, 0, 0),
arrayOf(0, 4, 9, 2, 0, 6, 0, 0, 7)
)
for (row in 0 until board.size) {
if(row % 3 == 0 && row != 0) {
println(" - - - - - - - - - " )
}
for(col in 0 until board.size) {
if(col == 8){
println(" ")
}
if(col % 3 == 0 && col != 0) {
print(" |")
}
print(" ")
print(board[row][col])
}
}
}

输出为

7 8 0 | 4 0 0 | 1 2 
0 6 0 0 | 0 7 5 | 0 0 
9 0 0 0 | 6 0 1 | 0 7 
8 - - - - - - - - - 
0 0 7 | 0 4 0 | 2 6 
0 0 0 1 | 0 5 0 | 9 3 
0 9 0 4 | 0 6 0 | 0 0 
5 - - - - - - - - - 
0 7 0 | 3 0 0 | 0 1 
2 1 2 0 | 0 0 7 | 4 0 
0 0 4 9 | 2 0 6 | 0 0 
7

你在内部 for 循环中添加了一条新行,这实际上是在它之后需要的。我修改了您的代码,如下所示:

for (row in 0 until board.size) {
if(row % 3 == 0 && row != 0) {
println(" - - - - - - - - - " )
}
for(col in 0 until board.size) {
if(col % 3 == 0 && col != 0) {
print(" |")
}
print(" " +board[row][col])
}
println()
}

根据您的要求,这可以完美地工作(因为您希望前后都有尾随空格(

法典:

val board = arrayOf(
arrayOf(7, 8, 0, 4, 0, 0, 1, 2, 0),
arrayOf(6, 0, 0, 0, 7, 5, 0, 0, 9),
arrayOf(0, 0, 0, 6, 0, 1, 0, 7, 8),
arrayOf(0, 0, 7, 0, 4, 0, 2, 6, 0),
arrayOf(0, 0, 1, 0, 5, 0, 9, 3, 0),
arrayOf(9, 0, 4, 0, 6, 0, 0, 0, 5),
arrayOf(0, 7, 0, 3, 0, 0, 0, 1, 2),
arrayOf(1, 2, 0, 0, 0, 7, 4, 0, 0),
arrayOf(0, 4, 9, 2, 0, 6, 0, 0, 7)
)
for (row in board.indices) {
if (row % 3 == 0 && row != 0) {
println(" - - - - - - - - - - - ")
}
for (col in board.indices) {
if (col % 3 == 0 && col != 0) {
print(" |")
}
print(" " + board[row][col])
}
println()
}

结果:

7 8 0 | 4 0 0 | 1 2 0 
6 0 0 | 0 7 5 | 0 0 9 
0 0 0 | 6 0 1 | 0 7 8 
- - - - - - - - - - - 
0 0 7 | 0 4 0 | 2 6 0 
0 0 1 | 0 5 0 | 9 3 0 
9 0 4 | 0 6 0 | 0 0 5 
- - - - - - - - - - - 
0 7 0 | 3 0 0 | 0 1 2 
1 2 0 | 0 0 7 | 4 0 0 
0 4 9 | 2 0 6 | 0 0 7 

编辑:<>.indices只是0 until <>.size的简短扩展

相关内容

  • 没有找到相关文章

最新更新