Swift Knapsack problem using bottom-down (memoization) approach












0












$begingroup$


I'm solving the "unbounded" variant of the knapsack problem, meaning the repetition of items is allowed. As in the Hackerrank version of the knapsack problem, I am returning the sum nearest to, not exceeding the target.



Some sample calls, with the solutions afterwards ar



unboundedKnapsack(k: 10, arr: [2,3,4]) // 10
unboundedKnapsack(k: 12, arr: [1,6,9]) //12
unboundedKnapsack(k: 9, arr: [3,4,4,4,8]) // 9
unboundedKnapsack(k: 3, arr: [2]) // 2
unboundedKnapsack(k: 13, arr: [3,7,9,11]) //13
unboundedKnapsack(k: 11, arr: [3,7,9]) // 10


I developed a recursive solution, and as below I've added memoization:



func unboundedKnapsack(k: Int, arr: [Int]) -> Int {
var cache: [[Int]] = Array(repeating: Array(repeating: 0, count: arr.count), count: k)
return k - knap(k, arr, 0, 0, &cache)
}

func knap(_ target: Int, _ arr: [Int], _ ptr: Int, _ current : Int, _ cache: inout [[Int]]) -> Int {
// greedy - we either take the current item or we don't
if (current > target) {return Int.max}
if (ptr > arr.count - 1) {return target - current}
if (current == target) {return target - current}
if (cache[current][ptr] != 0) {return cache[current][ptr]}
let result = min(
// take the current and move pointer
knap(target, arr, ptr + 1, current + arr[ptr], &cache)
,
// take the current and leave the pointer so we can take more
knap(target, arr, ptr, current + arr[ptr], &cache),
// do not take the current and move pointer
knap(target, arr, ptr + 1, current, &cache)
)
cache[current][ptr] = result
return result
}


I haven't been able to test all inputs for my solution, so I wanted comments on how this particular approach could be improved (using my memoization as shown rather than changing the approach).









share









