For details read Perl NOC. After June 25

Alexander Anderson >
Algorithm-Knapsack >
Algorithm::Knapsack

Module Version: 0.02
Algorithm::Knapsack - brute-force algorithm for the knapsack problem

use Algorithm::Knapsack; my $knapsack = Algorithm::Knapsack->new( capacity => $capacity, weights => \@weights, ); $knapsack->compute(); foreach my $solution ($knapsack->solutions()) { foreach my $index (@{$solution}) { # do something with $weights[$index] } }

The knapsack problem asks, given a set of items of various weights, find a subset or subsets of items such that their total weight is no larger than some given capacity but as large as possible.

This module solves a special case of the 0-1 knapsack problem when the value of each item is equal to its weight. Capacity and weights are restricted to positive integers.

**new**-
my $knapsack = Algorithm::Knapsack->new( capacity => $capacity, weights => \@weights, );

Creates a new Algorith::Knapsack object. Value of $capacity is a positive integer and \@weights is a reference to an array of positive integers, each of which is less than $capacity.

**compute**-
$knapsack->compute();

Iterates over all possible combinations of weights to solve the knapsack problem. Note that the time to solve the problem grows exponentially with respect to the number of items (weights) to choose from.

**solutions**-
my @solutions = $knapsack->solutions();

Returns a list of solutions. Each solution is a reference to an array of indexes to @weights.

The following program solves the knapsack problem for a list of weights (14, 5, 2, 11, 3, 8) and capacity 30.

use Algorithm::Knapsack; my @weights = (14, 5, 2, 11, 3, 8); my $knapsack = Algorithm::Knapsack->new( capacity => 30, weights => \@weights, ); $knapsack->compute(); foreach my $solution ($knapsack->solutions()) { print join(',', map { $weights[$_] } @{$solution}), "\n"; }

The output from the above program is:

14,5,11 14,5,3,8 14,2,11,3

Alexander Anderson <a.anderson@utoronto.ca>

Copyright (c) 2004 Alexander Anderson. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

syntax highlighting: