VBA – Avoid nested loops with recursion (Part 2)

About two years after the “Nested loops with recursion” today I was looking for a way to avoid nested loops with recursion in google and found my article ๐Ÿ™‚ . Lots has changed in my coding style since then as far as I do not use “Call”, “Integer”, variables with names like “c” or “n”, I do not put “_” in the names of the Subs/Functions. Still, using the article from 2015 I have managed to achieve what I wanted.

So, what did I want to do? I wanted to simulate a brute force solution of this NP-complete problem:

Picture:ย https://xkcd.com/287/


At first I have thought about a solution with 6 nested for loops and I have managed to achieve it in a way pretty easily:

Then, I have remembered that I actually think of myself as a high level VBA developer and 6 nested loops is a bit “ugly”. Thus, I have googled “nested loops recursion vba” and the vitoshacademy.com was one of the top results ๐Ÿ™‚ Ironic, I thought! ๐Ÿ™‚ Anyhow, although the code I have written some years ago was a bit “bad”, I have managed to use it and to build this:

If you are wondering for the choice, this is what the waiter should bring:

The solution is not quite full, as far as I have assumed that the positions cannot be more than the squared number of the listed items. Thus, in our case a solution with more than 6×6 units is not considered. Thus, in case that there was a dessert that costs 5 cents, the obvious solution of 301 such desserts will not appear.

Cheers!


Edit:

Or you can order 7 * Mixed Fruit, if you use the good old Sover. Credit to IvenBachย for the solution:

Data>Analysis>Solver>Model=GRG Nonlinear

About

A VBA Developer.

Tagged with: ,