using System.Collections.Generic;
public static void Main()
int[] ans = Scale.Permutate(new int[] { 44, 10, 50, 11, 30, 20, 22, 33 });
for (int i = 0; i < 36; i++)
Console.WriteLine("{0} {1}", i, ans[i]);
Console.WriteLine("Average weighings: {0}", ((double)Enumerable.Range(0, 36).Select(i => i * ans[i]).Sum()) / ans.Sum());
private static int[] bit = { 1, 2, 4, 8, 16, 32, 64, 128 };
public Scale(int[] weights)
valuesum = weights.Sum();
public int Solve(bool show)
marks = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
Console.WriteLine("Weights: A={0}, B={1}, C={2}, D={3}, E={4}, F={5}, G={6}, H={7}", value[0], value[1], value[2], value[3], value[4], value[5], value[6], value[7]);
for (int i = 0; i < 8; i++)
if ((bit[i] & test) != 0)
weights += (char)('A' + i);
Console.WriteLine("{0} [{1}] {2} {3} {4} {5} {6}", iteration, string.Join(", ", marks), weights, total, valuesum - total, totalmarks, marks.Sum() - totalmarks);
if (total * 2 == valuesum)
else if (total * 2 > valuesum)
for (int i = 0; i < 8; i++)
if ((bit[i] & test) != 0)
for (int i = 0; i < 8; i++)
if ((bit[i] & test) == 0)
private int GetNextTest()
List<int[]> marble = new List<int[]>();
int[] index = new int[4];
int test, difference, besttest = 0, bestdifference = int.MaxValue;
for (int i = 0; i < 8; i++)
marble.Add(new int[] { i, marks[i] });
marble.Sort((i, j) => i[1] - j[1]);
int target = marks.Sum() / 2;
for (index[0] = 0; index[0] < 5; index[0]++)
for (index[1] = 7; index[1] > index[0] + 2; index[1]--)
for (index[2] = index[1] - 1; index[2] > index[0] + 1; index[2]--)
for (index[3] = index[0] + 1; index[3] < index[2]; index[3]++)
test = index.Select(i => bit[marble[i][0]]).Sum();
if (tests.Contains(test))
difference = Math.Abs(index.Select(i => marble[i][1]).Sum() - target);
else if (difference < bestdifference)
bestdifference = difference;
public static int[] Permutate(int[] weights)
for (int a = 0; a < 8; a++)
for (int b = 0; b < 8; b++)
for (int c = 0; c < 8; c++)
for (int d = 0; d < 8; d++)
if (a == d || b == d || c == d)
for (int e = 0; e < 8; e++)
if (a == e || b == e || c == e || d == e)
for (int f = 0; f < 8; f++)
if (a == f || b == f || c == f || d == f || e == f)
for (int g = 0; g < 8; g++)
if (a == g || b == g || c == g || d == g || e == g || f == g)
for (int h = 0; h < 8; h++)
if (a == h || b == h || c == h || d == h || e == h || f == h || g == h)
tester = new Scale(new int[] { weights[a], weights[b], weights[c], weights[d], weights[e], weights[f], weights[g], weights[h] });
tries = tester.Solve(false);