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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:ch.ethz.bsse.quasirecomb.simulation.Recombinator.java

public static void recombine(String path, int[] spots, String output) {
    Map<String, String> haplotypes = Utils.parseHaplotypeFile(path);
    if (Globals.getINSTANCE().isDEBUG()) {
        System.out.println(Arrays.toString(spots));
        for (String s : haplotypes.keySet()) {
            System.out.println(s);
        }//  www. j a va  2  s. c  o  m
    }

    List<Integer> spotsList = new LinkedList<>();
    spotsList.add(0);

    for (int i : spots) {
        spotsList.add(i);
    }

    spotsList.add(haplotypes.keySet().iterator().next().length());

    List<Set<String>> sets = new ArrayList<>();
    for (int i = 1; i < spotsList.size(); i++) {
        Set<String> tmp_set = new HashSet<>();
        for (String s : haplotypes.keySet()) {
            tmp_set.add(s.substring(spotsList.get(i - 1), spotsList.get(i)));
        }
        sets.add(tmp_set);
    }

    Set<List<String>> cartesianProduct = Sets.cartesianProduct(sets);
    List<String> recombinants = new ArrayList<>();
    for (List<String> ll : cartesianProduct) {
        StringBuilder sb = new StringBuilder();
        for (String s : ll) {
            sb.append(s);
        }
        recombinants.add(sb.toString());
    }
    StringBuilder sb = new StringBuilder();
    int i = 0;
    for (String s : haplotypes.keySet()) {
        recombinants.remove(s);
        sb.append(">generator-").append(i++).append("\n").append(s).append("\n");
    }
    i = 0;
    for (String s : recombinants) {
        //            System.out.println(s);
        sb.append(">recombinant-").append(i++).append("\n").append(s).append("\n");
    }
    //        if (output.endsWith(File.separator)) {
    //            output+="recombinants.fasta";
    //        }
    System.out.println(sb.toString());
    //        Utils.saveFile(output, sb.toString());
}

From source file:com.jrestless.test.InvokableArguments.java

static <T> Set<List<T>> getCartesianProduct(List<Set<T>> arguments) {
    return Sets.cartesianProduct(arguments);
}

From source file:org.eclipse.viatra.query.runtime.matchers.psystem.rewriters.PQueryFlattener.java

/**
 * Utility function to produce the permutation of every possible mapping of values.
 * //from   w  ww  .j  a  va  2 s  . c  o  m
 * @param values
 * @return
 */
private static <K, V> Set<Map<K, V>> permutation(Map<K, Set<V>> values) {
    // An ordering of keys is defined here which will help restoring the appropriate values after the execution of
    // the cartesian product
    List<K> keyList = new ArrayList<>(values.keySet());

    // Produce list of value sets with the ordering defined by keyList
    List<Set<V>> valuesList = new ArrayList<Set<V>>(keyList.size());
    for (K key : keyList) {
        valuesList.add(values.get(key));
    }

    // Cartesian product will obey ordering of the list
    Set<List<V>> valueMappings = Sets.cartesianProduct(valuesList);

    // Build result
    Set<Map<K, V>> result = new LinkedHashSet<>();
    for (List<V> valueList : valueMappings) {
        Map<K, V> map = new HashMap<>();
        for (int i = 0; i < keyList.size(); i++) {
            map.put(keyList.get(i), valueList.get(i));
        }
        result.add(map);
    }

    return result;
}

From source file:com.dangdang.ddframe.rdb.sharding.router.mixed.CartesianTablesRouter.java

CartesianResult route() {
    CartesianResult result = new CartesianResult();
    for (Entry<String, Set<String>> entry : getDataSourceLogicTablesMap().entrySet()) {
        List<Set<String>> actualTableGroups = getActualTableGroups(entry.getKey(), entry.getValue());
        List<Set<SingleRoutingTableFactor>> routingTableFactorGroups = toRoutingTableFactorGroups(
                entry.getKey(), actualTableGroups);
        result.merge(entry.getKey(),//from  ww  w.  j ava 2 s .co m
                getCartesianTableReferences(Sets.cartesianProduct(routingTableFactorGroups)));
    }
    log.trace("cartesian tables sharding result: {}", result);
    return result;
}

From source file:io.mindmaps.graql.internal.query.ConjunctionImpl.java

@Override
public Disjunction<Conjunction<VarAdmin>> getDisjunctiveNormalForm() {
    // Get all disjunctions in query
    List<Set<Conjunction<VarAdmin>>> disjunctionsOfConjunctions = patterns.stream()
            .map(p -> p.getDisjunctiveNormalForm().getPatterns()).collect(toList());

    // Get the cartesian product.
    // in other words, this puts the 'ands' on the inside and the 'ors' on the outside
    // e.g. (A or B) and (C or D)  <=>  (A and C) or (A and D) or (B and C) or (B and D)
    Set<Conjunction<VarAdmin>> dnf = Sets.cartesianProduct(disjunctionsOfConjunctions).stream()
            .map(ConjunctionImpl::fromConjunctions).collect(toSet());

    return Patterns.disjunction(dnf);

    // Wasn't that a horrible function? Here it is in Haskell:
    //     dnf = map fromConjunctions . sequence . map getDisjunctiveNormalForm . patterns
}

