Skip to content

Instantly share code, notes, and snippets.

@tavimori
Last active January 14, 2019 13:25
Show Gist options
  • Save tavimori/a1afa96c50551941c97b0a49564a93c2 to your computer and use it in GitHub Desktop.
Save tavimori/a1afa96c50551941c97b0a49564a93c2 to your computer and use it in GitHub Desktop.
A faster way for CSC1002
import math
import itertools
possible_set = set()
def check_match(guess, target):
count_exact = 0
count_guess = 0
for i in range(4):
if guess[i] == target[i]:
count_exact += 1
for j in range(4):
if guess[i] == target[j]:
count_guess += 1
return count_guess, count_exact
def update_possible_set(guess, count_guess, count_exact):
global possible_set
next_round_set = set()
for i in possible_set:
if check_match(guess, i) == (count_guess, count_exact):
next_round_set.add(i)
possible_set = next_round_set
def init_set():
for i in itertools.permutations(range(10), 4):
if i[0] == 0:
continue
possible_set.add(i)
def calc_entropy(guess_int):
count = [0] * 25
guess = tuple(map(int, str(guess_int)))
for i in possible_set:
count_guess, count_exact = check_match(guess, i)
count[count_guess * 4 + count_exact] += 1
entropy = 0
for i in count:
if i != 0:
p = i / len(possible_set)
entropy += -math.log(p, 2) * p
return entropy
def gen_guess():
max = 0
best_guess = 0
for i in range(1000, 10000):
if (len(set(list(str(i)))) == 4):
entropy = calc_entropy(i)
if entropy > max:
max = entropy
best_guess = i
return best_guess
def main():
init_set()
print("please think of a number")
guess = (1, 2, 3, 4)
count_global = 0
while len(possible_set) > 1:
# guess = tuple(map(int ,str(input("guess what"))))
count_global += 1
# print(len(possible_set))
print("I guess " + str(guess) + " (" + str(count_global) + " times")
count_guess = int(input("count_guess"))
count_exact = int(input("count_exact"))
update_possible_set(guess, count_guess, count_exact)
guess = tuple(map(int, str(gen_guess())))
# print("poss" + str(len(possible_set)))
# print(gen_guess())
print("I think it should be " + str(possible_set))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment