Exemple #1
0
    def crossover(self, state1, state2):
        cut_point = randint(0, itemSize - 1)
        child = state1[:cut_point] + state2[cut_point:]
        return child

    def mutate(self, state):
        mutation = choice('01')
        mutation_point = randint(0, itemSize - 1)
        mutated = ''.join([
            state[i] if i != mutation_point else mutation
            for i in range(len(state))
        ])
        return mutated


problem = knapsack(initial_state='0101')
result = genetic(problem, mutation_chance=0.1, viewer=WebViewer())
print(result.state)
print(result.path())
'''
problem = knapsack(initial_state='0101')
result = hill_climbing(problem, viewer=ConsoleViewer())
print(result.state)
print(result.path())
'''
'''
problem = knapsack(initial_state='0101')
result = hill_climbing_random_restarts(problem, viewer=ConsoleViewer())
print(result.state)
print(result.path())
'''
Exemple #2
0
        attacks = 0

        for queen_col, queen_row in enumerate(state):
            for queen2_col, queen2_row in enumerate(state):
                if queen_col < queen2_col:
                    # no son la misma reina, chequeemos ataques
                    if queen_row == queen2_row:
                        # están en la misma fila
                        attacks += 1
                    else:
                        # están en la misma diagonal?
                        cols_diff = abs(queen_col - queen2_col)
                        rows_diff = abs(queen_row - queen2_row)

                        if cols_diff == rows_diff:
                            # están en la misma diagonal
                            attacks += 1

        return -attacks


problem = GeneticQueensProblem(None)

result = genetic(problem,
                 population_size=150,
                 mutation_chance=0.1,
                 iterations_limit=100)

print(result.state)
print("Attacks:", -problem.value(result.state))
Exemple #3
0
	def value(self, s):
		v = 0
		for index, item in enumerate(s):
			if item == 1:
				v += self.values[index]
		return v


	def _weight(self, s):
		weight = 0
		for index, item in enumerate(s):
			if item == 1:
				weight += self.weights[index]
		return weight

	def _valid(self, s):
		if self._weight(s) > maxWeight:
			return False
		return True

if __name__ == "__main__":
	numObjects = 20
	weights = [4, 6, 5, 5, 3, 2, 4, 8, 1, 5, 3, 7, 2, 5, 6, 3, 8, 4, 7, 2]
	values = [5, 6, 2, 8, 6, 5, 8, 2, 7, 6, 1, 3, 4, 4, 1, 5, 6, 2, 5, 3]
	maxWeight = 35
	problem = KnapsackProblem(numObjects, maxWeight, weights, values)
	result = genetic(problem, iterations_limit=100, population_size=16, mutation_chance=0.10)
	print result.path()
	print 'Weight = ' + str(problem._weight(result.path()[0][1]))
	print 'Value = ' + str(problem.value(result.path()[0][1]))