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:ai.grakn.graql.internal.gremlin.ConjunctionQuery.java

private static Stream<List<Fragment>> cartesianProduct(List<EquivalentFragmentSet> fragmentSets) {
    // Get fragments in each set
    List<Set<Fragment>> fragments = fragmentSets.stream().map(EquivalentFragmentSet::fragments)
            .collect(toList());/*from  w w  w  .ja v a  2 s  .c  om*/
    return Sets.cartesianProduct(fragments).stream();
}

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

@SuppressWarnings(value = "unchecked")
private static Set<List<String>> getValueScenario(final GString gString) {
    List<Set<String>> dimValue = new ArrayList<>(gString.getValues().length);
    for (Object each : gString.getValues()) {
        if (null == each) {
            continue;
        }//  w  w  w .  ja  v a 2s  . com
        if (each instanceof Collection) {
            dimValue.add(Sets.newHashSet(
                    Collections2.transform((Collection<Object>) each, new Function<Object, String>() {
                        @Override
                        public String apply(final Object input) {
                            return input.toString();
                        }
                    })));
        } else {
            dimValue.add(Sets.newHashSet(each.toString()));
        }
    }
    return Sets.cartesianProduct(dimValue);
}

From source file:fr.aliacom.obm.common.user.UserEmails.java

public Iterable<String> expandAllEmailDomainTuples() {
    return FluentIterable
            .from(Sets.cartesianProduct(ImmutableList.of(ImmutableSet.copyOf(addresses), domain.getNames())))
            .transform(new Function<List<String>, String>() {
                @Override//from w  ww  . j av  a2s. co m
                public String apply(List<String> input) {
                    return appendSuffixToEmailIfRequired(input.get(0), input.get(1));
                }
            }).toSet();
}

From source file:org.lanternpowered.server.block.state.LanternBlockStateMap.java

@SuppressWarnings("rawtypes")
public LanternBlockStateMap(LanternBlockType blockType, Iterable<BlockTrait<?>> blockTraits) {
    this.blockType = blockType;

    // There are no block traits
    if (!blockTraits.iterator().hasNext()) {
        final LanternBlockState blockState = new LanternBlockState(this, ImmutableMap.of());
        blockState.propertyValueTable = ImmutableTable.of();
        this.blockStates = ImmutableList.of(blockState);
        this.blockTraits = ImmutableMap.of();
        this.keys = ImmutableSet.of();
        return;//from   ww w  . java 2 s . c om
    }

    // Convert to a list so it can be sorted
    final List<BlockTrait<?>> list = Lists.newArrayList(blockTraits);

    // Sort the traits by the name
    list.sort(Comparator.comparing(BlockTrait::getName));

    // The builder for the name to trait lookup
    final ImmutableMap.Builder<String, BlockTrait<?>> builder = ImmutableMap.builder();
    final ImmutableSet.Builder<Key<?>> keys = ImmutableSet.builder();

    // All the sets with all the allowed values
    final List<Set<Comparable<?>>> allowedValues = new ArrayList<>();

    for (BlockTrait<?> trait : list) {
        allowedValues.add(new HashSet<>(trait.getPossibleValues()));
        keys.add(((LanternBlockTrait) trait).getKey());
        builder.put(trait.getName(), trait);
    }

    // Build the lookups
    this.blockTraits = builder.build();
    this.keys = keys.build();

    // A map with as the key the trait values map and as value the state
    final LinkedHashMap<Map<?, ?>, BlockState> stateByValuesMap = new LinkedHashMap<>();

    // The block states
    final ImmutableList.Builder<BlockState> blockStates = ImmutableList.builder();

    // Do the cartesian product to get all the possible combinations
    for (List<Comparable<?>> comparables : Sets.cartesianProduct(allowedValues)) {
        final Iterator<Comparable<?>> objectsIt = comparables.iterator();

        final ImmutableMap.Builder<BlockTrait<?>, Comparable<?>> traitValuesBuilder = ImmutableMap.builder();
        for (BlockTrait<?> trait : list) {
            traitValuesBuilder.put(trait, objectsIt.next());
        }

        final ImmutableMap<BlockTrait<?>, Comparable<?>> traitValues = traitValuesBuilder.build();
        final LanternBlockState blockState = new LanternBlockState(this, traitValues);
        stateByValuesMap.put(traitValues, blockState);
        blockStates.add(blockState);
    }

    this.blockStates = blockStates.build();
    this.blockStates.stream().map(state -> (LanternBlockState) state).forEach(state -> {
        final ImmutableTable.Builder<BlockTrait<?>, Comparable<?>, BlockState> tableBuilder = ImmutableTable
                .builder();
        list.forEach(trait -> trait.getPossibleValues().stream()
                .filter(value -> value != state.getTraitValue(trait).get()).forEach(value -> {
                    final Map<BlockTrait<?>, Comparable<?>> valueByTrait = new HashMap<>();
                    valueByTrait.putAll(state.traitValues);
                    valueByTrait.put(trait, value);
                    tableBuilder.put(trait, value, stateByValuesMap.get(valueByTrait));
                }));
        state.propertyValueTable = tableBuilder.build();
    });

    int internalId = 0;
    for (BlockState blockState : this.blockStates) {
        final LanternBlockState blockState1 = (LanternBlockState) blockState;
        blockState1.extended = blockType.getExtendedBlockStateProvider().remove(blockState) != blockState;
        blockState1.internalId = internalId++;
    }
}

