I have a 3x3 grid of bools and I’m trying to work out all the combinations I can have around the center cell. I.E.
I tried to work it out on a spreadsheet, but keep getting lost, as I don’t want any repeated combinations. I’m trying to think up a way of writing a function that will work out all the combinations and output them to the console so I can copy and paste it into notepad. I know I’ll need a list to store the outcomes to reference before writing to debug console, but can’t come up with an iteration loop.
Any ideas?
Take a look at this awesome post:
Tile Bitmasking
Scroll down to the “8-Bit Bitmasking” section, I think it might help in a way.
Here’s a class which uses Heap’s recursive algorithm for working out all possible permutations of an array. Permutations are ordered, which means 4, 3 is the same as 3, 4 so it doesn’t count as a permutation. I used an array of numbers from 1 to 9, and wherever the middle item (5) is in the middle, the permutation is added to a list of permutations. There are a lot here, since without the middle item condition, the length of the list would be 9! (factorial):
class Heap
{
public static void Main()
{
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
HeapGen heapGen = new HeapGen(a);
foreach (int[] array in heapGen.GeneratedPermutations)
{
foreach (int item in array)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
}
class HeapGen
{
public List<int[]> GeneratedPermutations = new List<int[]>();
public HeapGen(int[] data)
{
HeapPermutation(data, data.Length, data.Length);
SiftThroughArray();
}
// Generating permutations using Heap Algorithm
void HeapPermutation(int[] a, int size, int n)
{
// if size becomes 1 then prints the obtained
// permutation
if (size == 1)
{
List<int> permutation = new List<int>();
foreach (int item in a)
{
//Console.Write(item + " ");
permutation.Add(item);
}
//Console.WriteLine();
GeneratedPermutations.Add(permutation.ToArray());
}
for (int i = 0; i < size; i++)
{
HeapPermutation(a, size - 1, n);
// if size is odd, swap 0th i.e (first) and
// (size-1)th i.e (last) element
if (size % 2 == 1)
{
int temp = a[0];
a[0] = a[size - 1];
a[size - 1] = temp;
}
// If size is even, swap ith and
// (size-1)th i.e (last) element
else
{
int temp = a*;*
a = a[size - 1];
a[size - 1] = temp;
}
}
}
void SiftThroughArray()
{
List<int[]> NormalPermutations = new List<int[]>();
for (int i = 0; i < GeneratedPermutations.Count; i++)
{
int[] array = GeneratedPermutations*;*
// Any array without the middle item in the same place
// should be removed
if (array[4] == 5)
{
NormalPermutations.Add(array);
}
}
GeneratedPermutations = NormalPermutations;
}
}
Now that I think about it… This doesn’t really help.