Skip to content

Commit

Permalink
Must. Optimize.
Browse files Browse the repository at this point in the history
  • Loading branch information
skytreader committed Mar 11, 2017
1 parent 57ba7cf commit d0f0c45
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions ai/ga/mastermind_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from ai.mastermind import MasterMind
from ai.ga.genetic import GASolver
from errors import UnreachableSolutionException
from .errors import UnreachableSolutionException

import random
import sys
Expand Down Expand Up @@ -34,7 +34,7 @@ def mutate(self, variation):
def compute_fitness(self, variation):
return self.mastermind.rate(variation)

class SmartermindSolver(MasterMindSolver)
class SmartermindSolver(MastermindSolver):
"""
Mastermind solver that "breaks" the conventions of GASolver, in the interest
of being smarter.
Expand All @@ -53,6 +53,7 @@ def __pick_distinct_subset(self, universe, length, autoexclude=None):
Returns a set containing the indices of the chosen subset.
"""
autoexclude = [] if autoexclude is None else autoexclude

if len(autoexclude) >= length:
return set(autoexclude)
Expand All @@ -67,35 +68,36 @@ def __pick_distinct_subset(self, universe, length, autoexclude=None):
distinct_subset = set()

while len(distinct_subset) < length:
item = random.choice(universe)
if item not in distinct_subset:
distinct_subset.add(item)
# Relies on there being no canonical order to sets
distinct_subset.add(choices.pop())

return distinct_subset

def mutate(self, variation):
varclone = [x for x in variation]
variation_decision = self.mastermind.decide(variation)
t_count = sum([1 for d in variation_decision if d])
f_count = sum([1 for d in variation_descision if not d])
f_count = sum([1 for d in variation_decision if not d])

guess_correct = self.__pick_distinct_subset(variation, t_count)
guess_misplaced = self.__pick_distinct_subset(variation, f_count, autoexclude=guess_correct)
untouchables = guess_correct + guess_misplaced
untouchables = set()
untouchables.union(guess_correct)
untouchables.union(guess_misplaced)
varindices = set(range(len(variation)))
replaceables = varindices - untouchables

for misplaced in guess_misplaced:
swap_index = self.__pick_distinct_subset(variation, 1, guess_correct).pop()
varclone[misplaced], varclone[swap_index] = varclone[swap_index], varclone[misplaced]

for replace in replaceables:
varclone[replace] = random.choice(self.mastermind.charset)
return varclone
for replace in replaceables:
varclone[replace] = random.choice(self.mastermind.charset)

return varclone

if __name__ == "__main__":
if len(sys.argv) != 2:
if len(sys.argv) != 3:
print("Usage: python3 -m ai.ga.mastermind_solver (naive|smart) <numslots>")
exit(1)

Expand Down

0 comments on commit d0f0c45

Please sign in to comment.