source: src/main/java/agents/anac/y2017/simpleagent/CartesianCalculator.java@ 346

Last change on this file since 346 was 1, checked in by Wouter Pasman, 6 years ago

Initial import : Genius 9.0.0

File size: 1.2 KB
Line 
1package agents.anac.y2017.simpleagent;
2
3import java.util.ArrayList;
4import java.util.List;
5
6public class CartesianCalculator {
7
8 public <T> List<List<T>> calculate(List<List<T>> input) {
9 List<List<T>> res = new ArrayList<>();
10 if (input.isEmpty()) { // if no more elements to process
11 res.add(new ArrayList<T>()); // then add empty list and return
12 return res;
13 } else {
14 process(input, res); // we need to calculate the cartesian product
15 // of input and store it in res variable
16 }
17 return res; // method completes , return result
18 }
19
20 private <T> void process(List<List<T>> lists, List<List<T>> res) {
21 List<T> head = lists.get(0); // take first element of the list
22 List<List<T>> tail = calculate(lists.subList(1, lists.size())); // invoke
23 // calculate
24 // on
25 // remaining
26 // element,
27 // here
28 // is
29 // recursion
30
31 for (T h : head) { // for each head
32 for (List<T> t : tail) { // iterate over the tail
33 List<T> tmp = new ArrayList<>(t.size());
34 tmp.add(h); // add the head
35 tmp.addAll(t); // and current tail element
36
37 res.add(tmp);
38 }
39 }
40 }
41}
Note: See TracBrowser for help on using the repository browser.