1
$\begingroup$

For example I want to find solution with maximum value among solutions (and possibly plot it):

answers = Piecewise[List @@@ Last @@@ N @Solve[{
       z == 40 x + 50 y,
       6 x + 10 y <= 672,
       0.25 x + 0.15 y <= 24,
       1.5 y <= 42,
       0 <= x,
       0 <= y
       }, {z}, Integers]]

In this case it is : {4230.,x\[LongEqual]87.\[And]y\[LongEqual]15.}

$\endgroup$

3 Answers 3

4
$\begingroup$

I'm not sure why you are using piecewice to hold the answers, but you could just use sort and get the last element:

 answers = 
  List @@@ Last @@@ 
  N@Solve[{z == 40 x + 50 y, 6 x + 10 y <= 672, 
  0.25 x + 0.15 y <= 24, 1.5 y <= 42, 0 <= x, 0 <= y}, {z}, 
  Integers]

 Sort[answers][[-1]]

 (*=> *) {4230., x == 87. && y == 15.}

As for plotting the solution points, you could turn the conditional expressions into individual points and plot those using ListPlot3D:

 zxy = answers //. {{a_, Or[b_, c_]} :> Sequence[{a, b}, {a, c}] , 
 And -> Sequence, Equal[_, b_] :> b};

 ListPlot3D[zxy[[1 ;;, {2, 3, 1}]], AxesLabel -> {"x", "y", "z"} ]

This doesn't work for arbitrary answer lists, but works in your case. If you have results with different logic constructs you can modify the replacement rules accordingly.

Output from ListPlot3D showing the solutions

$\endgroup$
3
$\begingroup$

Could use Maximize.

Maximize[{z, z == 40*x + 50*y,
       6 x + 10 y <= 672,
       x/4 + 3*y/20 <= 24,
       3*y/2 <= 42,
       0 <= x,
       0 <= y}, {x,y,z}, Integers]

(* {4230, {x -> 87, y -> 15, z -> 4230}} *)
$\endgroup$
1
$\begingroup$
 answers[[1, -1]]
 (* {4230., x == 87. && y == 15.}   *)

EDIT: An alternative series of replacements to get the data for plotting:

pltdata =  (List @@@ Last @@@ N@
     Solve[{z == 40 x + 50 y, 6 x + 10 y <= 672, 
       0.25 x + 0.15 y <= 24, 1.5 y <= 42, 0 <= x, 0 <= y}, {z}, Integers] /.
  {And -> List, Or -> List, Equal[_, a_] :> a} //
  If[Depth[#] == 3, Reverse[#], Sequence @@ Reverse /@ Thread[#, List, 2]] & /@ # &) /.
  {{a_, b_}, c_} :> {a, b, c};

ListPointPlot3D[pltdata, ColorFunction -> (Hue[#3] &), BoxRatios -> 1]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.