-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenotype.rb
67 lines (57 loc) · 1.79 KB
/
genotype.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'set'
class Genotype
def initialize(permutations, original_matrix)
@permutations = permutations
@fitness_value = calculate_fitness_function(original_matrix)
end
def calculate_fitness_function(original_matrix)
permuted_matrix = create_permuted_matrix(original_matrix)
total = 0
@permutations.size.times do |i|
for j in (i + 1)..@permutations.size - 1
total += permuted_matrix[i][j]
end
end
total
end
def create_permuted_matrix(original_matrix)
permute_columns(permute_rows(original_matrix))
end
def permute_rows(original_matrix)
permuted_matrix = []
@permutations.each do |row|
permuted_matrix << original_matrix[row]
end
permuted_matrix
end
def permutations
@permutations.clone
end
def permute_columns(permuted_matrix)
final_matrix = @permutations.inject([]) { |matrix, _| matrix << [] }
@permutations.each do |col|
@permutations.size.times do |row_index|
final_matrix[row_index] << permuted_matrix[row_index][col]
end
end
final_matrix
end
def fitness_value
@fitness_value
end
def self.select_worst(candidates:)
criteria = Proc.new { |current, candidate| current.fitness_value < candidate.fitness_value ? current : candidate }
self.select(candidates: candidates,
selection_criteria: criteria)
end
def self.select_best(candidates:)
criteria = Proc.new { |current, candidate| current.fitness_value > candidate.fitness_value ? current : candidate }
self.select(candidates: candidates,
selection_criteria: criteria)
end
def self.select(candidates:, selection_criteria:)
candidates.inject(candidates.first) do |current_selected, candidate|
selection_criteria.call current_selected, candidate
end
end
end