示例#1
0
def search(knapsack: Knapsack, max_nb_eval: int) -> Tuple[float, int]:
    base_solution = random_solution(knapsack)
    base_score = knapsack.evaluate(base_solution)
    nb_eval = 1
    voisins_possibles = list(range(knapsack.items))

    while True:
        shuffle(voisins_possibles)
        current_score = base_score
        index_voisin = -1

        while (index_voisin + 1 < len(voisins_possibles)
               and current_score <= base_score and nb_eval <= max_nb_eval):
            index_voisin += 1
            index = voisins_possibles[index_voisin]
            base_solution[index] = not base_solution[index]
            current_score = knapsack.evaluate(base_solution)
            nb_eval += 1
            base_solution[index] = not base_solution[index]

        if current_score > base_score:
            base_score = current_score
            index = voisins_possibles[index_voisin]
            base_solution[index] = not base_solution[index]
        elif index_voisin + 1 == len(voisins_possibles):
            break  # optimum local

        if nb_eval >= max_nb_eval:
            break

    return base_score, nb_eval
示例#2
0
def search(knapsack: Knapsack, max_evals: int) -> Tuple[float, int]:
    """Use the hill climber best improvement to find a solution."""
    base_solution = random_solution(knapsack)
    base_score = knapsack.evaluate(base_solution)
    nb_eval = 1

    while True:
        best_score = -math.inf
        index_solution = -1

        for i in range(knapsack.items):
            base_solution[i] = not base_solution[i]
            score = knapsack.evaluate(base_solution)
            nb_eval += 1

            if score > best_score:
                best_score = score
                index_solution = i

            base_solution[i] = not base_solution[i]

        if nb_eval >= max_evals:
            break

        if best_score > base_score:
            base_solution[index_solution] = not base_solution[index_solution]
            base_score = best_score
        else:
            break  # Optimum local

    return base_score, nb_eval
示例#3
0
 def __init__(self, mu: int, knapsack: Knapsack):
     self.knapsack = knapsack
     parents = [random_solution(knapsack) for i in range(mu)]
     self._population = [
         Individu(parent, knapsack.evaluate(parent)) for parent in parents
     ]
     self.mu = mu