All Classes Namespaces Files Functions Variables Typedefs Enumerations Friends Macros Pages
fill_knapsack_dynamic_table.hpp
Go to the documentation of this file.
1 //=======================================================================
2 // Copyright (c) 2013 Piotr Wygocki
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See
5 // accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt)
7 //=======================================================================
15 #ifndef PAAL_FILL_KNAPSACK_DYNAMIC_TABLE_HPP
16 #define PAAL_FILL_KNAPSACK_DYNAMIC_TABLE_HPP
17 
19 
20 namespace paal {
46 template <typename ValueIterator, typename Objects, typename ObjectSizeFunctor,
47  typename Combine, typename Compare, typename Init,
48  typename GetPositionRange>
49 detail::FunctorOnRangePValue<ObjectSizeFunctor, Objects>
50 fill_knapsack_dynamic_table(ValueIterator valuesBegin, ValueIterator valuesEnd,
51  Objects &&objects, ObjectSizeFunctor size,
52  Combine combine, Compare compare, Init init,
53  GetPositionRange get_range) {
54  using Size = detail::FunctorOnRangePValue<ObjectSizeFunctor, Objects>;
55 
56  Size maxSize = std::distance(valuesBegin, valuesEnd);
57 
58  std::fill(valuesBegin + 1, valuesEnd, boost::none);
59  init(*valuesBegin);
60 
61  auto posRange = get_range(0, maxSize);
62 
63  auto objIter = std::begin(objects);
64  auto oEnd = std::end(objects);
65  for (; objIter != oEnd; ++objIter) {
66  auto &&obj = *objIter;
67  auto objSize = size(obj);
68  // for each position, from largest to smallest
69  for (auto pos : posRange) {
70  auto stat = *(valuesBegin + pos);
71  // if position was reached before
72  if (stat != boost::none) {
73  Size newPos = pos + objSize;
74  auto &newStat = *(valuesBegin + newPos);
75  // if we're not exceeding maxSize
76  if (newPos < maxSize) {
77  auto newValue = combine(stat, objIter);
78  // if the value is bigger than previous
79  if (newStat == boost::none || compare(newStat, newValue)) {
80  // update value
81  newStat = newValue;
82  }
83  }
84  }
85  }
86  }
87  return maxSize - 1;
88 }
89 
90 }
91 #endif // PAAL_FILL_KNAPSACK_DYNAMIC_TABLE_HPP
detail::FunctorOnRangePValue< ObjectSizeFunctor, Objects > fill_knapsack_dynamic_table(ValueIterator valuesBegin, ValueIterator valuesEnd, Objects &&objects, ObjectSizeFunctor size, Combine combine, Compare compare, Init init, GetPositionRange get_range)
Computes dynamic algorithm table (valuesBegin, valuesEnd) The values collection has element type Valu...