5
$\begingroup$

So I have been wodering if Mathematica has any in-built function that would easily solve me these problem without manual search using for cycles that slow down the computation.

Let's imagine I have a certain condition, a function that depends on three different parameters and a boundary limit for that function:

$$f(x,y,z)<K$$

$x$, $y$ and $z$ are discrete variables that are described by lists of numbers, for instance

$$x \in \{x_1, x_2,x_3,..., x_X \}$$ $$y \in \{y_1, y_2,y_3,..., y_Y \}$$ $$z \in \{z_1, z_2,z_3,..., z_Z \}$$

Now, I want to find all the combinations of values between these 3 sets that when inserted into function $f$ verify my inequality. Any guess on how this can be done. Perhaps something around the Flatten function, but I want it to return all sets. Thank you!

$\endgroup$
2
  • $\begingroup$ How big are x, y, z? $\endgroup$
    – lericr
    Dec 27, 2022 at 23:38
  • $\begingroup$ @lericr well ideally I did not want for it to depend on size, but they are rather short lists of maximum of 10 elements, which leads to a 1000 different combinations. $\endgroup$ Dec 27, 2022 at 23:42

2 Answers 2

6
$\begingroup$

With BacktrackSearch you don't have to hold all the combinations in memory like you would with Tuples:

{xS, yS, zS} =
  {{1, 2, 3},
   {6, 7, 15, 16},
   {3, 8, 9, 10}};

f[x_, y_, z_] := 4 x^2 - 3 y + 3 z^2

k = 10;
ResourceFunction["BacktrackSearch"][
 {xS, yS, zS},
 Length[#] <= 3 &,
 (f @@ #) < k &, All]

{{1, 15, 3}, {1, 16, 3}, {2, 15, 3}, {2, 16, 3}}
$\endgroup$
1
  • $\begingroup$ Thank you! I will try to apply that, the fact it does not hold every combination in memory is excellent as I intend to make the problem grow to multiple variables. $\endgroup$ Dec 29, 2022 at 11:25
4
$\begingroup$

If the lists are small, as the comment indicates, then brute force works just fine:

AllPossibleInputs = Tuples[{xValues, yValues, zValues}]

Then you can just select

Select[AllPossibleInputs, f @@ # < K &]
(* or however your f function works *)
$\endgroup$
1
  • $\begingroup$ Thank you for your answer. Although the other one with BacktrackSearch suits my problem the best as it will grow into more variables and longer lists, this one is also very useful for small stuff. $\endgroup$ Dec 29, 2022 at 11:26

Your Answer

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

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