cargo.exs (1125B)
1 defmodule Cargo do 2 alias Types.Chromosome 3 @behaviour Problem 4 5 @impl true 6 def genotype do 7 genes = Enum.map(1..10, fn _ -> Enum.random(0..1) end) 8 %Chromosome{genes: genes, size: 10} 9 end 10 11 @impl true 12 def fitness_function(chromosome) do 13 profits = [6, 5, 8, 9, 6, 7, 3, 1, 2, 6] 14 weights = [10, 6, 8, 7, 10, 9, 7, 11, 6, 8] 15 weight_limit = 40 16 17 potential_profits = 18 profits 19 |> Enum.zip(chromosome.genes) 20 |> Enum.map(fn {p, g} -> p * g end) 21 |> Enum.sum() 22 23 over_limit? = 24 weights 25 |> Enum.zip(chromosome.genes) 26 |> Enum.map(fn {w, g} -> w * g end) 27 |> Enum.sum() 28 |> Kernel.>(weight_limit) 29 30 profits = if over_limit?, do: 0, else: potential_profits 31 profits 32 end 33 34 @impl true 35 def terminate?(_population, generation) do 36 generation == 100 37 end 38 end 39 40 {soln, _} = Genetic.run(Cargo, crossover_type: &Toolbox.Crossover.single_point/3) 41 IO.puts("\nsolution: #{inspect(soln.genes)}") 42 43 weight = 44 soln.genes 45 |> Enum.zip([10, 6, 8, 7, 10, 9, 7, 11, 6, 8]) 46 |> Enum.map(fn {g, w} -> g * w end) 47 |> Enum.sum() 48 49 IO.puts("weight: #{weight}")