java - Array List .get() not working correctly -
i'm implementing greedy algorithm solve knapsack problem, , keep running issue can't figure out.
public void greedysort() { int curw = 0; collections.sort(sorted); for(int = 0; < sorted.size(); i++) { entry temp = sorted.get(i); system.out.println("index: " + temp.index + "ratio: " + temp.ratio); } system.out.println("sorted size: "+sorted.size()); while(sorted.size() > 0 && curw < maxw) { entry temp = sorted.get(0); if(curw + temp.weight <= maxw) { ret.add(temp); curw += temp.weight; } sorted.remove(0); } }
when run the
entry temp = sorted.get(0);
i indexoutofboundsexception, though loop after collections.sort(sorted) iterate through "sorted" correctly , print out values in right order. doing wrong? also, if see errors algorithm design within code, let me know those.
edit: added sorted.size println. prints 20, should. sorted arraylist of knapsack entries sorted value/weight ratio. sorted not empty, here output after running 20 value input file through
index: 14 ratio: 14.0 index: 0 ratio: 3.1379310344827585 index: 15 ratio: 2.7 index: 4 ratio: 1.7555555555555555 index: 17 ratio: 1.72 index: 19 ratio: 1.4210526315789473 index: 8 ratio: 1.3333333333333333 index: 18 ratio: 1.2195121951219512 index: 11 ratio: 1.2 index: 1 ratio: 0.9230769230769231 index: 9 ratio: 0.9230769230769231 index: 6 ratio: 0.8636363636363636 index: 2 ratio: 0.8591549295774648 index: 12 ratio: 0.6530612244897959 index: 5 ratio: 0.647887323943662 index: 16 ratio: 0.6111111111111112 index: 7 ratio: 0.5876288659793815 index: 10 ratio: 0.3508771929824561 index: 13 ratio: 0.34831460674157305 index: 3 ratio: 0.15 sorted size: 20 exception in thread "main" java.lang.indexoutofboundsexception: index: 0, size: 0
sorted created here using values given function driver
public void greedy(int[] val, int[] weight, int maxval) { final long starttime = system.currenttimemillis(); greedyalgorithm alg = new greedyalgorithm(); alg.sorted = new arraylist<entry>(); alg.ret = new arraylist<entry>(); alg.maxw = maxval; for(int = 0; < val.length; i++) { entry newe = new entry(); newe.index = i; newe.value = val[i]; newe.weight = weight[i]; newe.ratio = ((double)newe.value)/((double)newe.weight); alg.sorted.add(newe); } alg.greedysort(); final long endtime = system.currenttimemillis(); system.out.println("total execution time: " + (endtime - starttime) ); }
as previous commenter pointed out, keep removing first element in arraylist. time iterate through 20 elements, have removed in arraylist.
so make sure end loop when list empty. change while condition this:
while(sorted.size() > 0 && curw < maxw) { // put print line inside loop debug. system.out.println("sorted size: "+sorted.size()); entry temp = sorted.get(0); if(curw + temp.weight <= maxw) { ret.add(temp); curw += temp.weight; } sorted.remove(0); }
Comments
Post a Comment