001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.math.genetics; 018 019 import static org.junit.Assert.*; 020 import org.junit.Test; 021 022 public class OnePointCrossoverTest { 023 024 @Test 025 public void testCrossover() { 026 Integer[] p1 = new Integer[] {1,0,1,0,0,1,0,1,1}; 027 Integer[] p2 = new Integer[] {0,1,1,0,1,0,1,1,1}; 028 029 BinaryChromosome p1c = new DummyBinaryChromosome(p1); 030 BinaryChromosome p2c = new DummyBinaryChromosome(p2); 031 032 OnePointCrossover<Integer> opc = new OnePointCrossover<Integer>(); 033 034 // how to test a stochastic method? 035 for (int i=0; i<20; i++) { 036 ChromosomePair pair = opc.crossover(p1c,p2c); 037 038 Integer[] c1 = new Integer[p1.length]; 039 Integer[] c2 = new Integer[p2.length]; 040 041 c1 = ((BinaryChromosome) pair.getFirst()).getRepresentation().toArray(c1); 042 c2 = ((BinaryChromosome) pair.getSecond()).getRepresentation().toArray(c2); 043 044 // first and last values will be the same 045 assertEquals((int) p1[0], (int) c1[0]); 046 assertEquals((int) p2[0], (int) c2[0]); 047 assertEquals((int) p1[p1.length-1], (int) c1[c1.length-1]); 048 assertEquals((int) p2[p2.length-1], (int) c2[c2.length-1]); 049 // moreover, in the above setting, the 2nd, 3rd and 7th values will be the same 050 assertEquals((int) p1[2], (int) c1[2]); 051 assertEquals((int) p2[2], (int) c2[2]); 052 assertEquals((int) p1[3], (int) c1[3]); 053 assertEquals((int) p2[3], (int) c2[3]); 054 assertEquals((int) p1[7], (int) c1[7]); 055 assertEquals((int) p2[7], (int) c2[7]); 056 } 057 } 058 059 }