Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2806

Bulls and Cowsをシェルプログラムで作成してみた

$
0
0

はじめに

Bashプログラミングの小ネタとして作成しました。
第6弾です。今回はなかなか手強かったです。

Bulls and Cowsとは

Bulls and Cowsに関してはWikipediaこちらをご確認ください。

もともとは文字列当てゲームですが、
今回は数字当てゲームとして作成してみます。

ソース

#!/bin/bashfunction chkAns {bull=0
  cow=0
  num=$1dig=$2ans=$3for i in$(seq 1 $dig)do
    for j in$(seq 1 $dig)do
      if[[${num:i:1}==${ans:j:1}&&$i==$j]]then#       echo bull: $bull        #for debug(( bull = bull + 1 ))elif[[${num:i:1}==${ans:j:1}&&$i!=$j]]then#       echo cow: $cow          #for debug(( cow = cow + 1 ))fi
    done
  done

  if(( bull == dig ))then
    echo-e"$dig bulls ! You did it !"exit
  else
    echo-e"$bull bull and $cow cow."fi}echo"Welcome 'Bulls and Cows' Game"echo-e"Please input digits of numbers => \c"read digits

tmp=$(shuf-i 0-9 -n$digits-z)answer=${tmp:0:3}#echo $answer  #for debugfor k in$(seq 1 10)do
  echo-e"Input $digits numbers of your answer. (${k} time) => \c"read num

  chkAns $num$digits$answerif(($k== 10 ))then
    echo"You failed 10 times..."fi
done

echo-e"The answer is '$answer'"

$RANDOMでも良かったですが、信用してないので採用しませんでした。
代わりに、shufコマンドを使いました。

実行結果(正解する)

$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh: 行 39: 警告: command substitution: ignored null byte in input
Input 3 numbers of your answer. (1 time)=> 321
2 bull and 0 cow.
Input 3 numbers of your answer. (2 time)=> 324
2 bull and 0 cow.
Input 3 numbers of your answer. (3 time)=> 325
3 bulls ! You did it !

「警告: command substitution: ignored null byte in input」のメッセージは、ヌルバイトが含まれていると出るようです。
ただ、Nullを使わないとN桁の生成が難しかったので無視しています。
良い対処方法があればコメントください。

実行結果(失敗する)

真面目に正解しようとしています。

$ ./bulls_and_cows.sh
Welcome 'Bulls and Cows' Game
Please input digits of numbers => 3
./bulls_and_cows.sh: 行 39: 警告: command substitution: ignored null byte in input
Input 3 numbers of your answer. (1 time)=> 345
1 bull and 0 cow.
Input 3 numbers of your answer. (2 time)=> 219
1 bull and 0 cow.
Input 3 numbers of your answer. (3 time)=> 398
1 bull and 0 cow.
Input 3 numbers of your answer. (4 time)=> 470
1 bull and 1 cow.
Input 3 numbers of your answer. (5 time)=> 709
1 bull and 0 cow.
Input 3 numbers of your answer. (6 time)=> 507
2 bull and 0 cow.
Input 3 numbers of your answer. (7 time)=> 504
1 bull and 0 cow.
Input 3 numbers of your answer. (8 time)=> 570
1 bull and 1 cow.
Input 3 numbers of your answer. (9 time)=> 407
2 bull and 0 cow.
Input 3 numbers of your answer. (10 time)=> 307
2 bull and 0 cow.
You failed 10 times...
The answer is '567'

おわりに

このプログラムを作成することで

  • 変数
  • 変数の操作
  • 条件式
  • 繰り返し構文
  • 関数
  • readコマンド
  • shuf(シャッフル)コマンド

が理解できました。


Viewing all articles
Browse latest Browse all 2806

Trending Articles