linux – Bash简化数独
作者:互联网
因此,我必须编写一个bash脚本来检查9×9“sudoku”解决方案是否有效,但简化的是我不必将其划分为3×3,而只是检查行和列是否包含任何重复的数字,以及有效数字仅为1-9 ..
这是我的想法,但无法让它工作:
#!/bin/bash
error="false"
count=0
#this would be for columns
#for i in 1 2 3 4 5 6 7 8 9
#do
#cat sudoku.txt | awk -F "\t" '{ print $'$i'}' | uniq -c | awk '$1 > 1 { count++ } END { print count }'
#done
#and this would be for rows
for i in 1 2 3 4 5 6 7 8 9
do
cat sudoku.txt | awk '{ print FNR=$'$i'}' | uniq -c |
awk '$1 > 1 { count++ } END { print count }' |
awk ' count > 0 { $error="true" } END { print $i }' |
awk '{ if ($error = "true") print "Wrong data!"; else print "Correct data!"; } '
done
解决方法:
$awk '
function check(num) {
return num != 45 ? 1 : 0;
}
{
row = 0;
for (i = 1; i <= 9; i++) {
row += $i;
col[i] += $i;
}
if (check(row) > 0) {
errors[++error_len] = sprintf("error in line %s: %s", FNR, $0);
}
}
END {
for (i = 1; i <= 9; i++) {
if (check(row) > 0) {
errors[++error_len] = sprintf("error in column %s: %s", i, col[i]);
}
}
if (error_len) {
for (i = 0; i <= error_len; i++) {
print(errors[i]);
}
}
else {
print("all good");
}
}
' sudoku
error in line 4: 6 7 1 4 8 2 6 9 3
$cat sudoku
8 1 2 9 7 4 3 6 5
9 3 4 6 5 1 7 8 2
7 6 5 8 2 3 9 4 1
6 7 1 4 8 2 6 9 3 <-- see the 6 here thats an error:
2 8 9 3 6 5 4 1 7
6 4 3 7 1 9 2 5 8
1 9 6 5 3 7 8 2 4
3 2 8 1 4 6 5 7 9
4 5 7 2 9 8 1 3 6
标签:sudoku,bash,linux,shell,awk 来源: https://codeday.me/bug/20191002/1842980.html