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.math.genetics;
18  
19  import static org.junit.Assert.*;
20  import org.junit.Test;
21  
22  public class OnePointCrossoverTest {
23  
24      @Test
25      public void testCrossover() {
26          Integer[] p1 = new Integer[] {1,0,1,0,0,1,0,1,1};
27          Integer[] p2 = new Integer[] {0,1,1,0,1,0,1,1,1};
28          
29          BinaryChromosome p1c = new DummyBinaryChromosome(p1);
30          BinaryChromosome p2c = new DummyBinaryChromosome(p2);
31          
32          OnePointCrossover<Integer> opc = new OnePointCrossover<Integer>();
33          
34          // how to test a stochastic method?
35          for (int i=0; i<20; i++) {
36              ChromosomePair pair = opc.crossover(p1c,p2c);
37              
38              Integer[] c1 = new Integer[p1.length];
39              Integer[] c2 = new Integer[p2.length];
40              
41              c1 = ((BinaryChromosome) pair.getFirst()).getRepresentation().toArray(c1);
42              c2 = ((BinaryChromosome) pair.getSecond()).getRepresentation().toArray(c2);
43              
44              // first and last values will be the same
45              assertEquals((int) p1[0], (int) c1[0]);
46              assertEquals((int) p2[0], (int) c2[0]);
47              assertEquals((int) p1[p1.length-1], (int) c1[c1.length-1]);
48              assertEquals((int) p2[p2.length-1], (int) c2[c2.length-1]);
49              // moreover, in the above setting, the 2nd, 3rd and 7th values will be the same
50              assertEquals((int) p1[2], (int) c1[2]);
51              assertEquals((int) p2[2], (int) c2[2]);
52              assertEquals((int) p1[3], (int) c1[3]);
53              assertEquals((int) p2[3], (int) c2[3]);
54              assertEquals((int) p1[7], (int) c1[7]);
55              assertEquals((int) p2[7], (int) c2[7]);
56          }
57      }
58  
59  }