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 "\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
It's easy if you transpose the matrix first using awk, then just loop over it the same way you did for the columns.
file: transpose.awk
for a in {1..9}; do var=$(cut -d ' ' -f ${a} sudoku.txt | sort -n | uniq -d); ((${var:-0} > 0)) && echo "Column $a is bad, duplicate ${var}'s."; done
for a in {1..9}; do var=$(transpose.awk sudoku.txt | cut -d ' ' -f ${a} | sort -n | uniq -d); ((${var:-0} > 0)) && echo "Row $a is bad, duplicate ${var}'s."; done
Run on sample file
sudoku.txt
:Column 2 is bad, duplicate 3's.
Column 4 is bad, duplicate 1's.
Column 9 is bad, duplicate 8's.
Row 3 is bad, duplicate 3's.
Row 7 is bad, duplicate 1's.
Row 9 is bad, duplicate 8's.