我必须编写一个脚本,它获取一个文本文件,其中包含 9 行和行中的 9 个数字(1-9)。
例如:
123456789
234567891
345678912
456789123
567891234
678912345
789123456
891234567
912345678
我必须根据数独规则检查行和行。
一行或一行中不能有相同的数字。
所以这个例子是一个正确的解决方案。
如何在bash shell脚本中编写它?
我无法使用数组,那么我该怎么办?
一个没有 awk 的解决方案,结合了不同的其他工具。
编辑:此解决方案适用于称为输入的输入文件和数字之间的空格。请参阅有关更改此行为的评论。
echo "Checking 9 lines"
if [ $(wc -l <input ) -ne 9 ]; then
echo "Wrong number of lines"
exit 1
fi
echo "Check for correct layout"
if [ $(grep -cv '^[1-9] [1-9] [1-9] [1-9] [1-9] [1-9] [1-9] [1-9] [1-9]$' input ) -ne 0 ]; then
echo "Not all lines are correct, maybe spaces at the end of a line?"
grep -v '^[1-9] [1-9] [1-9] [1-9] [1-9] [1-9] [1-9] [1-9] [1-9]$' input
exit 1
fi
i=0
while read -r line; do
((i++))
if [ $(echo "${line}" | tr " " "\n" | sort -u | wc -l ) -ne 9 ]; then
echo "Wrong nr of unique numbers in row $i"
fi
done <input
for j in {1..9}; do
if [ $(cut -d" " -f${j} input | sort -u | wc -l ) -ne 9 ]; then
echo "Wrong nr of unique numbers in column $j"
fi
done
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)