Exemplo n.º 1
0
 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]
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
def generate_board(length):
    s = ""
    for _ in range(length):
        s += str(random.randint(0, length - 1))
    return Board(s)
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
 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)
Exemplo n.º 8
0
 def test_fitness_function(self):
     self.assertEqual(4, Board("0213").fitness_function())
Exemplo n.º 9
0
 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))
Exemplo n.º 10
0
 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())