I have a program that will get all possible permutations of a certain equation:
A + 13 * B / C + D + 12 * E - F - 11 + G * H / I - 10 == 66
Where A, B....I is a value 1-9, and where each digit is used only once in the equation (So if A is 1, no other variable can be 1). There are 136 different solutions for this.
using System;
using System.Collections.Generic;
using System.IO;
using Rationals;
class Program
{
static void Main(string[] args)
{
HashSet<string> list = new HashSet<string>();
for (Rational a = 1; a <= 9; a++)
{
for (Rational b = 1; b <= 9; b++)
{
HashSet<Rational> unique2 = new HashSet<Rational>() { a, b };
if (unique2.Count != 2) continue;
for (Rational c = 1; c <= 9; c++)
{
HashSet<Rational> unique3 = new HashSet<Rational>() { a, b, c };
if (unique3.Count != 3) continue;
for (Rational d = 1; d <= 9; d++)
{
HashSet<Rational> unique4 = new HashSet<Rational>() { a, b, c, d };
if (unique4.Count != 4) continue;
for (Rational e = 1; e <= 9; e++)
{
HashSet<Rational> unique5 = new HashSet<Rational>() { a, b, c, d, e };
if (unique5.Count != 5) continue;
for (Rational f = 1; f <= 9; f++)
{
HashSet<Rational> unique6 = new HashSet<Rational>() { a, b, c, d, e, f };
if (unique6.Count != 6) continue;
for (Rational g = 1; g <= 9; g++)
{
HashSet<Rational> unique7 = new HashSet<Rational>() { a, b, c, d, e, f, g };
if (unique7.Count != 7) continue;
for (Rational h = 1; h <= 9; h++)
{
HashSet<Rational> unique8 = new HashSet<Rational>() { a, b, c, d, e, f, g, h };
if (unique8.Count != 8) continue;
for (Rational i = 1; i <= 9; i++)
{
HashSet<Rational> unique = new HashSet<Rational>() { a, b, c, d, e, f, g, h, i };
if (unique.Count != 9) continue;
if (a + (Rational)13 * b / c + d + (Rational)12 * e - f - (Rational)11 + g * h / i - (Rational)10 == 66)
{
list.Add(string.Format("{0} + 13 * {1} / {2} + {3} + 12 * {4} - {5} - 11 + {6} * {7} / {8} - 10 == 66", a, b, c, d, e, f, g, h, i));
}
}
}
}
}
}
}
}
}
}
File.WriteAllText("resultsNonUnique.txt", string.Join(Environment.NewLine, list));
Console.WriteLine(list.Count);
Console.ReadLine();
}
}
Adding the HashSet
s before a nesting loop makes the program faster for me. I know I can do comparisons individually instead but this is less tedious for me and still faster.
Someone wrote a Haskell solution for this, which looks like:
solutions = [ l | (l @ [a, b, c, d, e, f, g, h, i]) <- permutations [1 .. 9], a % 1 + 13 * b % c + d % 1 + 12 * e % 1 - f % 1 - 11 % 1 + g * h % i - 10 == 66 ]
Okay, granted that my output is more elegant, this code is a little intimidating. It's incredibly...short (I wonder if people see the irony between code and real life like I do).
Is there a way I can make my code shorter? Like with LINQ? If possible no external packages that I would need, but that's all okay.
solutions = [p for p in itertools.permutations(range(1, 10)) for a, b, c, d, e, f, g, h, i in [p] if a + 13 * b / c + d + 12 * e - f - 11 + g * h / i - 10 == 66]
\$\endgroup\$ – Gareth Rees May 26 '15 at 11:37