Download the PHP package mistralys/subsetsum without Composer
On this page you can find all versions of the php package mistralys/subsetsum. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download mistralys/subsetsum
More information about mistralys/subsetsum
Files in mistralys/subsetsum
Package subsetsum
Short Description PHP SubsetSum implementation to search for number combinations.
License MIT
Informations about the package subsetsum
PHP SubsetSum implementation
Given a target number and a list of numbers, determines which number combinations equal the target number.
For example: With 25
as the target number, and 10
, 5
, 15
as the numbers list, this will determine that 25 = 10 + 15
.
Requirements
- PHP >= 7.1
- BCMath extension
Installation
Require the package via composer on the command line:
Or edit composer.json directly:
Usage
The create
method is used to create a new instance, which can be used to retrieve matches, or to configure options:
Checking if there are any matches
Some methods like getShortestMatch()
can return null, so it's best to check if there are matches beforehand.
Getting all matches
To retrieve all matching number combinations:
This will return an array like this:
NOTE: The numbers in each match result are always sorted in ascending order.
Getting the shortest match
The shortest match is the one that uses the least amount of number combinations.
In the example, this would return the following match array:
Getting the longest match
The longest match is the one that uses the highest amount of number combinations.
In the example, this would return the following match array:
Adjusting the amount of decimals & rounding
By default, the internal calculations will round the numbers to 2
decimals, using PHP's default "round up half" rounding. This can be easily adjusted to your needs:
The full list of possible modes can be found here:
http://www.php.net/manual/en/math.constants.php
Working with integers
Working in integer mode simply means using a precision of 0
.
NOTE: The match arrays will contain integers, but which are still typed as floats. You will have to cast them to int
as needed.
Performance
A word of caution: calculating subset sums has an exponential complexity the higher the amount of numbers to search through. You can easily bring your server to your knees with larger sets, so I would recommend setting some limits on the amount of numbers in your application.
Credits
The initial mechanism was inspired by this answer on StackOverflow:
There is also another interesting package that goes further than this:
All versions of subsetsum with dependencies
ext-bcmath Version *