001/*
002 *                    BioJava development code
003 *
004 * This code may be freely distributed and modified under the
005 * terms of the GNU Lesser General Public Licence.  This should
006 * be distributed with the code.  If you do not have a copy,
007 * see:
008 *
009 *      http://www.gnu.org/copyleft/lesser.html
010 *
011 * Copyright for this code is held jointly by the individual
012 * authors.  These should be listed in @author doc comments.
013 *
014 * For more information on the BioJava project and its aims,
015 * or to join the biojava-l mailing list, visit the home page
016 * at:
017 *
018 *      http://www.biojava.org/
019 *
020 */
021package org.biojava.nbio.structure.quaternary;
022
023import java.util.ArrayList;
024import java.util.Collections;
025import java.util.List;
026
027
028/**
029 * A cartesian product between two lists A and B is the set of all ordered pairs
030 * of the elements of both sets.
031 *
032 * See http://en.wikipedia.org/wiki/Cartesian_product for more details.
033 *
034 * Since the order of the elements matters; Lists are used instead of Sets.
035 *
036 * Example:
037 *  A = {1, 2, 3}
038 *  B = {4, 5}
039 *  The ordered pairs are {1, 4}, {1, 5}, {2, 4}, .., {3, 5}
040 *
041 * @author Peter Rose
042 *
043 */
044public class CartesianProduct<T> {
045
046        private List<T> list1 = Collections.emptyList();
047        private List<T> list2 = Collections.emptyList();
048
049        /**
050         * Class constructor specifying the two lists of a cartesian product.
051         */
052        public CartesianProduct(List<T> list1, List<T> list2) {
053                this.list1 = list1;
054                this.list2 = list2;
055        }
056
057        /**
058         * Generates the list of ordered pair between two sets.
059         *
060         * @return the list of ordered pairs
061         */
062        public List<OrderedPair<T>> getOrderedPairs() {
063                List<OrderedPair<T>> pairs = new ArrayList<OrderedPair<T>>(list1.size()*list2.size());
064
065                for (T element1: list1) {
066                        for (T element2: list2) {
067                                pairs.add(new OrderedPair<T>(element1, element2));
068                        }
069                }
070
071                return pairs;
072        }
073}