Example usage for com.google.common.collect Collections2 permutations

List of usage examples for com.google.common.collect Collections2 permutations

Introduction

In this page you can find the example usage for com.google.common.collect Collections2 permutations.

Prototype

@Beta
public static <E> Collection<List<E>> permutations(Collection<E> elements) 

Source Link

Document

Returns a Collection of all the permutations of the specified Collection .

Usage

From source file:com.datumbox.framework.mathematics.discrete.Combinatorics.java

/**
 * Returns the permutations of a collection. Uses Guava library's Collection2.
 * //from  w w w.  ja  v  a2  s.c o  m
 * @param <T>
 * @param elements
 * @return 
 */
public static <T> Collection<List<T>> permutations(Collection<T> elements) {
    Collection<List<T>> permutations = Collections2.permutations(elements);

    List<List<T>> result = new ArrayList<>();
    for (List<T> internalList : permutations) {
        result.add(new ArrayList<>(internalList));
    }

    return result;
}

From source file:Days.Day09.java

@Override
public void run() throws Exception {
    {/*from  ww  w.j  av  a 2 s  . c  om*/
        // get input file
        File f = getInput();
        String test = "London to Dublin = 464\n" + "London to Belfast = 518\n" + "Dublin to Belfast = 141\n";
        Scanner sc = new Scanner(f);

        while (sc.hasNext()) {
            String from = sc.next(); // van-stad bepalen
            sc.next();
            String to = sc.next(); // naar-stad bepalen
            sc.next();
            int distance = Integer.parseInt(sc.next()); // afstand bepalen

            // afstand bidirectioneel toevoegen aan distances (ongerichte graaf)
            distances.put(from + to, distance);
            distances.put(to + from, distance);

            // alle unieke steden toevoegen aan locations
            if (!locations.contains(from)) {
                locations.add(from);
            }
            if (!locations.contains(to)) {
                locations.add(to);
            }
        }
    }

    int min = 9999; // stel een hoge waarde als eerste minimum, geen zin om extra code te schrijven
    int max = 0;
    for (List<String> perm : Collections2.permutations(locations)) {
        int distance = 0; // init afstand
        for (int i = 0; i < perm.size() - 1; i++) {
            distance += distances.get(perm.get(i) + perm.get(i + 1)); // voeg de afstand tussen 2 intermediaire locaties toe
        }
        if (distance < min) { // afstand is kleiner dan huidig minimum
            min = distance;
        }
        if (distance > max) { // afstand is groter dan huidig maximum
            max = distance;
        }
    }

    System.out.println(min);
    System.out.println(max);
}

From source file:Days.Day13.java

@Override
public void run() throws Exception {
    {/*  w  ww. j a v  a  2s.  c o m*/
        // get input file
        File f = getInput();
        Scanner sc = new Scanner(f);

        while (sc.hasNext()) {
            String[] line = sc.nextLine().split(" ");
            String from = line[0]; // van-persoon bepalen
            boolean positive = line[2].equals("gain");
            int happyness = Integer.parseInt(line[3]); // waarde bepalen
            if (!positive) {
                happyness *= -1;
            }
            String to = line[10]; // naar-persoon bepalen
            to = to.substring(0, to.length() - 1); // leesteken verwijderen

            // afstand directioneel toevoegen aan distances (gerichte graaf)
            modifiers.put(from + to, happyness);

            if (!personen.contains("me")) {
                personen.add("me");
            }
            // alle unieke steden toevoegen aan locations
            if (!personen.contains(from)) {
                personen.add(from);
                modifiers.put("me" + from, 0);
                modifiers.put(from + "me", 0);
            }
            if (!personen.contains(to)) {
                personen.add(to);
                modifiers.put("me" + to, 0);
                modifiers.put(to + "me", 0);
            }
        }
    }

    int min = 9999; // stel een hoge waarde als eerste minimum, geen zin om extra code te schrijven
    int max = 0;
    for (List<String> perm : Collections2.permutations(personen)) {
        int distance = 0; // init afstand
        for (int i = 0; i < perm.size() - 1; i++) {
            distance += modifiers.get(perm.get(i) + perm.get(i + 1)); // voeg de afstand tussen 2 intermediaire locaties toe
            distance += modifiers.get(perm.get(i + 1) + perm.get(i));
        }
        distance += modifiers.get(perm.get(0) + perm.get(perm.size() - 1));
        distance += modifiers.get(perm.get(perm.size() - 1) + perm.get(0));
        if (distance < min) { // afstand is kleiner dan huidig minimum
            min = distance;
        }
        if (distance > max) { // afstand is groter dan huidig maximum
            max = distance;
        }
    }

    System.out.println(min);
    System.out.println(max);
}

From source file:io.crate.planner.consumer.ManyTableConsumer.java

/**
 * returns a new collection with the same items as relations contains but in an order which
 * allows the most join condition push downs (assuming that a left-based tree is built later on)
 *
 * @param relations               all relations, e.g. [t1, t2, t3, t3]
 * @param implicitJoinedRelations contains all relations that have a join condition e.g. {{t1, t2}, {t2, t3}}
 * @param joinPairs               contains a list of {@link JoinPair}.
 * @param preSorted               a ordered subset of the relations. The result will start with those relations.
 *                                E.g. [t3] - This would cause the result to start with [t3]
 *//*from  w w w .  j a va  2s  .co m*/
static Collection<QualifiedName> orderByJoinConditions(Collection<QualifiedName> relations,
        Set<? extends Set<QualifiedName>> implicitJoinedRelations, List<JoinPair> joinPairs,
        Collection<QualifiedName> preSorted) {
    if (preSorted.isEmpty()) {
        return relations;
    }
    if (relations.size() == preSorted.size()) {
        return preSorted;
    }
    if (relations.size() == 2 || (joinPairs.isEmpty() && implicitJoinedRelations.isEmpty())) {
        LinkedHashSet<QualifiedName> qualifiedNames = new LinkedHashSet<>(preSorted);
        qualifiedNames.addAll(relations);
        return qualifiedNames;
    }

    // Create a Copy to ensure equals works correctly for the subList check below.
    preSorted = ImmutableList.copyOf(preSorted);
    Set<QualifiedName> pair = new HashSet<>(2);
    Set<QualifiedName> outerJoinRelations = JoinPairs.outerJoinRelations(joinPairs);
    Collection<QualifiedName> bestOrder = null;
    int best = -1;
    outerloop: for (List<QualifiedName> permutation : Collections2.permutations(relations)) {
        if (!preSorted.equals(permutation.subList(0, preSorted.size()))) {
            continue;
        }
        int joinPushDowns = 0;
        for (int i = 0; i < permutation.size() - 1; i++) {
            QualifiedName a = permutation.get(i);
            QualifiedName b = permutation.get(i + 1);

            JoinPair joinPair = JoinPairs.ofRelations(a, b, joinPairs, false);
            if (joinPair == null) {
                // relations are not directly joined, lets check if they are part of an outer join
                if (outerJoinRelations.contains(a) || outerJoinRelations.contains(b)) {
                    // part of an outer join, don't change pairs, permutation not possible
                    continue outerloop;
                } else {
                    pair.clear();
                    pair.add(a);
                    pair.add(b);
                    joinPushDowns += implicitJoinedRelations.contains(pair) ? 1 : 0;
                }
            } else {
                // relations are directly joined
                joinPushDowns += 1;
            }
        }
        if (joinPushDowns == relations.size() - 1) {
            return permutation;
        }
        if (joinPushDowns > best) {
            best = joinPushDowns;
            bestOrder = permutation;
        }
    }
    if (bestOrder == null) {
        bestOrder = relations;
    }
    return bestOrder;
}

From source file:mvm.rya.indexing.IndexPlanValidator.TupleExecutionPlanGenerator.java

private List<TupleExpr> getPlans(TupleExpr te) {

    NodeCollector nc = new NodeCollector();
    te.visit(nc);/*  www  . j a v a  2  s.co  m*/

    Set<QueryModelNode> nodeSet = nc.getNodeSet();
    List<Filter> filterList = nc.getFilterSet();
    Projection projection = nc.getProjection().clone();

    List<TupleExpr> queryPlans = Lists.newArrayList();

    Collection<List<QueryModelNode>> plans = Collections2.permutations(nodeSet);

    for (List<QueryModelNode> p : plans) {
        if (p.size() == 0) {
            throw new IllegalArgumentException("Tuple must contain at least one node!");
        } else if (p.size() == 1) {
            queryPlans.add(te);
        } else {
            queryPlans.add(buildTuple(p, filterList, projection));
        }
    }

    return queryPlans;
}

From source file:org.apache.rya.indexing.IndexPlanValidator.TupleExecutionPlanGenerator.java

private List<TupleExpr> getPlans(final TupleExpr te) {

    final NodeCollector nc = new NodeCollector();
    te.visit(nc);/* ww w  .j a v  a2 s .  c  o m*/

    final Set<QueryModelNode> nodeSet = nc.getNodeSet();
    final List<Filter> filterList = nc.getFilterSet();
    final Projection projection = nc.getProjection().clone();

    final List<TupleExpr> queryPlans = Lists.newArrayList();

    final Collection<List<QueryModelNode>> plans = Collections2.permutations(nodeSet);

    for (final List<QueryModelNode> p : plans) {
        if (p.size() == 0) {
            throw new IllegalArgumentException("Tuple must contain at least one node!");
        } else if (p.size() == 1) {
            queryPlans.add(te);
        } else {
            queryPlans.add(buildTuple(p, filterList, projection));
        }
    }

    return queryPlans;
}

