1 // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
2 // Copyright (C) 2010 Winch Gate Property Limited
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU Affero General Public License as
6 // published by the Free Software Foundation, either version 3 of the
7 // License, or (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU Affero General Public License for more details.
14 // You should have received a copy of the GNU Affero General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #ifndef RYAI_KNAPSACK_SOLVER_H
18 #define RYAI_KNAPSACK_SOLVER_H
20 //////////////////////////////////////////////////////////////////////////////
21 // IKnapsackContext //
22 //////////////////////////////////////////////////////////////////////////////
24 class IKnapsackContext
27 virtual ~IKnapsackContext() { }
28 virtual float weight(size_t i
) = 0;
29 virtual float value(size_t i
) = 0;
30 virtual size_t size() = 0;
33 //////////////////////////////////////////////////////////////////////////////
35 //////////////////////////////////////////////////////////////////////////////
37 /// This class resolves the knapsack problem, in french "probleme du sac a
52 VeryFastSingleReplace
,
53 //- /!\ Algorithms below don't respect constraints
56 static std::string
toString(Algorithm a
);
57 static CKnapsackSolver::Algorithm
fromString(std::string
const& a
);
59 IKnapsackContext
* _Context
;
66 explicit CKnapsackSolver(IKnapsackContext
* context
, bool* take
= NULL
);
67 virtual ~CKnapsackSolver();
71 float totalFreeWeight();
73 /// @param wMax Max weight that can be taken
74 /// @note Not thread safe
75 void optimize(float wMax
, Algorithm algorithm
= Optimal
);
77 float weight(size_t i
);
78 float value(size_t i
);
80 /// @name Algorithms entry points
82 void optimizeOptimal();
83 void optimizeFullAddCheck();
84 void optimizeAddCheck();
85 void optimizeFastAddCheck();
86 void optimizeFullSingleReplace();
87 void optimizeSingleReplace();
88 void optimizeFastSingleReplace();
89 void optimizeVeryFastSingleReplace();
90 void optimizeTakeAll();
92 /// @name Algorithms helper functions
94 void optimizeOptimalRec(int i
, float w
, float v
, bool* take
);
98 //////////////////////////////////////////////////////////////////////////////
99 // CKnapsackContext //
100 //////////////////////////////////////////////////////////////////////////////
102 class CKnapsackContext
103 : public IKnapsackContext
109 CKnapsackContext(size_t size
, float* weights
, float* values
);
110 virtual float weight(size_t i
);
111 virtual float value(size_t i
);
112 virtual size_t size();