-
Notifications
You must be signed in to change notification settings - Fork 3
/
InsertionMutationManager.cs
42 lines (39 loc) · 1.56 KB
/
InsertionMutationManager.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
using System;
using GeneticAlgorithm.Components.Interfaces;
namespace GeneticAlgorithm.Components.MutationManagers
{
/// <summary>
/// Removes a random genome and inserts it at a new location.
/// InsertionMutationManager guarantees that if the original chromosome contained each genome exactly once, so will the mutated chromosome.
/// </summary>
public class InsertionMutationManager<T> : IMutationManager<T>
{
public T[] Mutate(T[] vector)
{
var toRemove = ProbabilityUtils.GetRandomInt(vector.Length);
var insertAt = ProbabilityUtils.GetRandomInt(vector.Length);
var newVector = new T[vector.Length];
if (toRemove < insertAt)
{
for (int i = 0; i < toRemove; i++)
newVector[i] = vector[i];
for (int i = toRemove; i < insertAt; i++)
newVector[i] = vector[i + 1];
newVector[insertAt] = vector[toRemove];
for (int i = insertAt + 1; i < vector.Length; i++)
newVector[i] = vector[i];
}
else
{
for (int i = 0; i < insertAt; i++)
newVector[i] = vector[i];
newVector[insertAt] = vector[toRemove];
for (int i = insertAt + 1; i <= toRemove; i++)
newVector[i] = vector[i - 1];
for (int i = toRemove + 1; i < vector.Length; i++)
newVector[i] = vector[i];
}
return newVector;
}
}
}