LoginSignup
0
0

More than 1 year has passed since last update.

カスタム桁数(10まで)のhit&blowをpythonでやる

Last updated at Posted at 2022-04-24

hit&blow

hit&blowとは知ってる人も多いと思うが、ランダムに一個数字を選んで言った数字と比較するものである。

例えばランダムな数字が1234だとして1283と言ったら2hit1blowである。(因みに数字がかぶることはない)

つまり位置も数字も同じ場合hitが1増える、数字が同じでも位置が違えばblowが1増えるということだ。
良くあるのは3、4桁だが数字が被らないようにすれば10桁までいけるので作ってみた。(解くのに時間かかりそう)

コード

まずどのようにしてhit,blow数をカウントするかだが、これはまず2つの数字の共通する数字を全て数え出す(言葉で説明するのが難しいが、要は4桁だとしたら4×4の16通りの組み合わせの数字を比べて同じ数字の数を数えるということ)。•••①
そしたら数字が一緒になるときは位置について同じ位置か違う位置かしかないため①の数からhit数を引けば良い。
hit数を数えるのは

for i,n in zip(randomnum,inputnum):
  if i==n:

のように簡単に取得できる。
では作っていく。
ここではリストを使っているが、空文字列に+=していっても良い。

pythonのコード

解説は後ほどする

import random
num="".join(random.sample("1234567890",digit))
#digitは桁数

これでk桁のランダムな被りのない整数を生成する。

hit=[]
overlap=[]
#空のリストを二つ
digit=input()
#ここで桁数を決めます
num="".join(random.sample("0123456789",int(digit)))
m=0
while True:
  dig=input()
  if dig.isdigit():
    if hit!=[]:
      hit=[]#リセット
    if overlap!=[]:
      overlap=[]
    if len(str(dig))!=len(str(num)):
      print("桁数が違います")
    elif len(set(dig))!=len(dig):
      print("重複しています")
    else:
      if str(num)==str(dig):
        print(f"Complete! {int(m)+1}回でした")
        break
      else:
        for n in list(str(dig)):
          for s in list(str(num)):
            if n==s:
              overlap.append(True)
        for a,b in zip(list(str(dig)),list(str(num))):
          if a==b:
            hit.append(True)
        m+=1
        print(f"{len(hit)}hit,{len(overlap)-len(hit)}blow ({m}回目)")
  else:
    if dig=="stop":
      print(num)
      break
    else:
      print("整数です")

解説

hit=[]
overlap=[]
#空のリストを二つ
digit=input()
#ここで桁数を決めます
dig=input()
num=rand(0,9,int(digit))
m=0

hit数を数えるのリストと全部の被りの数を数えるoverlapというリストを作る。
digitで桁数を決める。
digは自分が入力する値。
mは回数を数えるのに使う。

while True:
  dig=input()
  if dig.isdigit():
    if hit!=[]:
      hit=[]#リセット
    if overlap!=[]:
      overlap=[]
    if len(str(dig))!=len(str(num)):
      print("桁数が違います")
    elif len(set(dig))!=len(dig):
      print("重複しています")

ループ処理
リストを空にする。
桁数が違う時や重複している場合は除外する。

    else:
      if str(num)==str(dig):
        print(f"Complete! {int(m)+1}回でした")
        break
      else:
        for n in list(str(dig)):
          for s in list(str(num)):
            if n==s:
              overlap.append(True)
        for a,b in zip(list(str(dig)),list(str(num))):
          if a==b:
            hit.append(True)
        m+=1
        print(f"{len(hit)}hit,{len(overlap)-len(hit)}blow ({m}回目)")

今回の要。
全重複数からhit数を引く。
同じだったらループ抜け。

else:
  if dig=="stop":
    print(num)
    break
  else:
    print("整数です")

stopと入力されたら数を表示して終了。
整数でない場合の処理。

スクリーンショット 2022-04-24 232410.png
こんな感じ。
たまにアルファベット打っても数字として認識されることがあるが、理由はわからない。(多分修正)
まあお遊び程度に。

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0