Skip to content

Instantly share code, notes, and snippets.

@gabehesse
Created May 2, 2011 22:46
Show Gist options
  • Save gabehesse/952517 to your computer and use it in GitHub Desktop.
Save gabehesse/952517 to your computer and use it in GitHub Desktop.
Power set P(S) in C#
var list = new List<char> { 'A', 'B', 'C' };
var result = new List<List<char>> ();
for (int i = 0; i < (1 << list.Count); i++) { // 1 << n == the n-th power of 2
var sublist = new List<char> ();
for (int j = 0; j < list.Count; j++) { // analyze each bit in "i"
if ((i & (1 << j)) != 0) { // if the j-th bit of i is set...
sublist.Add (list [j]); // add the item to the current sublist
}
}
result.Add (sublist); // add the current sublist to the final result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment