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:com.cloudera.exhibit.core.PivotCalculator.java

@Override
public ObsDescriptor initialize(ExhibitDescriptor descriptor) {
    ObsDescriptor fd = fc.initialize(descriptor);
    List<ObsDescriptor.Field> idFields = Lists.newArrayList();
    List<ObsDescriptor.Field> valueFields = Lists.newArrayList();
    List<Set<String>> levelSet = Lists.newArrayList(keys.values());
    for (ObsDescriptor.Field f : fd) {
        if (ids.contains(f.name)) {
            idFields.add(new ObsDescriptor.Field(f.name, f.type));
        } else if (!ids.contains(f.name) && !keys.containsKey(f.name)) { // value fields
            for (List<String> suffix : Sets.cartesianProduct(levelSet)) {
                StringBuilder sb = new StringBuilder(f.name);
                sb.append('_');
                sb.append(Joiner.on('_').join(suffix));
                valueFields.add(new ObsDescriptor.Field(sb.toString(), f.type));
            }// www .  j  a v a  2  s . c o  m
        }
    }
    idFields.addAll(valueFields);
    return new SimpleObsDescriptor(idFields);
}

From source file:org.tensorics.core.tensor.specific.PositionIndexer.java

public Set<Position> allPositions() {
    ImmutableSet.Builder<Position> builder = ImmutableSet.builder();
    Set<List<Object>> allCombinations = Sets.cartesianProduct(coordinateSets());
    for (List<Object> coordinates : allCombinations) {
        builder.add(Position.of(coordinates));
    }/*from  w  w  w.j av a  2 s  .  c o m*/
    return builder.build();
}

From source file:hudson.matrix.AxisList.java

/**
 * List up all the possible combinations of this list.
 *//*from ww  w. j  a v a 2s. c  o m*/
public Iterable<Combination> list() {
    List<Set<String>> axesList = Lists.newArrayList();
    for (Axis axis : this)
        axesList.add(new LinkedHashSet<String>(axis.getValues()));

    return Iterables.transform(Sets.cartesianProduct(axesList), new Function<List<String>, Combination>() {
        public Combination apply(@Nullable List<String> strings) {
            assert strings != null;
            return new Combination(AxisList.this, (String[]) strings.toArray(new String[0]));
        }
    });
}

From source file:com.dangdang.ddframe.rdb.sharding.config.common.internal.algorithm.ClosureShardingAlgorithm.java

@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames,
        final Collection<ShardingValue<?>> shardingValues) {
    List<Set<Comparable>> valuesDim = new ArrayList<>();
    List<String> columnNames = new ArrayList<>(shardingValues.size());
    for (ShardingValue<?> each : shardingValues) {
        columnNames.add(each.getColumnName());
        switch (each.getType()) {
        case SINGLE:
            valuesDim.add(Sets.newHashSet((Comparable) each.getValue()));
            break;
        case LIST:
            valuesDim.add(Sets.<Comparable>newHashSet(each.getValues()));
            break;
        case RANGE:
            throw new UnsupportedOperationException(
                    "Inline expression does not support BETWEEN, please use Java API Config");
        default://from  w ww  . j a  va  2  s .co m
            throw new UnsupportedOperationException(each.getType().name());
        }
    }
    Set<List<Comparable>> cartesianValues = Sets.cartesianProduct(valuesDim);
    List<String> result = new ArrayList<>(cartesianValues.size());
    for (List<Comparable> each : cartesianValues) {
        result.add(cloneClosure(columnNames, each).call().toString());
    }
    return result;
}

From source file:fr.ens.biologie.genomique.eoulsan.core.workflow.CrossDataProduct.java

