Created
December 28, 2013 13:44
-
-
Save Rhomboid/8159643 to your computer and use it in GitHub Desktop.
Very stupid sort (trolling homework)
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
/* http://codegolf.stackexchange.com/questions/16226/trolling-homework-questions-sorting */ | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
void read_some_doubles(double **data, size_t *size) | |
{ | |
char buf[512], *endptr; | |
double d; | |
size_t capacity = 16; | |
*size = 0; | |
*data = malloc(sizeof(double) * capacity); | |
while(fgets(buf, sizeof(buf), stdin)) { | |
d = strtod(buf, &endptr); | |
if(endptr == buf) | |
continue; | |
if(*size == capacity) { | |
capacity = capacity * 3 / 2; | |
*data = realloc(*data, sizeof(double) * capacity); | |
} | |
(*data)[(*size)++] = d; | |
} | |
} | |
void worker(double *data, size_t size, size_t myid, int (*pipes)[2]) | |
{ | |
char buf[256]; | |
size_t i; | |
for(i = 0; i < size; i++) | |
if(data[i] <= data[myid]) | |
close(pipes[i][1]); | |
while(read(pipes[myid][0], &buf, 1) != 0) | |
; | |
snprintf(buf, sizeof(buf), "%g\n", data[myid]); | |
write(1, buf, strlen(buf)); | |
exit(0); | |
} | |
int main(void) | |
{ | |
double *data; | |
size_t num, i; | |
int (*pipes)[2]; | |
read_some_doubles(&data, &num); | |
pipes = malloc(sizeof(int) * 2 * num); | |
for(i = 0; i < num; i++) | |
if(pipe(pipes[i]) < 0) | |
perror("input too large"), exit(1); | |
for(i = 0; i < num; i++) | |
if(fork() == 0) | |
worker(data, num, i, pipes); | |
for(i = 0; i < num; i++) | |
close(pipes[i][1]); | |
for(i = 0; i < num; i++) | |
wait(NULL); | |
return 0; | |
} |
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
$ gcc -Wall -O2 trollsort.c | |
$ echo 0 1 4.332 1e100 1 -12 99 | tr ' ' '\n' | ./a.out | |
-12 | |
0 | |
1 | |
1 | |
4.332 | |
99 | |
1e+100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment