Created
May 8, 2012 07:49
-
-
Save jmcd/2633345 to your computer and use it in GitHub Desktop.
Creates permutations of an integer for a fixed number of '1' bits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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