forked from giacomelli/GeneticSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntegerChromosome.cs
70 lines (60 loc) · 1.76 KB
/
IntegerChromosome.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
using GeneticSharp.Domain.Randomizations;
using System.Collections;
using System.Linq;
namespace GeneticSharp.Domain.Chromosomes
{
/// <summary>
/// Integer chromosome with binary values (0 and 1).
/// </summary>
public class IntegerChromosome : BinaryChromosomeBase
{
private int m_minValue;
private int m_maxValue;
private BitArray m_originalValue;
/// <summary>
/// Initializes a new instance of the <see cref="T:GeneticSharp.Domain.Chromosomes.IntegerChromosome"/> class.
/// </summary>
/// <param name="minValue">Minimum value.</param>
/// <param name="maxValue">Maximum value.</param>
public IntegerChromosome(int minValue, int maxValue) : base(32)
{
m_minValue = minValue;
m_maxValue = maxValue;
var intValue = RandomizationProvider.Current.GetInt(m_minValue, m_maxValue);
m_originalValue = new BitArray(new int[] { intValue });
CreateGenes();
}
#region implemented abstract members of ChromosomeBase
/// <summary>
/// Generates the gene.
/// </summary>
/// <returns>The gene.</returns>
/// <param name="geneIndex">Gene index.</param>
public override Gene GenerateGene(int geneIndex)
{
var value = m_originalValue[geneIndex];
return new Gene(value);
}
/// <summary>
/// Creates the new.
/// </summary>
/// <returns>The new.</returns>
public override IChromosome CreateNew()
{
return new IntegerChromosome(m_minValue, m_maxValue);
}
#endregion
/// <summary>
/// Converts the chromosome to its integer representation.
/// </summary>
/// <returns>The integer.</returns>
public int ToInteger()
{
var array = new int[1];
var genes = GetGenes().Select(g => (bool)g.Value).ToArray();
var bitArray = new BitArray(genes);
bitArray.CopyTo(array, 0);
return array[0];
}
}
}