CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Knapsack with twist

  1. #1
    Join Date
    Dec 2015

    Knapsack with twist

    I'm doing a Knapsack in Java where we only use weights no value. The weightlimit is 1000. We get 5 weights scanned from keyboard which we use.
    The twist is that you can actually go over 1000 aslong as its the closets to 1000. So in one scenario we have 2 possible weights 990 and 1010 and the program is suposed to pick the higher one.
    The scanned numbers can never be higher then 1000.
        package kapsackidone;
        import java.util.Scanner;
        import java.io.BufferedReader;
        import java.io.InputStreamReader;
        import java.io.*;
        public class Kapsack {
        public static void main(String[] args) throws Exception {
        	BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
        	int [] wt=new int[5];
        	int W = 1000;
        	System.out.println("Enter Weight 5 weights");
        	for(int i=0; i<5; i++)
            System.out.println(knapsack(wt, W));
        public static int knapsack(int wt[], int W) {
            int N = wt.length;
            int[][] V = new int[N + 1][W + 1];
            for (int col = 0; col <= W; col++) {
                V[0][col] = 0;
            for (int row = 0; row <= N; row++) {
                V[row][0] = 0;
            for (int item=1;item<=N;item++){
            for (int weight=1;weight<=W;weight++){
                if(wt[item-1] > weight)
                    V[item][weight] = V[item-1][weight];
                else if((weight - V[item-1][weight]) < (weight - (V[item-1][weight - wt[item-1]] + wt[item-1])))
                    V[item][weight] = V[item-1][weight];
                    V[item][weight] = V[item-1][weight - wt[item-1]] + wt[item-1];
            return V[N][W];
    I am really struggling with how I can get this done.
    Before you ask no its not homework im gonna be a project manager for a new group of people that consist of developers so im just trying to learn some java so that i understand a

  2. #2
    Join Date
    Jun 1999
    Eastern Florida

    Re: Knapsack with twist

    trying to learn some java
    Do you have any specific java programming questions? In other words, you have a detailed design for the program with a number of steps and you don't know how to code some of the steps.
    Post the step(s) you are having problems with coding in java.

    Or is your problem with doing a design for the program? Not a java coding problem.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)