From source file:ai.grakn.graql.internal.gremlin.GremlinQuery.java

public Stream<GraqlTraversal> allGraqlTraversals() {
    List<Set<List<Fragment>>> collect = innerQueries.stream().map(ConjunctionQuery::allFragmentOrders)
            .collect(toList());/*  ww w. ja v  a2 s. co  m*/
    Set<List<List<Fragment>>> lists = Sets.cartesianProduct(collect);
    return lists.stream().map(list -> GraqlTraversal.create(graph, Sets.newHashSet(list)));
}

From source file:org.sosy_lab.cpachecker.cpa.sign.SignCExpressionVisitor.java

@Override
public SIGN visit(CBinaryExpression pIastBinaryExpression) throws UnrecognizedCodeException {
    SIGN left = pIastBinaryExpression.getOperand1().accept(this);
    SIGN right = pIastBinaryExpression.getOperand2().accept(this);
    Set<SIGN> leftAtomSigns = left.split();
    Set<SIGN> rightAtomSigns = right.split();
    SIGN result = SIGN.EMPTY;//  www . j  a v a  2 s. c  om
    for (List<SIGN> signCombi : Sets.cartesianProduct(ImmutableList.of(leftAtomSigns, rightAtomSigns))) {
        result = result
                .combineWith(evaluateExpression(signCombi.get(0), pIastBinaryExpression, signCombi.get(1)));
    }
    return result;
}

From source file:org.verdictdb.core.querying.ola.AggMeta.java

List<TierCombination> generateAllTierCombinations(ScrambleMetaSet metaset) {
    List<TierCombination> combinations = new ArrayList<>();
    List<Pair<String, String>> scrambles = new ArrayList<>();
    List<Integer> tierCounts = new ArrayList<>();
    for (ScrambleMeta meta : metaset) {
        String schemaName = meta.getSchemaName();
        String tableName = meta.getTableName();
        scrambles.add(Pair.of(schemaName, tableName));
        tierCounts.add(meta.getNumberOfTiers());
    }/*w  w  w  .  j a  va2  s  .co  m*/

    // create individual tier number sets; this will be the argument for the cartesian product
    List<Set<Integer>> tierLists = new ArrayList<>();
    for (int c : tierCounts) {
        //      Set<Integer> tiers = Ranges.closedOpen(0, c).asSet(DiscreteDomains.integers());
        Set<Integer> tiers = new TreeSet<>();
        for (int i = 0; i < c; i++) {
            tiers.add(i);
        }
        tierLists.add(tiers);
    }
    Set<List<Integer>> product = Sets.cartesianProduct(tierLists);

    // convert the product to tier combination object
    for (List<Integer> c : product) {
        TierCombination comb = new TierCombination(scrambles, c);
        combinations.add(comb);
    }

    return combinations;
}

From source file:org.trnltk.tokenizer.TokenizationGraph.java