From source file:com.dangdang.ddframe.rdb.sharding.routing.type.complex.CartesianRoutingEngine.java

@Override
public CartesianRoutingResult route() {
    CartesianRoutingResult result = new CartesianRoutingResult();
    for (Entry<String, Set<String>> entry : getDataSourceLogicTablesMap().entrySet()) {
        List<Set<String>> actualTableGroups = getActualTableGroups(entry.getKey(), entry.getValue());
        List<Set<TableUnit>> tableUnitGroups = toTableUnitGroups(entry.getKey(), actualTableGroups);
        result.merge(entry.getKey(), getCartesianTableReferences(Sets.cartesianProduct(tableUnitGroups)));
    }//from  w ww .jav a  2s .c o  m
    log.trace("cartesian tables sharding result: {}", result);
    return result;
}

From source file:ai.grakn.graql.internal.pattern.ConjunctionImpl.java

@Override
public Disjunction<Conjunction<VarPatternAdmin>> getDisjunctiveNormalForm() {
    // Get all disjunctions in query
    List<Set<Conjunction<VarPatternAdmin>>> disjunctionsOfConjunctions = patterns.stream()
            .map(p -> p.getDisjunctiveNormalForm().getPatterns()).collect(toList());

    // Get the cartesian product.
    // in other words, this puts the 'ands' on the inside and the 'ors' on the outside
    // e.g. (A or B) and (C or D)  <=>  (A and C) or (A and D) or (B and C) or (B and D)
    Set<Conjunction<VarPatternAdmin>> dnf = Sets.cartesianProduct(disjunctionsOfConjunctions).stream()
            .map(ConjunctionImpl::fromConjunctions).collect(toSet());

    return Patterns.disjunction(dnf);

    // Wasn't that a horrible function? Here it is in Haskell:
    //     dnf = map fromConjunctions . sequence . map getDisjunctiveNormalForm . patterns
}

From source file:org.xacml4j.v30.pdp.profiles.MultipleResourcesViaRepeatingAttributesHandler.java

@Override
public Collection<Result> handle(RequestContext request, PolicyDecisionPointContext context) {
    if (!request.containsRepeatingCategories()) {
        return handleNext(request, context);
    }//www .j a  v  a 2s . c o  m
    List<Set<Category>> byCategory = new LinkedList<Set<Category>>();
    for (CategoryId categoryId : request.getCategories()) {
        Collection<Category> attributes = request.getAttributes(categoryId);
        if (attributes == null || attributes.isEmpty()) {
            continue;
        }
        byCategory.add(new LinkedHashSet<Category>(attributes));
    }
    Collection<Result> results = new LinkedList<Result>();
    Set<List<Category>> cartesian = Sets.cartesianProduct(byCategory);
    for (List<Category> requestAttr : cartesian) {
        results.addAll(handleNext(RequestContext.builder().copyOf(request, requestAttr).build(), context));
    }
    return results;
}

From source file:grakn.core.graql.reasoner.state.RoleExpansionState.java

/**
 * @param toExpand set of variables for which Role hierarchy should be expanded
 * @return stream of answers with expanded role hierarchy
 *//*from w  w  w  .j a va2  s  . c o  m*/
private static Stream<ConceptMap> expandHierarchies(ConceptMap answer, Set<Variable> toExpand) {
    if (toExpand.isEmpty())
        return Stream.of(answer);
    List<Set<AbstractMap.SimpleImmutableEntry<Variable, Concept>>> entryOptions = answer.map().entrySet()
            .stream().map(e -> {
                Variable var = e.getKey();
                Concept concept = answer.get(var);
                if (toExpand.contains(var)) {
                    if (concept.isSchemaConcept()) {
                        return concept.asSchemaConcept().sups()
                                .map(sup -> new AbstractMap.SimpleImmutableEntry<>(var, (Concept) sup))
                                .collect(Collectors.toSet());
                    }
                }
                return Collections.singleton(new AbstractMap.SimpleImmutableEntry<>(var, concept));
            }).collect(Collectors.toList());

    return Sets
            .cartesianProduct(
                    entryOptions)
            .stream()
            .map(mappingList -> new ConceptMap(mappingList.stream()
                    .collect(Collectors.toMap(AbstractMap.SimpleImmutableEntry::getKey,
                            AbstractMap.SimpleImmutableEntry::getValue)),
                    answer.explanation()))
            .map(ans -> ans.explain(answer.explanation()));
}

From source file:com.google.caliper.runner.FullCartesianExperimentSelector.java

protected static <T> Set<List<T>> cartesian(SetMultimap<String, T> multimap) {
    @SuppressWarnings({ "unchecked", "rawtypes" }) // promised by spec
    ImmutableMap<String, Set<T>> paramsAsMap = (ImmutableMap) multimap.asMap();
    return Sets.cartesianProduct(paramsAsMap.values().asList());
}