$endgroup$

















    0












    $begingroup$


    I'm solving the "unbounded" variant of the knapsack problem, meaning the repetition of items is allowed. As in the Hackerrank version of the knapsack problem, I am returning the sum nearest to, not exceeding the target.



    Some sample calls, with the solutions afterwards ar



    unboundedKnapsack(k: 10, arr: [2,3,4]) // 10
    unboundedKnapsack(k: 12, arr: [1,6,9]) //12
    unboundedKnapsack(k: 9, arr: [3,4,4,4,8]) // 9
    unboundedKnapsack(k: 3, arr: [2]) // 2
    unboundedKnapsack(k: 13, arr: [3,7,9,11]) //13
    unboundedKnapsack(k: 11, arr: [3,7,9]) // 10


    I developed a recursive solution, and as below I've added memoization:



    func unboundedKnapsack(k: Int, arr: [Int]) -> Int {
    var cache: [[Int]] = Array(repeating: Array(repeating: 0, count: arr.count), count: k)
    return k - knap(k, arr, 0, 0, &cache)
    }

    func knap(_ target: Int, _ arr: [Int], _ ptr: Int, _ current : Int, _ cache: inout [[Int]]) -> Int {
    // greedy - we either take the current item or we don't
    if (current > target) {return Int.max}
    if (ptr > arr.count - 1) {return target - current}
    if (current == target) {return target - current}
    if (cache[current][ptr] != 0) {return cache[current][ptr]}
    let result = min(
    // take the current and move pointer
    knap(target, arr, ptr + 1, current + arr[ptr], &cache)
    ,
    // take the current and leave the pointer so we can take more
    knap(target, arr, ptr, current + arr[ptr], &cache),
    // do not take the current and move pointer
    knap(target, arr, ptr + 1, current, &cache)
    )
    cache[current][ptr] = result
    return result
    }


    I haven't been able to test all inputs for my solution, so I wanted comments on how this particular approach could be improved (using my memoization as shown rather than changing the approach).









    share









    $endgroup$















      0












      0








      0





      $begingroup$


      I'm solving the "unbounded" variant of the knapsack problem, meaning the repetition of items is allowed. As in the Hackerrank version of the knapsack problem, I am returning the sum nearest to, not exceeding the target.



      Some sample calls, with the solutions afterwards ar



      unboundedKnapsack(k: 10, arr: [2,3,4]) // 10
      unboundedKnapsack(k: 12, arr: [1,6,9]) //12
      unboundedKnapsack(k: 9, arr: [3,4,4,4,8]) // 9
      unboundedKnapsack(k: 3, arr: [2]) // 2
      unboundedKnapsack(k: 13, arr: [3,7,9,11]) //13
      unboundedKnapsack(k: 11, arr: [3,7,9]) // 10


      I developed a recursive solution, and as below I've added memoization:



      func unboundedKnapsack(k: Int, arr: [Int]) -> Int {
      var cache: [[Int]] = Array(repeating: Array(repeating: 0, count: arr.count), count: k)
      return k - knap(k, arr, 0, 0, &cache)
      }

      func knap(_ target: Int, _ arr: [Int], _ ptr: Int, _ current : Int, _ cache: inout [[Int]]) -> Int {
      // greedy - we either take the current item or we don't
      if (current > target) {return Int.max}
      if (ptr > arr.count - 1) {return target - current}
      if (current == target) {return target - current}
      if (cache[current][ptr] != 0) {return cache[current][ptr]}
      let result = min(
      // take the current and move pointer
      knap(target, arr, ptr + 1, current + arr[ptr], &cache)
      ,
      // take the current and leave the pointer so we can take more
      knap(target, arr, ptr, current + arr[ptr], &cache),
      // do not take the current and move pointer
      knap(target, arr, ptr + 1, current, &cache)
      )
      cache[current][ptr] = result
      return result
      }


      I haven't been able to test all inputs for my solution, so I wanted comments on how this particular approach could be improved (using my memoization as shown rather than changing the approach).









      share









      $endgroup$




      I'm solving the "unbounded" variant of the knapsack problem, meaning the repetition of items is allowed. As in the Hackerrank version of the knapsack problem, I am returning the sum nearest to, not exceeding the target.



      Some sample calls, with the solutions afterwards ar



      unboundedKnapsack(k: 10, arr: [2,3,4]) // 10
      unboundedKnapsack(k: 12, arr: [1,6,9]) //12
      unboundedKnapsack(k: 9, arr: [3,4,4,4,8]) // 9
      unboundedKnapsack(k: 3, arr: [2]) // 2
      unboundedKnapsack(k: 13, arr: [3,7,9,11]) //13
      unboundedKnapsack(k: 11, arr: [3,7,9]) // 10


      I developed a recursive solution, and as below I've added memoization:



      func unboundedKnapsack(k: Int, arr: [Int]) -> Int {
      var cache: [[Int]] = Array(repeating: Array(repeating: 0, count: arr.count), count: k)
      return k - knap(k, arr, 0, 0, &cache)
      }

      func knap(_ target: Int, _ arr: [Int], _ ptr: Int, _ current : Int, _ cache: inout [[Int]]) -> Int {
      // greedy - we either take the current item or we don't
      if (current > target) {return Int.max}
      if (ptr > arr.count - 1) {return target - current}
      if (current == target) {return target - current}
      if (cache[current][ptr] != 0) {return cache[current][ptr]}
      let result = min(
      // take the current and move pointer
      knap(target, arr, ptr + 1, current + arr[ptr], &cache)
      ,
      // take the current and leave the pointer so we can take more
      knap(target, arr, ptr, current + arr[ptr], &cache),
      // do not take the current and move pointer
      knap(target, arr, ptr + 1, current, &cache)
      )
      cache[current][ptr] = result
      return result
      }


      I haven't been able to test all inputs for my solution, so I wanted comments on how this particular approach could be improved (using my memoization as shown rather than changing the approach).







      swift





      share












      share










      share



      share










      asked 4 mins ago









      stevenpcurtisstevenpcurtis

      1314




      1314






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213009%2fswift-knapsack-problem-using-bottom-down-memoization-approach%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213009%2fswift-knapsack-problem-using-bottom-down-memoization-approach%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          Refactoring coordinates for Minecraft Pi buildings written in Python