View Javadoc
1   package net.bmahe.genetics4j.core.combination;
2   
3   import java.util.ArrayList;
4   import java.util.Collections;
5   import java.util.List;
6   
7   import org.apache.commons.lang3.Validate;
8   
9   import net.bmahe.genetics4j.core.Genotype;
10  import net.bmahe.genetics4j.core.chromosomes.Chromosome;
11  import net.bmahe.genetics4j.core.spec.AbstractEAConfiguration;
12  import net.bmahe.genetics4j.core.util.MultiIntCounter;
13  
14  /**
15   * TODO TEST THE SHIT OUT OF ME
16   * 
17   * @author bruno
18   *
19   */
20  public class AllCasesGenotypeCombinator implements GenotypeCombinator {
21  
22  	@Override
23  	public List<Genotype> combine(final AbstractEAConfiguration eaConfiguration, final List<List<Chromosome>> chromosomes) {
24  		Validate.notNull(eaConfiguration);
25  		Validate.notNull(chromosomes);
26  		Validate.isTrue(eaConfiguration.chromosomeSpecs().size() == chromosomes.size());
27  
28  		boolean hasChild = true;
29  		for (int i = 0; i < chromosomes.size() && hasChild; i++) {
30  			final List<Chromosome> list = chromosomes.get(i);
31  
32  			if (list.isEmpty()) {
33  				hasChild = false;
34  			}
35  		}
36  		if (hasChild == false) {
37  			return Collections.emptyList();
38  		}
39  
40  		final int[] maxIndices = chromosomes.stream().mapToInt(List::size).toArray();
41  
42  		final MultiIntCounter multiIntCounter = new MultiIntCounter(maxIndices);
43  
44  		boolean done = false;
45  		final List<Genotype> combined = new ArrayList<>();
46  		while (done == false) {
47  
48  			final List<Chromosome> currentGenotype = new ArrayList<>();
49  
50  			for (int i = 0; i < chromosomes.size(); i++) {
51  				final int index = multiIntCounter.getIndex(i);
52  				currentGenotype.add(chromosomes.get(i).get(index));
53  			}
54  			combined.add(new Genotype(currentGenotype));
55  
56  			multiIntCounter.next();
57  			if (multiIntCounter.hasNext() == false) {
58  				done = true;
59  			}
60  		}
61  
62  		return combined;
63  	}
64  }