search
HomeJavajavaTutorialExample analysis of how to implement knapsack algorithm in Java

This article mainly introduces a brief introduction to the implementation of the knapsack algorithm (0-1 knapsack problem) in java. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

0-1 Knapsack problem

The Knapsack problem is an NP-complete problem of combinatorial optimization. The problem can be described as: given a set of items, each item has its own weight and price, within the limited total weight, how do we choose so that the total price of the items is the highest. The name of the problem comes from how to choose the most appropriate item to place in a given backpack.

This is the most basic backpack problem. Its characteristics are: there is only one item of each type, and you can choose to put it or not.

Use sub-problems to define the state: that is, f[i][v] represents the maximum value that can be obtained by putting the first i items into a backpack with a capacity of v. Then its state transition equation is:

f[i][v]=max{ f[i-1][v], f[i-1][v-w[i]]+v[i ] }.


public class Bag {

  static class Item {// 定义一个物品
    String id; // 物品id
    int size = 0;// 物品所占空间
    int value = 0;// 物品价值

    static Item newItem(String id, int size, int value) {
      Item item = new Item();
      item.id = id;
      item.size = size;
      item.value = value;
      return item;
    }

    public String toString() {
      return this.id;
    }
  }

  static class OkBag { // 定义一个打包方式
    List<Item> Items = new ArrayList<Item>();// 包里的物品集合

    OkBag() {
    }

    int getValue() {// 包中物品的总价值
      int value = 0;
      for (Item item : Items) {
        value += item.value;
      }
      return value;
    };

    int getSize() {// 包中物品的总大小
      int size = 0;
      for (Item item : Items) {
        size += item.size;
      }
      return size;
    };

    public String toString() {
      return String.valueOf(this.getValue()) + " ";
    }
  }

  // 可放入包中的备选物品
  static Item[] sourceItems = { Item.newItem("4号球", 4, 5), Item.newItem("5号球", 5, 6), Item.newItem("6号球", 6, 7) };
  static int bagSize = 10; // 包的空间
  static int itemCount = sourceItems.length; // 物品的数量

  // 保存各种情况下的最优打包方式 第一维度为物品数量从0到itemCount,第二维度为包裹大小从0到bagSize
  static OkBag[][] okBags = new OkBag[itemCount + 1][bagSize + 1];

  static void init() {
    for (int i = 0; i < bagSize + 1; i++) {
      okBags[0][i] = new OkBag();
    }

    for (int i = 0; i < itemCount + 1; i++) {
      okBags[i][0] = new OkBag();
    }
  }

  static void doBag() {
    init();
    for (int iItem = 1; iItem <= itemCount; iItem++) {
      for (int curBagSize = 1; curBagSize <= bagSize; curBagSize++) {
        okBags[iItem][curBagSize] = new OkBag();
        if (sourceItems[iItem - 1].size > curBagSize) {// 当前物品大于包空间.肯定不能放入包中.
          okBags[iItem][curBagSize].Items.addAll(okBags[iItem - 1][curBagSize].Items);
        } else {
          int notIncludeValue = okBags[iItem - 1][curBagSize].getValue();// 不放当前物品包的价值
          int freeSize = curBagSize - sourceItems[iItem - 1].size;// 放当前物品包剩余空间
          int includeValue = sourceItems[iItem - 1].value + okBags[iItem - 1][freeSize].getValue();// 当前物品价值+放了当前物品后剩余包空间能放物品的价值
          if (notIncludeValue < includeValue) {// 放了价值更大就放入.
            okBags[iItem][curBagSize].Items.addAll(okBags[iItem - 1][freeSize].Items);
            okBags[iItem][curBagSize].Items.add(sourceItems[iItem - 1]);
          } else {// 否则不放入当前物品
            okBags[iItem][curBagSize].Items.addAll(okBags[iItem - 1][curBagSize].Items);
          }
        }

      }
    }
  }

  public static void main(String[] args) {
    Bag.doBag();
    for (int i = 0; i < Bag.itemCount + 1; i++) {// 打印所有方案中包含的物品
      for (int j = 0; j < Bag.bagSize + 1; j++) {
        System.out.print(Bag.okBags[i][j].Items);
      }
      System.out.println("");
    }

    for (int i = 0; i < Bag.itemCount + 1; i++) {// 打印所有方案中包的总价值
      for (int j = 0; j < Bag.bagSize + 1; j++) {
        System.out.print(Bag.okBags[i][j]);
      }
      System.out.println("");
    }

    OkBag okBagResult = Bag.okBags[Bag.itemCount][Bag.bagSize];
    System.out.println("最终结果为:" + okBagResult.Items.toString() + okBagResult);

  }

}

The above is the detailed content of Example analysis of how to implement knapsack algorithm in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),