private void inferEdges(TokenizationGraphNode sourceNode, TokenizationGraphNode targetNode, boolean addSpace,
        ImmutableList<TextBlock> exampleTextBlocks) {
    // assume we have sourceTypes <A,B> and targetTypes <C,D>
    // and K infers from A, L infers from B, M infers from C, N infers from D
    // target is to have same rule for following:
    // <A,B> - <C,D>        //not this! this is already the "premise"
    // <A,B> - <C,N>
    // <A,B> - <M,D>
    // <A,B> - <M,N>
    // <A,L> - <C,D>
    // <A,L> - <C,N>
    // <A,L> - <M,D>
    // <A,L> - <M,N>
    // <K,B> - <C,D>
    // <K,B> - <C,N>
    // <K,B> - <M,D>
    // <K,B> - <M,N>
    // <K,L> - <C,D>
    // <K,L> - <C,N>
    // <K,L> - <M,D>
    // <K,L> - <M,N>

    // [A,B]/*www. j  a  v a 2  s.c  o  m*/
    final ImmutableList<TextBlockType> sourceTypes = sourceNode.getData().getTextBlockTypes();
    final ImmutableList<TextBlockType> targetTypes = targetNode.getData().getTextBlockTypes();

    final Function<TextBlockType, Set<TextBlockType>> inferringFunction = new Function<TextBlockType, Set<TextBlockType>>() {
        @Override
        public Set<TextBlockType> apply(TextBlockType input) {
            Set<TextBlockType> types = Sets.newHashSet(input);

            final ImmutableCollection<TextBlockType> textBlockTypes = TextBlockType.INFERENCE_MAP.get(input);
            if (textBlockTypes != null)
                types.addAll(textBlockTypes);

            return types;
        }
    };

    // [{A,K},{B,L}]
    final List<Set<TextBlockType>> sourceInferenceTypes = Lists.transform(sourceTypes, inferringFunction);
    final List<Set<TextBlockType>> targetInferenceTypes = Lists.transform(targetTypes, inferringFunction);

    // [[A,B],[A,L],[K,B],[K,L]]
    final Set<List<TextBlockType>> sourceInferencePossibilities = Sets.cartesianProduct(sourceInferenceTypes);
    final Set<List<TextBlockType>> targetInferencePossibilities = Sets.cartesianProduct(targetInferenceTypes);

    final Set<Pair<TextBlockTypeGroup, TextBlockTypeGroup>> nodesToAddRules = new HashSet<Pair<TextBlockTypeGroup, TextBlockTypeGroup>>();

    for (List<TextBlockType> sourceInferencePossibility : sourceInferencePossibilities) {
        for (List<TextBlockType> targetInferencePossibility : targetInferencePossibilities) {
            nodesToAddRules.add(Pair.of(new TextBlockTypeGroup(sourceInferencePossibility),
                    new TextBlockTypeGroup(targetInferencePossibility)));
        }
    }

    nodesToAddRules.remove(Pair.of(sourceNode.getData(), targetNode.getData())); //don't add premise again

    if (logger.isDebugEnabled()) {
        logger.debug("Gonna try inferring rules for these source and target nodes:\t");
        for (Pair<TextBlockTypeGroup, TextBlockTypeGroup> pair : nodesToAddRules) {
            logger.debug(pair);
        }
    }

    this.addInferredEdges(nodesToAddRules, addSpace, exampleTextBlocks);
}

From source file:no.ssb.jsonstat.v2.support.DatasetTableView.java

private Set<List<String>> computeIndex(Set<String> dimensions) {
    List<Set<String>> rowDimensions = Lists.newArrayList();
    for (String row : dimensions) {
        rowDimensions.add(ImmutableSet.copyOf(this.dimensions.get(row)));
    }/* www .  j a va  2 s .  co  m*/
    return Sets.cartesianProduct(rowDimensions);
}

From source file:com.dangdang.ddframe.rdb.sharding.config.common.internal.parser.InlineParser.java

@SuppressWarnings("unchecked")
private Set<List<String>> getCartesianValues(final GString segment) {
    List<Set<String>> result = new ArrayList<>(segment.getValues().length);
    for (Object each : segment.getValues()) {
        if (null == each) {
            continue;
        }/*from w w w  .  jav a2 s.  com*/
        if (each instanceof Collection) {
            result.add(Sets.newHashSet(
                    Collections2.transform((Collection<Object>) each, new Function<Object, String>() {

                        @Override
                        public String apply(final Object input) {
                            return input.toString();
                        }
                    })));
        } else {
            result.add(Sets.newHashSet(each.toString()));
        }
    }
    return Sets.cartesianProduct(result);
}