001    package com.hammurapi.reasoning.impl;
002    
003    import java.util.ArrayList;
004    import java.util.Collection;
005    import java.util.Iterator;
006    
007    import com.hammurapi.convert.ConvertingService;
008    import com.hammurapi.reasoning.spi.Superseder;
009    
010    /**
011     * Compacts collections of facts by removing facts superseded
012     * by other facts in the collection. 
013     * @author Pavel Vlasov
014     *
015     */
016    public class KnowledgeCompactor {
017    
018            @SuppressWarnings("unchecked")
019            static <F> Collection<F> compact(Collection<F> input) {
020                    F[] elements = (F[]) new Object[input.size()];
021                    Iterator<F> it = input.iterator();
022                    for (int i=0; it.hasNext(); ++i) {
023                            elements[i] = it.next();
024                    }
025                    
026                    for (int i=0; i<elements.length; ++i) {
027                            if (elements[i]!=null) {
028                                    Superseder superseder = ConvertingService.convert(elements[i], Superseder.class);
029                                    if (superseder!=null) {
030                                            for (int j=0; j<elements.length; ++j) {
031                                                    if (j!=i && elements[j]!=null && superseder.supersedes(elements[j])) {
032                                                            elements[j] = null;
033                                                    }
034                                            }
035                                    }
036                            }
037                    }
038                    
039                    Collection<F> ret = new ArrayList<F>();
040                    for (F element: elements) {
041                            if (element!=null) {
042                                    ret.add(element);
043                            }
044                    }
045                    return ret;
046            }
047    }