@Override
public Set<ImmutableMap<InputPort, Data>> makeProduct(final StepInputPorts inputPorts,
        final Multimap<InputPort, Data> inputTokens) {

    checkNotNull(inputPorts, "inputPorts argument cannot be null");
    checkNotNull(inputTokens, "inputTokens argument cannot be null");

    final Set<ImmutableMap<InputPort, Data>> result = new HashSet<>();
    final List<StepInputPort> portsList = Lists.newArrayList(inputPorts.iterator());

    // First create the lists for Sets.cartesianProduct()
    final List<Set<CartesianProductEntry>> sets = new ArrayList<>();
    for (StepInputPort port : portsList) {
        final Set<CartesianProductEntry> s = new HashSet<>();
        for (Data d : inputTokens.get(port)) {
            s.add(new CartesianProductEntry(port, d));
        }/*  w w  w .j  av a  2 s .  c  o m*/
        sets.add(s);
    }

    // Compute cartesian product
    final Set<List<CartesianProductEntry>> cartesianProduct = Sets.cartesianProduct(sets);

    // Now convert result of cartesianProduct() to final result
    for (List<CartesianProductEntry> l : cartesianProduct) {

        final ImmutableMap.Builder<InputPort, Data> imb = ImmutableMap.builder();

        for (CartesianProductEntry e : l) {
            imb.put(e.port, e.data);
        }

        result.add(imb.build());
    }

    return result;
}

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

@Override
public Collection<Result> handle(RequestContext request, PolicyDecisionPointContext context) {
    if (request.containsRepeatingCategories()) {
        return handleNext(request, context);
    }/*w  w w  . ja v  a 2  s.c o m*/
    if (!request.containsAttributeValues(MULTIPLE_CONTENT_SELECTOR, XacmlTypes.XPATH)) {
        if (log.isDebugEnabled()) {
            log.debug("Request does not have attributeId=\"{}\" of type=\"{}\", "
                    + "passing request to next handler", MULTIPLE_CONTENT_SELECTOR, XacmlTypes.XPATH);
        }
        return handleNext(request, context);
    }
    try {
        XPathProvider xpathProvider = context.getXPathProvider();
        List<Set<Category>> all = new LinkedList<Set<Category>>();
        for (Category attribute : request.getAttributes()) {
            all.add(getAttributes(request, attribute, xpathProvider));
        }
        Set<List<Category>> cartesian = Sets.cartesianProduct(all);
        List<Result> results = new LinkedList<Result>();
        for (List<Category> requestAttr : cartesian) {
            RequestContext req = RequestContext.builder().copyOf(request, requestAttr).build();
            if (log.isDebugEnabled()) {
                log.debug("Created request=\"{}\"", req);
            }
            results.addAll(handleNext(req, context));
        }
        return results;
    } catch (RequestSyntaxException e) {
        return Collections.singleton(Result.indeterminate(e.getStatus())
                .includeInResultAttr(request.getIncludeInResultAttributes()).build());
    }
}

From source file:io.crate.analyze.where.EqualityExtractor.java

private List<List<Symbol>> extractMatches(Collection<ColumnIdent> columns, Symbol symbol, boolean exact,
        @Nullable TransactionContext transactionContext) {
    EqualityExtractor.ProxyInjectingVisitor.Context context = new EqualityExtractor.ProxyInjectingVisitor.Context(
            columns, exact);/*from  w  w  w  .ja  v  a 2  s  .c om*/
    Symbol proxiedTree = ProxyInjectingVisitor.INSTANCE.process(symbol, context);

    // bail out if we have any unknown part in the tree
    if (context.exact && context.seenUnknown) {
        return null;
    }

    List<Set<EqProxy>> comparisons = context.comparisonSet();
    Set<List<EqProxy>> cp = Sets.cartesianProduct(comparisons);

    List<List<Symbol>> result = new ArrayList<>();
    for (List<EqProxy> proxies : cp) {
        boolean anyNull = false;
        for (EqProxy proxy : proxies) {
            if (proxy != NULL_MARKER_PROXY) {
                proxy.setTrue();
            } else {
                anyNull = true;
            }
        }
        Symbol normalized = normalizer.normalize(proxiedTree, transactionContext);
        if (normalized == Literal.BOOLEAN_TRUE) {
            if (anyNull) {
                return null;
            }
            if (!proxies.isEmpty()) {
                List<Symbol> row = new ArrayList<>(proxies.size());
                for (EqProxy proxy : proxies) {
                    proxy.reset();
                    row.add(proxy.origin.arguments().get(1));
                }
                result.add(row);
            }
        } else {
            for (EqProxy proxy : proxies) {
                proxy.reset();
            }
        }
    }
    return result.isEmpty() ? null : result;

}

