1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math4.legacy.genetics;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
23
24
25
26
27
28
29
30 public abstract class BinaryChromosome extends AbstractListChromosome<Integer> {
31
32
33
34
35
36
37 public BinaryChromosome(List<Integer> representation) throws InvalidRepresentationException {
38 super(representation);
39 }
40
41
42
43
44
45
46 public BinaryChromosome(Integer[] representation) throws InvalidRepresentationException {
47 super(representation);
48 }
49
50
51
52
53 @Override
54 protected void checkValidity(List<Integer> chromosomeRepresentation) throws InvalidRepresentationException {
55 for (int i : chromosomeRepresentation) {
56 if (i < 0 || i >1) {
57 throw new InvalidRepresentationException(LocalizedFormats.INVALID_BINARY_DIGIT,
58 i);
59 }
60 }
61 }
62
63
64
65
66
67
68 public static List<Integer> randomBinaryRepresentation(int length) {
69
70 List<Integer> rList= new ArrayList<> (length);
71 for (int j=0; j<length; j++) {
72 rList.add(GeneticAlgorithm.getRandomGenerator().nextInt(2));
73 }
74 return rList;
75 }
76
77
78 @Override
79 protected boolean isSame(Chromosome another) {
80
81 if (! (another instanceof BinaryChromosome)) {
82 return false;
83 }
84 BinaryChromosome anotherBc = (BinaryChromosome) another;
85
86 if (getLength() != anotherBc.getLength()) {
87 return false;
88 }
89
90 for (int i=0; i< getRepresentation().size(); i++) {
91 if (!(getRepresentation().get(i).equals(anotherBc.getRepresentation().get(i)))) {
92 return false;
93 }
94 }
95
96 return true;
97 }
98 }