Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created May 8, 2012 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcd/2633345 to your computer and use it in GitHub Desktop.
Save jmcd/2633345 to your computer and use it in GitHub Desktop.
Creates permutations of an integer for a fixed number of '1' bits
public class ComboMaskFactory
{
private int _current;
private readonly int _lim;
public ComboMaskFactory(int maxNumberOfBitsInMask, int numberOfOneBits)
{
if (maxNumberOfBitsInMask > 32) throw new Exception("ComboMaskFactory can only be used with maxNumberOfBitsInMask up to 32.");
_current = GetLowestValueUsingSuppliedNumberOfOneBits(numberOfOneBits);
_lim = 1 + _current << maxNumberOfBitsInMask - numberOfOneBits;
}
private int GetLowestValueUsingSuppliedNumberOfOneBits(int numberOfOneBits)
{
var result = 0;
for (var i = 0; i < numberOfOneBits; i++)
{
result += (int)Math.Pow(2, i);
}
return result;
}
private static int GetLowestBit(int l)
{
return l & -l;
}
public bool HasNext()
{
return _current < _lim;
}
public int Next()
{
var result = _current;
MoveNext();
return result;
}
private void MoveNext()
{
var lowestBitOfCurrent = GetLowestBit(_current);
var resultA = _current + lowestBitOfCurrent;
var lowestBitOfResultA = GetLowestBit(resultA);
var resultB = ((lowestBitOfResultA / lowestBitOfCurrent) >> 1) - 1;
_current = resultA | resultB;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment