package org.tallison.lucene.syns;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TopNList<E extends Valuable> {
private List<E> list = null;
private int max = -1;
private ValueComparator comp = null;
public TopNList(int max){
this(max, new DescendingValueComparator());
}
private TopNList(int max, ValueComparator comp){
this.max = max;
this.comp = comp;
list = new ArrayList<E>(max);
}
public double bottomValue(){
if (list.size() == 0){
return Double.MIN_VALUE;
}
return list.get(list.size()-1).getValue();
}
public boolean willAdd(Valuable newObj){
if (list.size() < max)
return true;
return comp.compare(newObj, list.get(list.size() - 1)) < 0;
}
public void add(E newObj){
if (list.size() == max){
if (comp.compare(newObj, list.get(list.size()-1)) >= 0){
return;
}
}
int insert = -1;
//this could be sped up with binary search
for (int i = 0; i < list.size(); i++){
if (comp.compare(newObj, list.get(i)) < 0){
insert = i;
break;
}
}
insert = (insert < 0) ? list.size() : insert;
list.add(insert, newObj);
if (list.size() > max)
list.remove(max);
}
public List<E> getList(){
return list;
}
public String toString(){
return list.toString();
}
public static void main(String[] args){
//def m = [ 'cat' : 4, 'bison' : 5, 'dog' : 6,
//'aardvark' : 15, 'the' : 120, 'a' : 50, 'centipede' : 1]
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("z", 150);
m.put("y", 115);
m.put("x", 110);
m.put("cat2", 4);
m.put("bison", 5);
m.put("dog",6);
m.put("aardvark",15);
m.put("the",120);
TopNList<TermDoublePair> list = new TopNList<TermDoublePair>(3, new DescendingValueComparator());
for (Map.Entry<String, Integer> e : m.entrySet()){
System.out.println("adding " + e.getKey() + " " +e.getValue());
list.add(new TermDoublePair(e.getKey(), e.getValue()));
}
System.out.println(list);
}
}