How to solve the “Mastermind” guessing game?

后端 未结 10 447
有刺的猬
有刺的猬 2020-12-04 07:42

How would you create an algorithm to solve the following puzzle, \"Mastermind\"?

Your opponent has chosen four different colours from a set of six (yellow, blue, gre

10条回答
  •  失恋的感觉
    2020-12-04 08:39

    My friend was considering relatively simple case - 8 colors, no repeats, no blanks.

    With no repeats, there's no need for the max entropy consideration, all guesses have the same entropy and first or random guessing all work fine.

    Here's the full code to solve that variant:

    # SET UP
    import random
    import itertools
    colors = ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', 'ultra')
    
    # ONE FUNCTION REQUIRED
    def EvaluateCode(guess, secret_code):
        key = []
        for i in range(0, 4):
            for j in range(0, 4):
                if guess[i] == secret_code[j]:
                    key += ['black'] if i == j else ['white']    
        return key
    
    # MAIN CODE
    # choose secret code
    secret_code = random.sample(colors, 4)
    print ('(shh - secret code is: ', secret_code, ')\n', sep='')
    # create the full list of permutations
    full_code_list = list(itertools.permutations(colors, 4))
    N_guess = 0
    while True:
        N_guess += 1
        print ('Attempt #', N_guess, '\n-----------', sep='')
        # make a random guess
        guess = random.choice(full_code_list)
        print ('guess:', guess)
        # evaluate the guess and get the key
        key = EvaluateCode(guess, secret_code)
        print ('key:', key)
        if key == ['black', 'black', 'black', 'black']:
            break
        # remove codes from the code list that don't match the key
        full_code_list2 = []
        for i in range(0, len(full_code_list)):
            if EvaluateCode(guess, full_code_list[i]) == key:
                full_code_list2 += [full_code_list[i]]
        full_code_list = full_code_list2
        print ('N remaining: ', len(full_code_list), '\n', full_code_list, '\n', sep='')
    print ('\nMATCH after', N_guess, 'guesses\n')
    

提交回复
热议问题