Skip to content

Instantly share code, notes, and snippets.

@leroycep
Created April 16, 2020 15:00
Show Gist options
  • Save leroycep/8a4e9da5bf8beff943b0c28917d894d0 to your computer and use it in GitHub Desktop.
Save leroycep/8a4e9da5bf8beff943b0c28917d894d0 to your computer and use it in GitHub Desktop.
Create a new population with a weighted list of parents
scores = [(0.4, "a"), (0.5, "b"), (0.1, "c")]
# Calculate the sum of all scores.
#
# Will probably be 1 since the bots are scored with a percentage,
# but just in case...
denominator = 0
for score in scores:
denominator += score[0]
new_population = []
POPULATION_SIZE = 100
for i in range(POPULATION_SIZE):
rand_num = random.random() * denominator
# Loop through the scores, seeing which score the random number
# "landed" on.
#
# This could be made (algorithmically) faster by changing the
# scores into a cumulative value, and then doing a binary search
# on it, but I doubt speed will be an issue here.
for score in scores:
if score[0] > rand_num:
new_population.append(score[1])
break
rand_num -= score[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment