Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

linux - Bash simplified sudoku

So,I have to write a bash script to check if a 9x9 "sudoku" solution is valid,but the simplification is that I don't have to divide it into 3x3,but just check if rows and columns contain any duplicate numbers,and valid numbers are only 1-9..

this is what I had in mind,but couldn't get it working:

    #!/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 "" '{ 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$ 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...