From source file:com.rockhoppertech.music.examples.Guava.java

public static void permute() {
    List<Integer> numz = Lists.newArrayList(1, 2, 3);
    Collection<List<Integer>> perms = Collections2.permutations(numz);
    for (List<Integer> p : perms) {
        System.out.println(p);// w ww.  j a va  2  s. c o m
    }

    // Collections2.orderedPermutations(elements, comparator)
}

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

/**
 * Get all possible orderings of fragments
 *//*from  w  w  w .ja v  a 2s  .  c  o m*/
Set<List<Fragment>> allFragmentOrders() {
    Collection<List<EquivalentFragmentSet>> fragmentSetPermutations = Collections2
            .permutations(equivalentFragmentSets);
    return fragmentSetPermutations.stream().flatMap(ConjunctionQuery::cartesianProduct).collect(toSet());
}

From source file:edu.cornell.cs.nlp.spf.genlex.ccg.template.GenerationRepository.java

public boolean addTemplate(LexicalTemplate template) {
    if (!templates.contains(template)) {
        LOG.debug("Trying to add template: %s", template);
        // First verify that we really need this template. There's an
        // existing issue with spurious ambiguity in factoring. This fix
        // is a brute-force hack to try to suppress it when using GENLEX.
        // When there are many templates, this process is going to explode
        final Iterator<LexicalTemplate> iterator = templates.iterator();
        while (iterator.hasNext()) {
            final LexicalTemplate existingTemplate = iterator.next();
            final int numAttributes = existingTemplate.getSignature().getNumAttributes();
            if (numAttributes == template.getSignature().getNumAttributes() && existingTemplate.getSignature()
                    .getTypes().size() == template.getSignature().getTypes().size()) {
                // Create dummy attributes list.
                final List<String> dummyAttributes = new ArrayList<String>(numAttributes);
                for (int i = 0; i < numAttributes; ++i) {
                    dummyAttributes.add("dummy" + i);
                }//from w  ww.  ja v  a  2 s  .c  om
                for (final List<LogicalConstant> permutation : Collections2
                        .permutations(template.getArguments())) {
                    // Create a dummy lexeme.
                    final Lexeme dummy = new Lexeme(TokenSeq.of(), permutation, dummyAttributes);
                    if (existingTemplate.isValid(dummy)) {
                        final Category<LogicalExpression> application = existingTemplate.apply(dummy);
                        if (application != null && application.equals(template
                                .apply(new Lexeme(TokenSeq.of(), template.getArguments(), dummyAttributes)))) {
                            // Skip adding this template.
                            LOG.debug("Ignoring template (spurious ambiguity): %s", template);
                            LOG.debug("... detected duplicate of: %s", existingTemplate);
                            return false;
                        }
                    }
                }
            }
        }
        LOG.info("Adding new template to generation repository (%d constants, %d attributes): %s",
                template.getArguments().size(), template.getSignature().getNumAttributes(), template);
        templates.add(template);
        if (signatures.add(template.getSignature())
                && !arrityAndAttributes.containsKey(template.getSignature().getNumAttributes())) {
            arrityAndAttributes.put(template.getSignature().getNumAttributes(),
                    createAttributePermutations(template.getSignature().getNumAttributes()));
        }

        templatesAndAttributes.put(template,
                Collections.unmodifiableList(createAllAttributesPermutations(template)));
        return true;
    }

    return false;
}

From source file:edu.cornell.cs.nlp.spf.genlex.ccg.template.GenerationRepository.java

/**
 * Create all attribute permutations that can be used (within a lexeme) to
 * initialize this template.//w  ww . java2  s . c  o m
 */
private List<List<String>> createAllAttributesPermutations(LexicalTemplate template) {
    if (template.getSignature().getNumAttributes() == 0) {
        return ListUtils.createSingletonList(Collections.<String>emptyList());
    }

    final List<List<String>> attributePermutations = new LinkedList<List<String>>();
    for (final List<String> subset : new PowerSetWithFixedSize<String>(attributes,
            template.getSignature().getNumAttributes())) {
        // Create all permutations of this subset of attributes.
        for (final List<String> permutation : Collections2.permutations(subset)) {
            if (template.apply(new Lexeme(TokenSeq.of(), template.getArguments(), permutation)) != null) {
                attributePermutations.add(Collections.unmodifiableList(permutation));
            }
        }
    }
    return attributePermutations;
}