Print every subset of {a, b, c} using the bits of a counter.
Solution
main.c
#include <stdio.h>
int main(void) {
const char items[] = {'a', 'b', 'c'};
int n = 3;
for (unsigned mask = 0; mask < (1u << n); mask++) {
printf("{");
for (int i = 0; i < n; i++)
if (mask & (1u << i)) /* bit i says: include item i */
printf("%c", items[i]);
printf("}%s", mask + 1 < (1u << n) ? " " : "\n");
}
return 0;
}
Output Verified by compiling and running
{} {a} {b} {ab} {c} {ac} {bc} {abc}
The numbers 0 to 2ⁿ − 1 contain every combination of n bits, and each bit decides whether one item is in the subset. This is the standard way to brute-force small sets in contests.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!