# Solve equation with conditions of a variable equal to a set of values

Let's say that I need to know all the solutions to an equation like

(variables in an interval)

c1 = 1 <= x <= 9;

c2 = 1 <= y <= 9;

c3 = 1 <= z <= 9;

c4 = 1 <= t <= 9;

c5 = 1 <= w <= 9;

And conditions like

eq1 = Abs[x - t] == 1;

eq2 = Abs[y - z] == 1;

eq3 = y + w == 10;

And I want to give specific possible values to a variable. For instance, let's say x can only be 2, 4 or 5. Or a thousand different number in a vector (but discrete values I already know). Is there a way to do that? I know a loop could be used, but I can't make 5 loops realistically.

Something that says: hey, solve with x = this discrete set of values, y= this discrete set of values, etc.

## 2 Answers

\$Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global*"]

var = {t, w, x, y, z};


Without the specific constraints on x

sol1 = Solve[
Abs[x - t] == 1 && Abs[y - z] == 1 && y + w == 10 &&
And @@ Thread[1 <= var <= 9], var, Integers];

Length@sol1

(* 256 *)


Looking at the first few solutions

sol1[[1 ;; 5]]

(* {{t -> 2, w -> 8, x -> 1, y -> 2, z -> 1},
{t -> 1, w -> 8, x -> 2, y -> 2, z -> 1},
{t -> 3, w -> 8, x -> 2, y -> 2, z -> 1},
{t -> 2, w -> 8, x -> 3, y -> 2, z -> 1},
{t -> 4, w -> 8, x -> 3, y -> 2, z -> 1}} *)


Adding the additional constraints on x

sol2 = Solve[
Abs[x - t] == 1 && Abs[y - z] == 1 && y + w == 10 &&
And @@ Thread[1 <= var <= 9] && Or @@ Thread[x == {2, 4, 5}], var,
Integers];

Length@sol2

(* 96 *)


Verifying that sol2 is a subset of sol1

Sort@sol2 ===
Sort@Select[sol1, MemberQ[{2, 4, 5}, x /. #] &]

(* True *)


Assume that we want to solve

1<={x,y,z,w,t}<=9, Abs[x - t] == 1, Abs[y - z] == 1, y + w == 10,{x, y, z, w, t} ∈ Integers


and in addition that x can only be 2, 4 or 5 and y can only be 1, 2 or 3

• Follow @Carl Woll The condition x can only be 2, 4 or 5 can be write as {x} ∈ Point[List /@ {2, 4, 5}] etc.

• the condition 1<={x,y,z,w,t}<=9 can also be write as {x, y, z, w, t} ∈ Cuboid[{1, 1, 1, 1, 1}, {9, 9, 9, 9, 9}].

reg = ImplicitRegion[{{x, y, z, w, t} ∈
Cuboid[{1, 1, 1, 1, 1}, {9, 9, 9, 9, 9}], Abs[x - t] == 1,
Abs[y - z] == 1,
y + w == 10, {x, y, z, w, t} ∈ Integers, {x} ∈
Point[List /@ {2, 4, 5}], {y} ∈
Point[List /@ {1, 2, 3}]}, {x, y, z, w, t}];
Solve[{x, y, z, w, t} ∈ reg]
`