<p>Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:</p>

<pre><code>Array
(
    [leg0] =&gt; Array
        (
            [UPS] =&gt; Array
                (
                    [days] =&gt; 1
                    [cost] =&gt; 5000
                )

            [FedEx] =&gt; Array
                (
                    [days] =&gt; 2
                    [cost] =&gt; 3000
                )

            [Conway] =&gt; Array
                (
                    [days] =&gt; 5
                    [cost] =&gt; 1000
                )

        )

    [leg1] =&gt; Array
        (
            [UPS] =&gt; Array
                (
                    [days] =&gt; 1
                    [cost] =&gt; 3000
                )

            [FedEx] =&gt; Array
                (
                    [days] =&gt; 2
                    [cost] =&gt; 3000
                )

            [Conway] =&gt; Array
                (
                    [days] =&gt; 3
                    [cost] =&gt; 1000
                )

        )

    [leg2] =&gt; Array
        (
            [UPS] =&gt; Array
                (
                    [days] =&gt; 1
                    [cost] =&gt; 4000
                )

            [FedEx] =&gt; Array
                (
                    [days] =&gt; 1
                    [cost] =&gt; 3000
                )

            [Conway] =&gt; Array
                (
                    [days] =&gt; 2
                    [cost] =&gt; 5000
                )

        )

)
</code></pre>

<p>How would you go about finding the best combination programmatically?</p>

<p>My best attempt so far (third or fourth algorithm) is:</p>

<ol>
<li>Find the longest shipper for each leg</li>
<li>Eliminate the most "expensive" one</li>
<li>Find the cheapest shipper for each leg</li>
<li>Calculate the total cost &amp; days</li>
<li>If days are acceptable, finish, else, goto 1</li>
</ol>

<p>Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):</p>

<pre><code>$shippers["leg1"] = array(
    "UPS"    =&gt; array("days" =&gt; 1, "cost" =&gt; 4000),
    "Conway" =&gt; array("days" =&gt; 3, "cost" =&gt; 3200),
    "FedEx"  =&gt; array("days" =&gt; 8, "cost" =&gt; 1000)
);

$shippers["leg2"] = array(
    "UPS"    =&gt; array("days" =&gt; 1, "cost" =&gt; 3500),
    "Conway" =&gt; array("days" =&gt; 2, "cost" =&gt; 2800),
    "FedEx"  =&gt; array("days" =&gt; 4, "cost" =&gt; 900)
);

$shippers["leg3"] = array(
    "UPS"    =&gt; array("days" =&gt; 1, "cost" =&gt; 3500),
    "Conway" =&gt; array("days" =&gt; 2, "cost" =&gt; 2800),
    "FedEx"  =&gt; array("days" =&gt; 4, "cost" =&gt; 900)
);    

$times = 0;
$totalDays = 9999999;

print "&lt;h1&gt;Shippers to Choose From:&lt;/h1&gt;&lt;pre&gt;";
print_r($shippers);
print "&lt;/pre&gt;&lt;br /&gt;";

while($totalDays &gt; $maxDays &amp;&amp; $times &lt; 500){
            $totalDays = 0;
            $times++;
            $worstShipper = null;
            $longestShippers = null;
            $cheapestShippers = null;

            foreach($shippers as $legName =&gt; $leg){
                //find longest shipment for each leg (in terms of days)
                unset($longestShippers[$legName]);
                $longestDays = null;        

                if(count($leg) &gt; 1){
                    foreach($leg as $shipperName =&gt; $shipper){
                        if(empty($longestDays) || $shipper["days"] &gt; $longestDays){
                            $longestShippers[$legName]["days"] = $shipper["days"];
                            $longestShippers[$legName]["cost"] = $shipper["cost"];
                            $longestShippers[$legName]["name"] = $shipperName;
                            $longestDays = $shipper["days"];
                        }
                    }           
                }
            }

            foreach($longestShippers as $leg =&gt; $shipper){
                $shipper["totalCost"] = $shipper["days"] * $shipper["cost"];

                //print $shipper["totalCost"] . " &amp;lt;?&amp;gt; " . $worstShipper["totalCost"] . ";";

                if(empty($worstShipper) || $shipper["totalCost"] &gt; $worstShipper["totalCost"]){
                    $worstShipper = $shipper;
                    $worstShipperLeg = $leg;
                }
            }

            //print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"];
            unset($shippers[$worstShipperLeg][$worstShipper["name"]]);

            print "&lt;h1&gt;Next:&lt;/h1&gt;&lt;pre&gt;";
            print_r($shippers);
            print "&lt;/pre&gt;&lt;br /&gt;";

            foreach($shippers as $legName =&gt; $leg){
                //find cheapest shipment for each leg (in terms of cost)
                unset($cheapestShippers[$legName]);
                $lowestCost = null;

                foreach($leg as $shipperName =&gt; $shipper){
                    if(empty($lowestCost) || $shipper["cost"] &lt; $lowestCost){
                        $cheapestShippers[$legName]["days"] = $shipper["days"];
                        $cheapestShippers[$legName]["cost"] = $shipper["cost"];
                        $cheapestShippers[$legName]["name"] = $shipperName;
                        $lowestCost = $shipper["cost"];
                    }
                }

                //recalculate days and see if we are under max days...
                $totalDays += $cheapestShippers[$legName]['days'];  
            }
            //print "&lt;h2&gt;totalDays: $totalDays&lt;/h2&gt;";
        }

        print "&lt;h1&gt;Chosen Shippers:&lt;/h1&gt;&lt;pre&gt;";
        print_r($cheapestShippers);
        print "&lt;/pre&gt;";
</code></pre>

<p>I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....</p>

<p>EDIT:
To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.</p>

<p>The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.</p>

<p>So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm.</p>

[{'answer_id': 14892, 'author': 'Baltimark', 'author_id': 1179, 'author_profile': 'https://Stackoverflow.com/users/1179', 'pm_score': 3, 'selected': False, 'text': '<p>Sounds like what you have is called a "linear programming problem". It also sounds like a homework problem, no offense. </p>\n\n<p>The classical solution to a LP problem is called the "Simplex Method". Google it.</p>\n\n<p>However, to use that method, you must have the problem correctly formulated to describe your requirements. </p>\n\n<p>Still, it may be possible to enumerate all possible paths, since you have such a small set. Such a thing won\'t scale, though. </p>\n'}, {'answer_id': 14895, 'author': 'Theo', 'author_id': 1109, 'author_profile': 'https://Stackoverflow.com/users/1109', 'pm_score': 3, 'selected': False, 'text': '<p>Sounds like a job for <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="noreferrer">Dijkstra\'s algorithm</a>:</p>\n\n<blockquote>\n  <p>Dijkstra\'s algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1959, <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="noreferrer">1</a> is a graph search algorithm that solves the single-source shortest path problem for a graph with non negative edge path costs, outputting a shortest path tree. This algorithm is often used in routing.</p>\n</blockquote>\n\n<p>There are also implementation details in the Wikipedia article.</p>\n'}, {'answer_id': 14899, 'author': 'Kevin Sheffield', 'author_id': 590, 'author_profile': 'https://Stackoverflow.com/users/590', 'pm_score': 4, 'selected': True, 'text': '<p>Could alter some of the <a href="http://en.wikipedia.org/wiki/Shortest_path_problem" rel="noreferrer">shortest path algorithms</a>, like Dijkstra\'s, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold.  Should find the cheapest that gets you in under your threshold that way</p>\n'}, {'answer_id': 14904, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 2, 'selected': False, 'text': "<p>If I knew I only had to deal with 5 cities, in a predetermined order, and that there were only 3 routes between adjacent cities, I'd brute force it.  No point in being elegant.</p>\n\n<p>If, on the other hand, this were a homework assignment and I were supposed to produce an algorithm that could actually scale, I'd probably take a different approach.</p>\n"}, {'answer_id': 14906, 'author': 'Baltimark', 'author_id': 1179, 'author_profile': 'https://Stackoverflow.com/users/1179', 'pm_score': -1, 'selected': False, 'text': "<p>I think that Dijkstra's algorithm is for finding a shortest path. </p>\n\n<p><strong>cmcculloh</strong> is looking for the minimal cost subject to the constraint that he gets it there in 5 days. </p>\n\n<p>So, merely finding the quickest way won't get him there cheapest, and getting there for the cheapest, won't get it there in the required amount of time. </p>\n"}, {'answer_id': 23622, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 2, 'selected': False, 'text': '<p>This is a <a href="http://en.wikipedia.org/wiki/List_of_knapsack_problems" rel="nofollow noreferrer">knapsack problem</a>. The weights are the days in transit, and the profit should be $5000 - cost of leg. Eliminate all negative costs and go from there!</p>\n'}, {'answer_id': 104979, 'author': 'Eonwe', 'author_id': 19198, 'author_profile': 'https://Stackoverflow.com/users/19198', 'pm_score': 2, 'selected': False, 'text': '<p>As Baltimark said, this is basically a Linear programming problem. If only the coefficients for the shippers (1 for included, 0 for not included) were not (binary) integers for each leg, this would be more easily solveable. Now you need to find some (binary) integer linear programming  (ILP) heuristics as the problem is NP-hard.\nSee <a href="http://en.wikipedia.org/wiki/Linear_programming#Integer_unknowns" rel="nofollow noreferrer" title="Wikipedia on integer linear programming">Wikipedia on integer linear programming</a> for links; on my linear programming course we used at least <a href="http://en.wikipedia.org/wiki/Branch_and_bound" rel="nofollow noreferrer" title="Branch and bound">Branch and bound</a>.</p>\n\n<p>Actually now that I think of it, this special case is solveable without actual ILP as the amount of days does not matter as long as it is &lt;= 5. Now start by choosing the cheapest carrier for first choice (Conway 5:1000). Next you choose yet again the cheapest, resulting 8 days and 4000 currency units which is too much so we abort that. By trying others too we see that they all results days > 5 so we back to first choice and try the second cheapest (FedEx 2:3000) and then ups in the second and fedex in the last. This gives us total of 4 days and 9000 currency units.</p>\n\n<p>We then could use this cost to prune other searches in the tree that would by some subtree-stage result costs larger that the one we\'ve found already and leave that subtree unsearched from that point on.\nThis only works as long as we can know that searching in the subtree will not produce a better results, as we do here when costs cannot be negative.</p>\n\n<p>Hope this rambling helped a bit :). </p>\n'}]
['https://Stackoverflow.com/questions/14884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58/']