Created
October 11, 2016 22:40
-
-
Save fschr/2c6332513ef96b968c9dd25205e3d766 to your computer and use it in GitHub Desktop.
super fast print powerset
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
#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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
not all of the
#include
s are necessary