Skip to content

Instantly share code, notes, and snippets.

@shoffing
Created September 9, 2015 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoffing/99b1b25a0ffaaa297c18 to your computer and use it in GitHub Desktop.
Save shoffing/99b1b25a0ffaaa297c18 to your computer and use it in GitHub Desktop.
17x17 9/9/15
import random
import time
import copy
# Parameters
NUM_COLORS = 4
NUM_ROWS = 17
NUM_COLS = 17
# Generate a random grid of color squares based off the parameters
def generateRandomSolution():
solution = []
for r in range(NUM_ROWS):
row = []
for c in range(NUM_COLS):
row.append(random.randint(0, NUM_COLORS - 1))
solution.append(row)
return solution
# Calculate the number of rectangles in a given potential solution
def calcScore(solution):
numRects = 0
for rowA in range(NUM_ROWS):
for rowB in range(rowA + 1, NUM_ROWS):
for color in range(NUM_COLORS):
numMatches = 0
for col in range(NUM_COLS):
if color == solution[rowA][col] == solution[rowB][col]:
numMatches += 1
numRects += numMatches * (numMatches - 1) / 2
return numRects
# Mutate a solution by the given percentage amount
def mutate(solution, amount):
# Make deep copy
sol = copy.deepcopy(solution)
for i in range(int(amount * NUM_ROWS * NUM_COLS)):
randRow = random.randint(0, NUM_ROWS - 1)
randCol = random.randint(0, NUM_COLS - 1)
sol[randRow][randCol] = random.randint(0, NUM_COLORS - 1)
return sol
# Given two parent solutions a/b and a weight,
# generate a child by taking rows from each parent
def crossover(a, b, weight):
child = []
for r in range(NUM_ROWS):
child.append(a[r] if random.random() > weight else b[r])
return child
###########
# Testing #
###########
# Generate parents
parentA = generateRandomSolution()
parentB = generateRandomSolution()
# Generate child
child = crossover(parentA, parentB, 0.5)
# Mutate child
mutatedChild = mutate(child, 0.25)
# prints a solution
def printSolution(solution):
print "\n".join(["".join([str(cell) for cell in row]) for row in solution])
print "Parent A:"
printSolution(parentA)
print ">> %d rectangles" % calcScore(parentA)
print "\n"
print "Parent B:"
printSolution(parentB)
print ">> %d rectangles" % calcScore(parentB)
print "\n"
print "Child:"
printSolution(child)
print ">> %d rectangles" % calcScore(child)
print "\n"
print "Child mutated 25%:"
printSolution(mutatedChild)
print ">> %d rectangles" % calcScore(mutatedChild)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment