简体   繁体   中英

Algorithm for testing all mathematical order

I want to implement, that the User can input a Array of int s ( int[] ), and a desired target .

Then the program should be able to test all possibilities in add , subtract , multiply and divide , and return true, if any possibilities are given.

Example:

int[] = {1, 4, 6, 3}, target = 8

(Program test everything, from 1+4+6+3 till 1/4/6/3 )

Desired result

1+4+6-3 

is the correct answer, since 1+4+6-3 == 8

Let's try brute force - we have just few formulae ( 3**4 == 81 of them) to test. First, let's generate all formlae:

using System.Data;
using System.Linq;

...

private static IEnumerable<string> Formulae(int[] numbers) {
  char[] alphabet = new char[] { '+', '-', '*', '/' };

  int[] current = new int[numbers.Length - 1];

  do {
    yield return string.Concat(numbers
      .Select((d, i) => $"{(i > 0 ? alphabet[current[i - 1]].ToString() : "")}{d}"));

    for (int i = 0; i < current.Length; ++i)
      if ((current[i] = (current[i] + 1) % alphabet.Length) != 0)
        break;
  }
  while (!current.All(i => i == 0));
}

then we Compute each formula:

private static string Solve(int[] numbers, int target) {
  using (DataTable table = new DataTable()) {
    foreach (string formula in Formulae(numbers)) {
      try {
        int result = Convert.ToInt32(table.Compute(formula, null));

        if (result == target)
          return $"{formula} = {target}";
      }
      catch (DivideByZeroException) {
        ;
      }
    }
  }

  return "No solution";
}

Demo:

Console.Write(Solve(new int[] { 1, 4, 6, 3 }, 8));

Outcome :

1+4+6-3 = 8

You need just a little modification, if you want to get all solutions :

private static IEnumerable<string> AllSolutions(int[] numbers, int target) {
  using (DataTable table = new DataTable()) {
    foreach (string formula in Formulae(numbers)) {
      int result; 

      try {
        result = Convert.ToInt32(table.Compute(formula, null));
      }
      catch (DivideByZeroException) {
        continue;
      }

      if (result == target)
        yield return $"{formula} = {target}";
    }
  }
}

Demo:

Console.Write(string.Join(Environment.NewLine, 
  AllSolutions(new int[] { 1, 4, 6, 3 }, 8)));

Outcome:

1+4+6-3 = 8
1*4*6/3 = 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM