Home > Mobile >  Find the possible values for two equations
Find the possible values for two equations

Time:01-09

2x   4y   6z = 1200
x   y   z = 300

how can I find the possible x, y, z integer values in a c# method?, I am trying to find a better solution instead of using brute force nested for loops since it is not a good solution.

public List<Tuple<int, int, int>> Calculate()
{
    var result = new List<Tuple<int, int, int>>();
    int maxValue = 300;

    for(int i = 0; i< maxValue; i  )
        for (int j = 0; j < maxValue; j  )
            for (int k = 0; k < maxValue; k  )
                if (i   j   k == maxValue && 2 * i   4 * j   6 * k == 1200)
                    result.Add(new Tuple<int, int, int>(i, j, k));

    return result;
}

Thank you in advance.

CodePudding user response:

Well, having

2x   4y   6z = 1200
x   y   z = 300

you can put it as

x   2y   3z = 600
x   y   z = 300

subtract 2nd from the 1st and you get

y   2z = 300

or

y = 300 - 2z

Since x = 300 - y - z we can put it as

x = 300 - y - z =
  = 300 - (300 - 2z) - z =
  = 300 - 300   2z - z =
  = z 

Finally, for the arbitrary z (which is free variable)

x = z
y = 300 - 2 * z;

Possible c# code:

private static (int x, int y, int z) Solution(int x) => (x, 300 - 2 * x, x);

Demo:

string solutions = string.Join(Environment.NewLine, Enumerable
  .Range(0, 10)
  .Select(x => Solution(x)));

...

// 10 solutions for x = 0..9 
string solutions = string.Join(Environment.NewLine, Enumerable
  .Range(0, 10)
  .Select(x => Solution(x)));

Console.Write(solutions);

Outcome:

(0, 300, 0)
(1, 298, 1)
(2, 296, 2)
(3, 294, 3)
(4, 292, 4)
(5, 290, 5)
(6, 288, 6)
(7, 286, 7)
(8, 284, 8)
(9, 282, 9)

If you are looking for non-negative solutions only (you've mentioned probabilities in the comments for the code), then use x in [0..150] range:

(0, 300, 0)
(1, 298, 1)
(2, 296, 2)
...
(148, 4, 148)
(149, 2, 149)
(150, 0, 150)

Edit: your Calculate() method improved:

public static List<Tuple<int, int, int>> Calculate() {
  var result = new List<Tuple<int, int, int>>();
  const int maxValue = 300;

  int start = Math.Max(150 - maxValue / 2, 0);

  for (int x = start; ;   x) {
    int y = 300 - 2 * x;
    int z = x;

    if (y < 0 || x > maxValue)
      break;

    result.Add(new Tuple<int, int, int>(x, y, z));
  }

  return result;
}
  •  Tags:  
  • Related