lixiaojun
2022-08-09 c7c696753fbe0b8ebf56eb6cfe584601a36c5fb2
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
using Accord.Genetic;
using System;
 
namespace IStation
{
    public class BinaryChromosomeForPumps : ChromosomeBase
    {
        public const int MaxLength = 64;
 
        protected int length;
 
        protected ulong val;
 
        protected static Random rand = new Random();
 
        public int Length => length;
 
        public ulong Value => val & (ulong.MaxValue >> 64 - length);
 
        public ulong MaxValue => ulong.MaxValue >> 64 - length;
 
        public BinaryChromosomeForPumps(int length)
        {
            this.length = System.Math.Max(2, System.Math.Min(64, length));
            Generate();
        }
 
        protected BinaryChromosomeForPumps(BinaryChromosomeForPumps source)
        {
            length = source.length;
            val = source.val;
            fitness = source.fitness;
        }
 
        public override string ToString()
        {
            ulong num = val;
            char[] array = new char[length];
            for (int num2 = length - 1; num2 >= 0; num2--)
            {
                array[num2] = (char)((num & 1) + 48);
                num >>= 1;
            }
            return new string(array);
        }
 
        public override void Generate()
        {
            byte[] array = new byte[8];
            rand.NextBytes(array);
            val = BitConverter.ToUInt64(array, 0);
        }
 
        public override IChromosome CreateNew()
        {
            return new BinaryChromosomeForPumps(length);
        }
 
        public override IChromosome Clone()
        {
            return new BinaryChromosomeForPumps(this);
        }
 
        public override void Mutate()
        {
            val ^= (ulong)(1L << rand.Next(length));
        }
 
        public override void Crossover(IChromosome pair)
        {
            BinaryChromosomeForPumps binaryChromosome = (BinaryChromosomeForPumps)pair;
            if (binaryChromosome != null && binaryChromosome.length == length)
            {
                int num = 63 - rand.Next(length - 1);
                ulong num2 = ulong.MaxValue >> num;
                ulong num3 = ~num2;
                ulong num4 = val;
                ulong num5 = binaryChromosome.val;
                val = ((num4 & num2) | (num5 & num3));
                binaryChromosome.val = ((num5 & num2) | (num4 & num3));
            }
        }
    }
}