-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenome.cs
138 lines (120 loc) · 3.37 KB
/
Genome.cs
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
using System;
using System.Collections;
using System.Collections.Generic;
namespace WindowsFormsApplication5
{
public class Genome
{
public Genome()
{
}
public Genome(int length)
{
m_length = length;
m_genes = new double[length];
CreateGenes();
}
public Genome(int length, bool createGenes)
{
m_length = length;
m_genes = new double[length];
if (createGenes)
CreateGenes();
}
public Genome(ref double[] genes)
{
m_length = genes.Length;
m_genes = new double[m_length];
Array.Copy(genes, m_genes, m_length);
}
public Genome DeepCopy()
{
Genome g = new Genome(m_length, false);
Array.Copy(m_genes, g.m_genes, m_length);
return g;
}
private void CreateGenes()
{
for (int i = 0; i < m_genes.Length; i++)
m_genes[i] = m_random.NextDouble();
}
public void Crossover(ref Genome genome2, out Genome child1, out Genome child2)
{
int pos = (int)(m_random.NextDouble() * (double)m_length);
child1 = new Genome(m_length, false);
child2 = new Genome(m_length, false);
for (int i = 0; i < m_length; i++)
{
if (i < pos)
{
child1.m_genes[i] = m_genes[i];
child2.m_genes[i] = genome2.m_genes[i];
}
else
{
child1.m_genes[i] = genome2.m_genes[i];
child2.m_genes[i] = m_genes[i];
}
}
}
public void Mutate()
{
for (int pos = 0; pos < m_length; pos++)
{
if (m_random.NextDouble() < m_mutationRate)
m_genes[pos] = (m_genes[pos] + m_random.NextDouble()) / 2.0;
}
}
public double[] Genes()
{
return m_genes;
}
public void Output()
{
foreach (double valeur in m_genes)
{
System.Console.WriteLine("{0:F4}", valeur);
}
System.Console.Write("------\n");
}
public void GetValues(ref double[] values)
{
for (int i = 0; i < m_length; i++)
values[i] = m_genes[i];
}
public double[] m_genes;
private int m_length;
private double m_fitness;
static Random m_random = new Random();
private static double m_mutationRate;
public double Fitness
{
get
{
return m_fitness;
}
set
{
m_fitness = value;
}
}
public static double MutationRate
{
get
{
return m_mutationRate;
}
set
{
m_mutationRate = value;
}
}
public int Length
{
get
{
return m_length;
}
}
}
}