Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Bulls and Cows by Kurush
# migrated from python 2.7
# For move calculation I have modeled bulls and cows as a game with two players.
# One of them try to guess the combination, the other one is cheating by always
# changing the guessed combination. In this case game can be solved with MinMax approach.
# There are a lot of combinations here. So MinMax works with one-move depth.
# Possible moves are stored in global variable moves in order to prevent repeating calculations.
import itertools
moves = []
def checkio(data):
global moves
if data == []:
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
moves = list(itertools.permutations(digits, 4))
return "0123" # fixed first move to decrease number of possible moves
else:
moves = decrease_moves(moves, int(data[len(data) - 1][5]), int(data[len(data) - 1][7]), data[len(data) - 1][0:4])
guesses = moves
for move in moves:
min = 5040
min_move = "0123"
results = dict()
for guess in guesses:
bulls, cows = get_bulls_cows(move, guess)
if ((bulls, cows) not in results):
results[(bulls, cows)] = 0
results[(bulls, cows)] += 1
max_vars = max([value for key, value in results.items()])
if max_vars < min:
min = max_vars
min_move = move
return "".join(move)
def decrease_moves(moves, bulls, cows, guess):
new_moves = []
for move in moves:
m_bulls, m_cows = get_bulls_cows(move, guess)
if (m_bulls == bulls) and (m_cows == cows):
new_moves.append(move)
return new_moves
def get_bulls_cows(trial, goal):
bulls = cows = 0
for u, g in zip(trial, goal):
if u == g:
bulls += 1
elif u in goal:
cows += 1
return bulls, cows
if __name__ == '__main__':
#This part is using only for self-checking and not necessary for auto-testing
def check_solution(func, goal):
recent = []
for step in range(8):
user_result = func(recent)
bulls = cows = 0
for u, g in zip(user_result, goal):
if u == g:
bulls += 1
elif u in goal:
cows += 1
recent.append("{0} {1}B{2}C".format(user_result, bulls, cows))
if bulls == 4:
print(("{0} Win with {1} steps.".format(goal, step + 1)))
return True
print(("{0} Fail.".format(goal)))
return False
assert check_solution(checkio, "1234"), "1234"
assert check_solution(checkio, "6130"), "6130"
assert check_solution(checkio, "0317"), "0317"
assert check_solution(checkio, "9876"), "9876"
June 16, 2014