def setUp(self): p1 = Board("222222") p2 = Board("555555") p3 = Board("222222") p4 = Board("555555") self.short_list = [p1, p2] self.long_list = [p1, p2, p3, p4]
def make_babies(p1, p2, pivot): k1_state = p1[0:pivot] + p2[pivot:] k2_state = p2[0:pivot] + p1[pivot:] k1_state = mutate(k1_state) k2_state = mutate(k2_state) k1 = Board(k1_state) k2 = Board(k2_state) return k1, k2
def get_rankings(population): """ Takes a population and ranks it from the most eligible parents to the least """ total_attacking_pairs = sum(map(lambda x: x.fitness_function(), population)) for board in population: board.set_eligibility(board.fitness_function() / total_attacking_pairs) return Board.rank_pop(population)
def find_solution(): attempt = 0 population = gen_population() stats = Stats(board_size, Board.max_attacking_pairs(board_size)) while attempt < attempts: rankings = get_rankings(population) parents = get_parents(rankings, population) population = breed(parents) stats.record(population) attempt += 1 print("ran %s attempts, now exiting" % attempt)
def generate_board(length): s = "" for _ in range(length): s += str(random.randint(0, length - 1)) return Board(s)
def test_consistency_check(self): with self.assertRaises(ValueError): Board("0126") # row index is higher than is possible for a 4x4 board with self.assertRaises(ValueError): Board("012") # No solution for N-Queens len() < 4
def test_sorting_by_eligibility(self): a = Board("0213") b = Board("3120") c = Board("0101") a.set_eligibility(0.2) b.set_eligibility(0.7) c.set_eligibility(0.1) pop = [a, b, c] print(pop) Board.rank_pop(pop) print(pop) self.assertIs(pop[0], b) self.assertIs(pop[1], a) self.assertIs(pop[2], c)
def test_fitness_function(self): self.assertEqual(4, Board("0213").fitness_function())
def test_calc_max_attacking_pairs(self): self.assertEqual(28, Board.max_attacking_pairs(8)) self.assertEqual(15, Board.max_attacking_pairs(6)) self.assertEqual(120, Board.max_attacking_pairs(16))
def test_count_attacking_pairs(self): self.assertEqual(2, Board("0213").count_attacking_pairs()) self.assertEqual(2, Board("3120").count_attacking_pairs()) self.assertEqual(4, Board("01143").count_attacking_pairs()) self.assertEqual(4, Board("02143").count_attacking_pairs())