-
-
Notifications
You must be signed in to change notification settings - Fork 334
/
FlipBitMutation.cs
52 lines (46 loc) · 1.62 KB
/
FlipBitMutation.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
using System.ComponentModel;
namespace GeneticSharp
{
/// <summary>
/// Takes the chosen genome and inverts the bits (i.e. if the genome bit is 1, it is changed to 0 and vice versa).
/// </summary>
/// <remarks>
/// When using this mutation the genetic algorithm should use IBinaryChromosome.
/// </remarks>
[DisplayName("Flip Bit")]
public class FlipBitMutation : MutationBase
{
#region Fields
private readonly IRandomization m_rnd;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="GeneticSharp.FlipBitMutation"/> class.
/// </summary>
public FlipBitMutation ()
{
m_rnd = RandomizationProvider.Current;
}
#endregion
#region Methods
/// <summary>
/// Mutate the specified chromosome.
/// </summary>
/// <param name="chromosome">The chromosome.</param>
/// <param name="probability">The probability to mutate each chromosome.</param>
protected override void PerformMutate (IChromosome chromosome, float probability)
{
var binaryChromosome = chromosome as IBinaryChromosome;
if (binaryChromosome == null)
{
throw new MutationException (this, "Needs a binary chromosome that implements IBinaryChromosome.");
}
if (m_rnd.GetDouble() <= probability)
{
var index = m_rnd.GetInt(0, chromosome.Length);
binaryChromosome.FlipGene (index);
}
}
#endregion
}
}