All Downloads are FREE. Search and download functionalities are using the official Maven repository.

edu.cmu.sv.utils.Combination Maven / Gradle / Ivy

Go to download

A library that allows rapid prototyping of dialog systems (language understanding, discourse modelling, dialog management, language generation).

There is a newer version: 0.7.0
Show newest version
package edu.cmu.sv.utils;

import org.apache.commons.math3.random.RandomData;
import org.apache.commons.math3.random.RandomDataImpl;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by David Cohen on 9/2/14.
 */
public class Combination {

    static RandomData randomData = new RandomDataImpl();

    public static  Set randomSubset(Collection items, int k){
        if (items.size() > k){
            return Arrays.asList(randomData.nextSample(
                    items, k)).stream().
                    map(x -> (T)x).
                    collect(Collectors.toSet());
        }
        else
            return new HashSet<>(items);
    }

    public static  Set> combinations(Set items){
        Set> ans = new HashSet<>();
        if (items.size()==1) {
            ans.add(new LinkedList(items));
            return ans;
        } else if (items.size()==0){
            return ans;
        }
        T item = new LinkedList<>(items).get(0);
        items.remove(item);
        for (List subList : combinations(items)){
            subList.add(item);
            ans.add(subList);
        }
        return ans;
    }

    public static  Set> possibleBindings(Map> keysAndValues){
        Set> ans = new HashSet<>();
        if (keysAndValues.size()==0){
            ans.add(new HashMap());
            return ans;
        }
        S key = new LinkedList<>(keysAndValues.keySet()).get(0);
        Set values = keysAndValues.get(key);
        keysAndValues.remove(key);
//        System.out.println("Combination.possibleBindings: key, values" + key + ", " + values);
        for (Map partialBinding : possibleBindings(keysAndValues)){
//            System.out.println("nested partial binding returned" + partialBinding);
            for (T value : values){
                Map extendedBinding = new HashMap<>(partialBinding);
                extendedBinding.put(key, value);
                ans.add(extendedBinding);
            }
        }
        return ans;
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy