private static (ulong MagicMultiplier, ulong[] MovesMasks) FindMagicMultiplier(Dictionary <ulong, ulong> occupancyToMovesMask, int shift, ulong?knownMagicMultiplier) { var indexBits = 64 - shift; var indexLength = (int)Math.Pow(2d, indexBits); var movesMasks = new ulong[indexLength]; var occupancies = new List <ulong>(occupancyToMovesMask.Keys); NextMagicMultiplier: var magicMultiplier = knownMagicMultiplier ?? SafeRandom.NextULong(); // Clear moves masks. for (var maskIndex = 0; maskIndex < movesMasks.Length; maskIndex++) { movesMasks[maskIndex] = 0; } for (var occupancyIndex = 0; occupancyIndex < occupancies.Count; occupancyIndex++) { var occupancy = occupancies[occupancyIndex]; var magicIndex = GetMagicIndex(occupancy, magicMultiplier, shift); var movesMask = movesMasks[magicIndex]; if (movesMask == 0) { movesMasks[magicIndex] = occupancyToMovesMask[occupancy]; // Moves mask not yet added to unique moves array. } else if (movesMask != occupancyToMovesMask[occupancy]) { goto NextMagicMultiplier; // Moves mask already added to unique moves array but mask is incorrect. } } // Found magic multiplier that maps to correct moves index for all occupancies. return(magicMultiplier, movesMasks); }