Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8692103
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T00:15:11+00:00 2026-06-13T00:15:11+00:00

I have to implement the following variation of the knapsack problem. Each item for

  • 0

I have to implement the following variation of the knapsack problem. Each item for the knapsack has a priority and a weight. Now I specify a weight X. I must know compute the smallest set of items of which the sum of weight is at least X and have the lowest priority. Each item can only chosen once. Example:

    KnapsackItem a = new KnapsackItem("a", 1000, 0.1);
    KnapsackItem b = new KnapsackItem("b", 1000, 0.01);
    KnapsackItem c = new KnapsackItem("c", 1000, 0.01);

    Knapsack sack = new Knapsack(1900);
    sack.addItem(a);
    sack.addItem(b);
    sack.addItem(c);

    for (KnapsackItem item : sack.compute()) {
        System.out.println(item);
    }

This should return b,c.

My solution returns b, a. I don’t know why. Spent hours debugging, but I just don’t get it. Maybe someone can have a look or post a solution of this problem variation as code.

public class Knapsack {
/**
 * The sum of the priorities. For example "prisoSum.get(2) returns 5" means,
 * that element 2 returns a sum priority of 5.
 */
private HashMap<Integer, Double> prioSum = new HashMap<Integer, Double>();

/**
 * List of items.
 */
private ArrayList<KnapsackItem> items;

/**
 * Minimum weight. The sum of the weights of the items in the item list must
 * at least be equal to this value.
 */
private int minWeight;

/**
 * Constructor.
 *
 * @param minWeight
 *            the minimum weight.
 */
public Knapsack(final int minWeight) {
    this.items = new ArrayList<KnapsackItem>();
    this.minWeight = minWeight;
}

/**
 * Computes the items to select.
 *
 * @return list of items to select.
 */
public final ArrayList<KnapsackItem> compute() {
    ArrayList<KnapsackItem> ret = new ArrayList<KnapsackItem>();
    int weightLeft = this.minWeight;
    KnapsackItem item;

    while (weightLeft > 0) {
        ArrayList<KnapsackItem> diff = getDifference(this.items, ret);
        if (diff.size() == 0) {
            break;
        }

        item = computeBestItemForMinVal(diff,
                weightLeft);

        ret.add(item);
        weightLeft -= item.getWeight();
    }

    return ret;
}

/**
 * Gets the best item to select for a given weight.
 *
 * @param list
 *            List of items to select form
 * @param minVal
 *            given weight
 * @return best item from list for given weight
 */
private KnapsackItem computeBestItemForMinVal(
        final ArrayList<KnapsackItem> list, final int minVal) {
    int[] best = new int[minVal + 1];
    for (int w = 0; w <= minVal; w++) {
        for (int i = 0; i < list.size(); i++) {
            KnapsackItem curIt = list.get(i);

            // Current priority inclusive all antecessors
            double curVal = 0;
            if (prioSum.get(w - curIt.getWeight()) != null) {
                curVal = prioSum.get(w - curIt.getWeight())
                        + curIt.getPriority();
            } else {
                curVal = 0 + curIt.getPriority();
            }
            if (prioSum.get(w) == null) {
                prioSum.put(w, curVal);
                best[w] = i;
            } else if (prioSum.get(w) > curVal) {
                prioSum.put(w, curVal);
                best[w] = i;
            }
        }
    }
    return list.get(best[minVal]);
}

/**
 * Computes the difference between two given list of Knapsack items and
 * returns it.
 *
 * @param main
 *            first list
 * @param sub
 *            second list
 * @return difference
 */
private ArrayList<KnapsackItem> getDifference(
        final ArrayList<KnapsackItem> main,
        final ArrayList<KnapsackItem> sub) {
    ArrayList<KnapsackItem> ret = new ArrayList<KnapsackItem>();

    for (int m = 0; m < main.size(); m++) {

        boolean found = false;
        for (int s = 0; s < sub.size(); s++) {
            if (main.get(m).getName() == sub.get(s).getName()) {
                found = true;
                break;
            }
        }

        if (!found) {
            ret.add(main.get(m));
        }
    }

    return ret;
}

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T00:15:12+00:00Added an answer on June 13, 2026 at 12:15 am

    I found my mistake. I have to add
    prioSum.clear();

    to computeBestItemForMinVal(). So the data of the previous calls gets deleted.
    I also start the for-loop for weight now at 1, not at 0:

    private KnapsackItem computeBestItemForMinVal(
            final ArrayList<KnapsackItem> list, final int minVal) {
        int[] best = new int[minVal + 1];
        prioSum.clear();
        for (int w = 1; w <= minVal; w++) {
    ...
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class which must implement the following property public ICollection<IType> Items {
I have to implement a wrapper for malloc called mymalloc with the following signature:
I would like to implement the following behaviour: I have a special media player,
I have an iPhone application and I need to implement the following method: +(UITextView
Hey all. I have a question on how to implement the following with Django.
I have the following assignment: Implement a basic shopping basket without using any predefined
I'm following this how-to to implement Core Data storage in my app: I have
I'm wondering why I have never seen the following way to implement templates in
I'm trying to write a user name validation that has the following restrictions: Must
So we have a PHP+Zend Framework+Doctrine 1.2 application that has the following structure: Controller

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.