The algorithm to remember to split the parcel once

Source: Internet
Author: User

As the company sells goods from the manufacturers to take over the time are packed into boxes, the specifications are as follows: Large packaging 50, packaging 30, small packaging 10. When users buy, the number may be 70, 60 or 5 of such data, so there is the need to split the package.

First of all, how do we have to dismantle to try to avoid unpacking? In principle, priority is given to large packaging, the last small package, that is, from large to small to unpack.

For example, the user purchased 80, can be split into 50*1+30*1+10*0, if the number of users to buy is 62? It can be split into 50*1+30*0+10*1+1*2.

Understand how to disassemble, began to write code, from the above analysis, we can see that the actual algorithm is used: (Purchase quantity-(Purchase quantity% packing unit))/packing unit, until the packing position is 1,

The following is no nonsense, directly write the core code:

public class Main {static list<integer> unitlist;        static {unitlist = new ArrayList ();        Unitlist.add (1);        Unitlist.add (10);        Unitlist.add (30);    Unitlist.add (50);             } public static void Main (string[] args) {Unitlist.sort (Comparator.reverseorder ());           Splitpack (unitlist); } public static void Splitpack (int count, list<integer> List) {map<integer, integer> Map = new Link        Edhashmap<> (); for (Integer currentunit:list) {if (count% Currentunit = = 0) {map.put (Currentunit, Count/                Currentunit);            Break                } else {int packagecount = (count-(count% currentunit))/currentunit;                Map.put (Currentunit, Packagecount);            Count = Count-currentunit * PACKAGECOUNT;    }} map.entryset (). ForEach (X-System.out.println (X.getkey () + "=" + X.getvalue ())); }}

Output Result:

50=1
30=0
10=1
1=2

That is, 50 a box, there are 1, 30 a box of 0, 10 a box of 1, a single package has 2.

The algorithm to remember to split the parcel once

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.