linux - Bash 简化数独

标签 linux bash shell awk sudoku

所以,我必须编写一个 bash 脚本来检查 9x9 的“数独”解决方案是否有效,但简化是我不必将它分成 3x3,而只需检查行和列是否包含任何重复项数字,有效数字只有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

关于linux - Bash 简化数独,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33585496/

相关文章:

linux - 如何在 Linux 中只为本地用户安装程序?

python - 如何在脚本仍在运行时使 shell 输出重定向 (>) 写入?

linux - Bash 将带引号的行拆分为参数

python - Bash 无法识别 python 命令

linux - Shell:如何检查可用空间并在空间不足时退出?

linux - Perl: Device::USB 没有通过测试

c - 为什么扩展 grep 不起作用?

shell - 通过 shell 运行 hive 命令获取错误

linux - Sqlite:比较两个数据库并更新旧的 - Linux

linux - Telnet 到 localhost 被拒绝,但是通过 IP 可以吗?