From source file:es.usc.citius.composit.core.composition.search.CompositSearch.java

private static <E> Set<Set<Operation<E>>> combine(Multimap<Set<E>, Operation<E>> matchMap) {
    // Get the groups
    Set<Set<E>> sets = matchMap.asMap().keySet();
    log.debug("\t\t> Performing set input cover of {}", sets);
    SetCoverIterator<E> sc = new SetCoverIterator<E>(sets);
    //sc.useParallelization(true);
    Set<Set<Operation<E>>> coveringSets = new HashSet<Set<Operation<E>>>();
    while (sc.hasNext()) {
        Set<Set<E>> group = sc.next();
        log.debug("\t\t\t+ Selected cover input group: {}", group);
        // Get the services associated to each E group
        List<Set<Operation<E>>> solution = new ArrayList<Set<Operation<E>>>();
        for (Set<E> inputsMatched : group) {
            Collection<Operation<E>> ops = matchMap.get(inputsMatched);
            solution.add(new HashSet<Operation<E>>(ops));
        }/*from w  w  w.j a  v a2s  . c o m*/
        log.debug("\t\t\t\t- Operation groups: {}", solution);
        // Generate cartesian product to decompose equivalent functional services
        Set<List<Operation<E>>> cartesian = Sets.cartesianProduct(solution);
        ;
        for (List<Operation<E>> cartesianResult : cartesian) {
            coveringSets.add(new HashSet<Operation<E>>(cartesianResult));
        }
        log.debug("\t\t\t\t- Cartesian product decomposition: {}", cartesian);
    }
    log.debug("\t\t\t- Cover sets before cartesian product decomposition {}", coveringSets);
    return coveringSets;
}

From source file:com.github.imasahiro.stringformatter.processor.FormatterMethod.java

private void checkArgumentTypes(ProcessingEnvironment processingEnv, List<FormatString> formatStringList,
        List<TypeMirror> expectedTypeList) {
    List<FormatSpecifier> formatSpecifiers = FluentIterable.from(formatStringList).filter(FormatSpecifier.class)
            .toList();/*  w w  w .  ja  v a  2 s .  co  m*/

    if (formatSpecifiers.size() != expectedTypeList.size()) {
        throw new RuntimeException(name + " cannot not acceptable to " + expectedTypeList);
    }

    Set<List<TypeMirror>> candidateArgumentTypes = Sets
            .cartesianProduct(
                    FluentIterable
                            .from(formatSpecifiers).transform(e -> e.getConversionType()
                                    .getType(processingEnv.getTypeUtils(), processingEnv.getElementUtils()))
                            .toList());

    if (!candidateArgumentTypes.stream()
            .anyMatch(candidate -> isAssignableArguments(processingEnv, candidate, expectedTypeList))) {
        errorReporter.fatal(name + " cannot not apply to " + expectedTypeList, element);
    }
}

From source file:org.eclipse.emf.compare.match.resource.NameSimilarityMatchingStrategy.java

/**
 * Computes the cartesian product of the two given iterables by converting them to {@link Set}s and
 * feeding them to {@link Sets#cartesianProduct(List)}.
 * /*from  w w  w .  j  a  v a2s .c  o m*/
 * @param iterable1
 *            First of the two iterables of which we need the cartesian product.
 * @param iterable2
 *            Second of the two iterables of which we need the cartesian product.
 * @param <T>
 *            Type of iterables' content.
 * @return The cartesian product of the two given iterables.
 * @see Sets#cartesianProduct(List)
 */
private static <T> Set<List<T>> cartesianProductOf(Iterable<? extends T> iterable1,
        Iterable<? extends T> iterable2) {
    Set<T> set1 = Sets.newLinkedHashSet(iterable1);
    Set<T> set2 = Sets.newLinkedHashSet(iterable2);
    List<Set<T>> input = ImmutableList.of(set1, set2);
    return Sets.cartesianProduct(input);
}