-
-
Notifications
You must be signed in to change notification settings - Fork 334
/
IntegerChromosome.cs
90 lines (78 loc) · 2.97 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections;
using System.Linq;
namespace GeneticSharp
{
/// <summary>
/// Integer chromosome with binary values (0 and 1).
/// </summary>
public class IntegerChromosome : BinaryChromosomeBase
{
private readonly int m_minValue;
private readonly int m_maxValue;
private readonly 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();
}
/// <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);
}
/// <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];
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:GeneticSharp.Domain.Chromosomes.FloatingPointChromosome"/>.
/// </summary>
/// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:GeneticSharp.Domain.Chromosomes.FloatingPointChromosome"/>.</returns>
public override string ToString()
{
return String.Join("", GetGenes().Reverse().Select(g => (bool) g.Value ? "1" : "0").ToArray());
}
/// <summary>
/// Flips the gene.
/// </summary>
/// <remarks>>
/// If gene's value is 0, the it will be flip to 1 and vice-versa.</remarks>
/// <param name="index">The gene index.</param>
public override void FlipGene(int index)
{
var realIndex = Math.Abs(31 - index);
var value = (bool)GetGene(realIndex).Value;
ReplaceGene(realIndex, new Gene(!value));
}
}
}