Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package il.ac.tau.cs.sw1.ex7;
- import java.util.*;
- public class FractionalKnapSack implements Greedy<FractionalKnapSack.Item>{
- int capacity;
- List<Item> lst;
- FractionalKnapSack(int c, List<Item> lst1){
- capacity = c;
- lst = lst1;
- }
- public static class Item {
- double weight, value;
- Item(double w, double v) {
- weight = w;
- value = v;
- }
- @Override
- public String toString() {
- return "{" + "weight=" + weight + ", value=" + value + '}';
- }
- }
- public class ItemComparator implements Comparator<Item> {
- @Override
- public int compare(Item item1, Item item2) {
- double item1RelativeValue = item1.value / item1.weight;
- double item2RelativeValue = item2.value / item2.weight;
- return Double.compare(item2RelativeValue, item1RelativeValue);
- }
- }
- public double weightSum(List<Item> candidates_lst) {
- double weightSum = 0;
- for (Item item: candidates_lst) {
- weightSum += item.weight;
- }
- return weightSum;
- }
- @Override
- public Iterator<Item> selection() {
- ArrayList<Item> items = new ArrayList<Item>(); // empty list of items
- for (Item item: this.lst) { // add items
- items.add(item);
- }
- ItemComparator comp = new ItemComparator();
- Collections.sort(items, comp); // descending order
- return items.iterator(); // return iterator
- }
- @Override
- public boolean feasibility(List<Item> candidates_lst, Item element) {
- return this.capacity > weightSum(candidates_lst);
- }
- @Override
- public void assign(List<Item> candidates_lst, Item element) {
- if (weightSum(candidates_lst) + element.weight <= this.capacity) {
- candidates_lst.add(element);
- }
- else {
- double partial_weight = this.capacity - weightSum(candidates_lst);
- Item partialItem = new Item(partial_weight, element.value);
- candidates_lst.add(partialItem);
- }
- }
- @Override
- public boolean solution(List<Item> candidates_lst) {
- return this.capacity == weightSum(candidates_lst);
- }
- public static void main(String[] args) {
- Item item1 = new Item(30, 120);
- Item item2 = new Item(20, 100);
- Item item3 = new Item(10, 60);
- List<Item> items = new ArrayList<Item>();
- items.add(item1);
- items.add(item2);
- items.add(item3);
- FractionalKnapSack sack = new FractionalKnapSack(50, items);
- System.out.println(sack.greedyAlgorithm().toString());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement