Last active
December 10, 2015 02:38
-
-
Save inaz2/4369607 to your computer and use it in GitHub Desktop.
Hit&Blow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inspired from http://blogs.wankuma.com/episteme/archive/2012/12/23/310246.aspx | |
$ python hit_and_blow.py | |
各桁が1~9である3桁の数を入力してほしい。各桁で数が重複するのは避けてくれ | |
987 | |
君が選んだのは 987 だね。では僕がその数を推理しよう。 | |
1回目: 正解となる数の候補は 504 あるが... 427 ではないかな? | |
1Hit / 0Blow | |
2回目: 正解となる数の候補は 90 あるが... 496 ではないかな? | |
0Hit / 1Blow | |
3回目: 正解となる数の候補は 24 あるが... 167 ではないかな? | |
1Hit / 0Blow | |
4回目: 正解となる数の候補は 4 あるが... 937 ではないかな? | |
2Hit / 0Blow | |
5回目: 正解となる数の候補は 2 あるが... 957 ではないかな? | |
2Hit / 0Blow | |
6回目: 正解となる数の候補は 1 あるが... 987 ではないかな? | |
3Hit / 0Blow |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import sys | |
import random | |
class HitAndBlow: | |
def __init__(self, N): | |
self.N = N | |
def gen_candidates(self): | |
digits = '123456789' | |
candidates = list(digits) | |
for i in range(self.N-1): | |
candidates = [x+c for x in candidates for c in digits if not c in x] | |
return candidates | |
def judge(self, actual, guess): | |
(hit, blow) = (0, 0) | |
for i in range(self.N): | |
for j in range(self.N): | |
if actual[i] == guess[j]: | |
if i == j: | |
hit = hit+1 | |
else: | |
blow = blow+1 | |
return (hit, blow) | |
def run(self): | |
candidates = self.gen_candidates() | |
while True: | |
print "各桁が1~9である%d桁の数を入力してほしい。各桁で数が重複するのは避けてくれ" % self.N | |
answer = sys.stdin.readline().strip() | |
if answer in candidates: | |
break | |
print "君が選んだのは %s だね。では僕がその数を推理しよう。" % answer | |
random.shuffle(candidates) | |
trial = 1 | |
while True: | |
print "%d回目: 正解となる数の候補は %d あるが..." % (trial, len(candidates)), | |
candidate = candidates.pop(0) | |
print "%s ではないかな?" % candidate | |
result = self.judge(answer, candidate) | |
print "%dHit / %dBlow" % result | |
if result[0] == self.N: | |
break | |
candidates = filter(lambda x: self.judge(x, candidate) == result, candidates) | |
trial = trial+1 | |
if __name__ == '__main__': | |
HitAndBlow(3).run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment