Example usage for com.google.common.collect Lists cartesianProduct

List of usage examples for com.google.common.collect Lists cartesianProduct

Introduction

In this page you can find the example usage for com.google.common.collect Lists cartesianProduct.

Prototype

public static <B> List<List<B>> cartesianProduct(List<? extends B>... lists) 

Source Link

Document

Returns every possible list that can be formed by choosing one element from each of the given lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian product</a>" of the lists.

Usage

From source file:ItemManagement.GuavaCartesian.java

public static List calcTrinketSets() {

    getUniqueItemsByInfix get = new getUniqueItemsByInfix();

    ArrayList myList = get.JustTrinket();

    List<List> cartesianProduct = Lists.cartesianProduct(myList);

    //  System.out.println(cartesianProduct.toString());
    System.out.println(cartesianProduct.size());
    //  Object[] toArray = cartesianProduct.toArray();
    return cartesianProduct;
}

From source file:com.sk89q.worldedit.world.block.BlockState.java

static Map<Map<Property<?>, Object>, BlockState> generateStateMap(BlockType blockType) {
    Map<Map<Property<?>, Object>, BlockState> stateMap = new LinkedHashMap<>();
    List<? extends Property<?>> properties = blockType.getProperties();

    if (!properties.isEmpty()) {
        List<List<Object>> separatedValues = Lists.newArrayList();
        for (Property<?> prop : properties) {
            List<Object> vals = Lists.newArrayList();
            vals.addAll(prop.getValues());
            separatedValues.add(vals);//from ww  w . j  av  a  2  s  . com
        }
        List<List<Object>> valueLists = Lists.cartesianProduct(separatedValues);
        for (List<Object> valueList : valueLists) {
            Map<Property<?>, Object> valueMap = Maps.newTreeMap(Comparator.comparing(Property::getName));
            BlockState stateMaker = new BlockState(blockType);
            for (int i = 0; i < valueList.size(); i++) {
                Property<?> property = properties.get(i);
                Object value = valueList.get(i);
                valueMap.put(property, value);
                stateMaker.setState(property, value);
            }
            stateMap.put(valueMap, stateMaker);
        }
    }

    if (stateMap.isEmpty()) {
        // No properties.
        stateMap.put(new LinkedHashMap<>(), new BlockState(blockType));
    }

    for (BlockState state : stateMap.values()) {
        state.populate(stateMap);
    }

    return stateMap;
}

From source file:ItemManagement.GuavaCartesian.java

public static List calcArmourStats() {

    getUniqueItemsByInfix get = new getUniqueItemsByInfix();

    ArrayList myList = get.JustArmour();

    List<List> cartesianProduct = Lists.cartesianProduct(myList);

    //  System.out.println(cartesianProduct.toString());
    System.out.println(cartesianProduct.size());
    //  Object[] toArray = cartesianProduct.toArray();
    return cartesianProduct;
}

From source file:ItemManagement.GuavaCartesian.java

public static ArrayList CartesianSetBuilder(ArrayList list1, int limit) throws IOException {

    List<List> cartesianProduct = Lists.cartesianProduct(list1);
    ArrayList uniqueSets = new ArrayList();
    ArrayList uniqueStats = new ArrayList();
    //  System.out.println(cartesianProduct.toString());
    System.out.println(cartesianProduct.size());
    int index = 0;
    if (limit == 0) {
        limit = cartesianProduct.size();
    }/*from  w  ww .ja  va 2  s . c o  m*/
    while (index != limit) {
        List mysets = cartesianProduct.get(index);

        itemSet myItemSet = new itemSet(mysets);
        myItemSet.calcSetStats();
        scoreValues setValues = myItemSet.getSetValues();
        //ListOfSets.add(myItemSet);
        if (uniqueStats.contains(setValues)) {
            System.out.println("stat set already exists");
        } else {
            uniqueStats.add(setValues);
            uniqueSets.add(myItemSet);
            System.out.println("UNIQUE SET ADDED - SIZE: " + uniqueSets.size());

        }
        // DbConnect con = new DbConnect();
        // con.storeItem(myItemSet);

        System.out.println(index + " OF " + limit);
        index++;

    }

    //myItemSet.calcscore(values);
    //  Object[] toArray = cartesianProduct.toArray();
    return uniqueSets;

}

From source file:grakn.core.graql.reasoner.pattern.RelationPattern.java

/**
 * Generates different relation patterns variants as a cartesian products of provided id configurations.
 *
 * ( (role label): $x, (role label): $y, ...) {T1(x), T2(y), ...}, {[x/...], [y/...], ...}
 *
 * NB: only roleplayer ids are involved in the Cartesian Product
 *
 * Example:/*from www  .  ja va 2s.  com*/
 * [someRole, someType, {V123, V456, V789} ]
 * [anotherRole, x, {V123}]
 * [yetAnotherRole, x, {V456}]
 *
 * Will generate the following relations:
 *
 * {Type cartesian product},
 * {Role Player Id cartesian product}
 * {Rel id variants}
 *
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), someType($genVarA)
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), [$genVarA/V123], [$genVarB/V123], [$genVarC/V456]
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), [$genVarA/V456], [$genVarB/V123], [$genVarC/V456]
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), [$genVarA/V789], [$genVarB/V123], [$genVarC/V456]
 *
 * @param spec roleplayer configuration in the form {role} -> {type label, {ids...}}
 * @param relationIds list of id mappings for relation variable
 * @return list of generated patterns as strings
 */
private static List<Pattern> generateRelationPatterns(
        Multimap<RelationProperty.RolePlayer, Pair<Label, List<ConceptId>>> spec, List<ConceptId> relationIds) {
    Statement relationVar = !relationIds.isEmpty() ? new Statement(new Variable().asReturnedVar())
            : Graql.var();
    Statement[] basePattern = { relationVar };
    List<List<Pattern>> rpTypePatterns = new ArrayList<>();
    List<List<Pattern>> rpIdPatterns = new ArrayList<>();
    spec.entries().forEach(entry -> {
        RelationProperty.RolePlayer rp = entry.getKey();
        Statement role = rp.getRole().orElse(null);

        Statement rolePlayer = new Statement(entry.getKey().getPlayer().var().asReturnedVar());

        Label type = entry.getValue().getKey();
        List<ConceptId> ids = entry.getValue().getValue();
        basePattern[0] = basePattern[0].rel(role, rolePlayer);

        //rps.put(role, rolePlayer);

        List<Pattern> rpPattern = Lists.newArrayList(rolePlayer);
        List<Pattern> typePattern = Lists.newArrayList(rolePlayer);
        if (type != null)
            typePattern.add(rolePlayer.isa(type.getValue()));

        ids.forEach(id -> {
            Statement idPattern = rolePlayer.id(id.getValue());
            rpPattern.add(idPattern);
        });

        rpIdPatterns.add(rpPattern);
        rpTypePatterns.add(typePattern);
    });
    List<Pattern> relIdPatterns = new ArrayList<>();
    relationIds
            .forEach(relId -> relIdPatterns.add(Graql.and(basePattern[0], relationVar.id(relId.getValue()))));

    List<Pattern> patterns = new ArrayList<>();

    Stream.concat(Lists.cartesianProduct(rpTypePatterns).stream(),
            Lists.cartesianProduct(rpIdPatterns).stream())
            //filter trivial patterns
            .map(l -> l.stream()
                    .filter(p -> (p instanceof Conjunction)
                            || ((Statement) p).properties().stream().findFirst().isPresent())
                    .collect(Collectors.toList()))
            .forEach(product -> {
                Pattern[] pattern = { basePattern[0] };
                product.forEach(p -> pattern[0] = Graql.and(pattern[0], p));
                if (!patterns.contains(pattern[0]))
                    patterns.add(pattern[0]);
            });
    return Stream.concat(patterns.stream(), relIdPatterns.stream()).collect(Collectors.toList());
}

From source file:tuupertunut.hintahaku.ostoskori.JoukkotilausAlgoritmi.java

private static Map<Ostos, Hintatieto> laskeParhaatHinnat(Ostoskori ostoskori) {

    Map<Ostos, List<Hintatieto>> ostoksenHintatiedot = new LinkedHashMap<>();

    /* Listn ostoksille niiden hintatiedot. */
    for (Ostos ostos : ostoskori.getOstokset()) {

        /* Listn kaikkien ostoksen tuotevaihtoehtojen hintatiedot yhteen
         * yhdeksi listaksi. *//*from   w w w .j  a v a 2  s. co m*/
        List<Hintatieto> yhdistetytHintatiedot = new ArrayList<>();
        for (Tuote vaihtoehto : ostos.getVaihtoehdot()) {
            yhdistetytHintatiedot.addAll(vaihtoehto.getHintatiedot());
        }

        /* Poistetaan hintatiedot, joiden suodatettua hintaa ei ole
         * mritetty (kauppa on suodatettu pois tai postikuluja ei
         * tiedet). */
        yhdistetytHintatiedot.removeIf((Hintatieto ht) -> !ht.getSuodatettuHinta().isPresent());

        /* Optimointi: Poistetaan ostoksesta ne hintatiedot, joiden
         * postikuluton hinta on suurempi kuin halvimman hintatiedon
         * suodatettu (postikulullinen) hinta. */
        Optional<Hinta> halvinSuodatettu = ostos.getHalvinSuodatettuHintatieto()
                .flatMap(Hintatieto::getSuodatettuHinta);
        if (halvinSuodatettu.isPresent()) {
            yhdistetytHintatiedot
                    .removeIf((Hintatieto ht) -> ht.getHinta().onEnemmanKuin(halvinSuodatettu.get()));
        }

        /* Jos hintatietolistassa on hintatietoja jljell, listn ne
         * mappiin. */
        if (!yhdistetytHintatiedot.isEmpty()) {
            ostoksenHintatiedot.put(ostos, yhdistetytHintatiedot);
        }
    }

    Map<Ostos, Hintatieto> halvinYhdistelma = null;

    List<Ostos> ostokset = new ArrayList<>(ostoksenHintatiedot.keySet());
    List<List<Hintatieto>> hintatietoListat = new ArrayList<>(ostoksenHintatiedot.values());

    /* Kydn lpi kaikki mahdolliset hintatietoyhdistelmt ja valitaan
     * niist halvin. Tm prosessi on erittin raskas suurilla tuote- ja
     * hintatietomrill, joten aiemmassa vaiheessa tehty optimointi on
     * hyvin trke. Esimerkkin 15 kpl 10:n hintatiedon tuotteita vaatisi
     * ilman optimointia jopa tuhat biljoonaa kokeilua. */
    for (List<Hintatieto> yhdistelmanHintatiedot : Lists.cartesianProduct(hintatietoListat)) {

        Map<Ostos, Hintatieto> yhdistelma = new HashMap<>();

        /* Muodostetaan yhdistelm hintatietoja. Tiedetn, ett
         * yhdistelmanHintatiedot- ja ostokset-listojen indexit vastaavat
         * toisiaan. */
        for (int i = 0; i < ostokset.size(); i++) {
            yhdistelma.put(ostokset.get(i), yhdistelmanHintatiedot.get(i));
        }

        /* Testataan, onko muodostettu yhdistelm halvempi kuin thn asti
         * halvin yhdistelm. */
        if (halvinYhdistelma == null
                || kokonaisHinta(yhdistelma).onVahemmanKuin(kokonaisHinta(halvinYhdistelma))) {
            halvinYhdistelma = yhdistelma;
        }
    }

    return halvinYhdistelma;
}

From source file:org.sosy_lab.cpachecker.util.templates.TemplatePrecision.java

/**
 * Generate all linear expressions of size up to {@code maxExpressionSize}
 * with coefficients in {@code allowedCoefficients},
 * over the variables returned by {@link #getVarsForNode(CFANode)}.
 *//*from   ww w.ja v  a2s. c o  m*/
private Set<Template> generateTemplates(final CFANode node) {

    Set<ASimpleDeclaration> varsForNode = getVarsForNode(node);
    Set<CIdExpression> vars = varsForNode.stream().filter(this::shouldProcessVariable)
            .map(d -> new CIdExpression(FileLocation.DUMMY, (CSimpleDeclaration) d))
            .collect(Collectors.toSet());
    int maxLength = Math.min(maxExpressionSize, vars.size());
    allowedCoefficients = allowedCoefficients.stream().filter(x -> !x.equals(Rational.ZERO))
            .collect(Collectors.toSet());

    // Copy the {@code vars} multiple times for the cartesian product.
    List<Set<CIdExpression>> lists = Collections.nCopies(maxLength, vars);

    // All lists of size {@code maxExpressionSize}.
    Set<List<CIdExpression>> product = Sets.cartesianProduct(lists);

    // Eliminate duplicates, and ensure that all combinations are unique.
    // As a by-product, produces the expressions of all sizes less than
    // {@code maxExpressionSize} as well.
    Set<Set<CIdExpression>> combinations = product.stream().map(HashSet<CIdExpression>::new)
            .collect(Collectors.toSet());

    Set<Template> returned = new HashSet<>();
    for (Set<CIdExpression> variables : combinations) {

        // For of every variable: instantiate with every coefficient.
        List<List<LinearExpression<CIdExpression>>> out = variables
                .stream().map(x -> allowedCoefficients.stream()
                        .map(coeff -> LinearExpression.monomial(x, coeff)).collect(Collectors.toList()))
                .collect(Collectors.toList());

        // Convert to a list of all possible linear expressions.
        List<LinearExpression<CIdExpression>> linearExpressions = Lists.cartesianProduct(out).stream()
                .map(list -> list.stream().reduce(LinearExpression.empty(), LinearExpression::add))
                .collect(Collectors.toList());

        Set<Template> generated = filterToSameType(filterRedundantExpressions(linearExpressions)).stream()
                .filter(t -> !t.isEmpty()).map(Template::of).collect(Collectors.toSet());
        returned.addAll(generated);
    }

    if (generateDifferences) {
        returned.addAll(generateDifferenceTemplates(vars));
    }

    return returned;
}

From source file:org.apache.atlas.gremlin.optimizer.ExpandOrsOptimization.java

/**
 * This is called when we encounter an expression that is not an "or", for example an "and" expressio.  For these
 * expressions, we process the children and create copies with the cartesian product of the updated
 * arguments./*ww w  .  j  av a  2 s.c o  m*/
 *
 * Example:
 *
 * g.V().and(or(has('x),has('y'), or(has('a'),has('b')))
 *
 * Here, we have an "and" expression with two children:
 *
 * 1) or(has('x),has('y')
 * 2) or(has('a'),has('b'))
 *
 * We first process these children.  They each yield 2 expressions:
 *
 * 1 -> [ has('x'), has('y') ]
 * 2 -> [ has('a'), has('b') ]
 *
 * The cartesian product of these gives this:
 *
 *    [ has('x'), has('a') ]
 *    [ has('x'), has('b') ]
 *    [ has('y'), has('a') ]
 *    [ has('y'), has('b') ]
 *
 * So the overall result is:
 *
 * g.V().and(has('x'), has('a'))
 * g.V().and(has('x'), has('b'))
 * g.V().and(has('y'), has('a'))
 * g.V().and(has('y'), has('b'))
 *
 *
 * @param source
 * @param context
 * @return expressions that should be unioned together to get the query result
 */
private List<GroovyExpression> processOtherExpression(GroovyExpression source, OptimizationContext context) {
    UpdatedExpressions updatedChildren = getUpdatedChildren(source, context);
    if (!updatedChildren.hasChanges()) {
        return Collections.singletonList(source);
    }
    List<GroovyExpression> result = new ArrayList<GroovyExpression>();

    //The updated children list we get back has the possible values for each child
    //in the expression.  We compute a cartesian product to get all possible
    //combinations of child values.
    List<List<GroovyExpression>> updateChildLists = Lists
            .cartesianProduct(updatedChildren.getUpdatedChildren());

    for (List<GroovyExpression> updatedChildList : updateChildLists) {
        result.add(source.copy(updatedChildList));
    }
    return result;
}