View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.math4.legacy.genetics;
18  
19  import org.junit.Assert;
20  import org.junit.Test;
21  
22  public class OnePointCrossoverTest {
23  
24      @Test
25      public void testCrossover() {
26          @SuppressWarnings("boxing")
27          Integer[] p1 = new Integer[] {1,0,1,0,0,1,0,1,1};
28          @SuppressWarnings("boxing")
29          Integer[] p2 = new Integer[] {0,1,1,0,1,0,1,1,1};
30  
31          BinaryChromosome p1c = new DummyBinaryChromosome(p1);
32          BinaryChromosome p2c = new DummyBinaryChromosome(p2);
33  
34          OnePointCrossover<Integer> opc = new OnePointCrossover<>();
35  
36          // how to test a stochastic method?
37          for (int i=0; i<20; i++) {
38              ChromosomePair pair = opc.crossover(p1c,p2c);
39  
40              Integer[] c1 = new Integer[p1.length];
41              Integer[] c2 = new Integer[p2.length];
42  
43              c1 = ((BinaryChromosome) pair.getFirst()).getRepresentation().toArray(c1);
44              c2 = ((BinaryChromosome) pair.getSecond()).getRepresentation().toArray(c2);
45  
46              // first and last values will be the same
47              Assert.assertEquals(p1[0],  c1[0]);
48              Assert.assertEquals(p2[0], c2[0]);
49              Assert.assertEquals(p1[p1.length-1], c1[c1.length-1]);
50              Assert.assertEquals(p2[p2.length-1], c2[c2.length-1]);
51              // moreover, in the above setting, the 2nd, 3rd and 7th values will be the same
52              Assert.assertEquals(p1[2], c1[2]);
53              Assert.assertEquals(p2[2], c2[2]);
54              Assert.assertEquals(p1[3], c1[3]);
55              Assert.assertEquals(p2[3], c2[3]);
56              Assert.assertEquals(p1[7], c1[7]);
57              Assert.assertEquals(p2[7], c2[7]);
58          }
59      }
60  }