Skip to content

Instantly share code, notes, and snippets.

@fschr
Created October 11, 2016 22:40
Show Gist options
  • Save fschr/2c6332513ef96b968c9dd25205e3d766 to your computer and use it in GitHub Desktop.
Save fschr/2c6332513ef96b968c9dd25205e3d766 to your computer and use it in GitHub Desktop.
super fast print powerset
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#define BUF_SIZE 4096
void print_powerset(uint32_t n) {
char buf[BUF_SIZE];
int offset = 0;
for (uint32_t i = 0; i < (1 << n); i++) {
for (uint32_t j = 0; (i >> j) != 0; j++) {
if ((i >> j) & 1) {
if (j+1 < 10) {
buf[offset++] = j+1 + 48;
} else {
buf[offset++] = ((j+1)%100)/10 + 48;
buf[offset++] = (j+1)%10 + 48;
}
buf[offset++] = ' ';
if (BUF_SIZE - offset < 13) {
write(1, buf, offset);
offset = 0;
}
}
}
buf[offset++] = '\n';
}
write(1, buf, offset);
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "expected one argument\n");
return 1;
}
long i = strtol(argv[1], NULL, 10);
if (i <= 0) {
fprintf(stderr, "expected positive integer\n");
return 1;
}
print_powerset((uint32_t)i);
}
@fschr
Copy link
Author

fschr commented Oct 11, 2016

not all of the #includes are necessary

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment