summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/coroutines/generator.c
blob: 3f51ce9ccce8c0d30167945f4b9ab35e95a3fd37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// https://quuxplusone.github.io/blog/2019/03/06/pythagorean-triples/

#include <stdio.h>
#include <stc/coroutine.h>

typedef struct {
    int size;
    int a, b, c;
} Triple;

cco_iter_struct(Triple,
    int count;
);

int Triple_next(Triple_iter* it) {
    Triple* g = it->ref; // note: before cco_routine
    cco_routine(it)
    {
        for (g->c = 5;; ++g->c) {
            for (g->a = 1; g->a < g->c; ++g->a) {
                for (g->b = g->a; g->b < g->c; ++g->b) {
                    if (g->a*g->a + g->b*g->b == g->c*g->c) {
                        if (it->count++ == g->size)
                            cco_return;
                        cco_yield();
                    }
                }
            }
        }
        cco_cleanup:
        it->ref = NULL;
        puts("done");
    }
    return 0;
}

Triple_iter Triple_begin(Triple* g) {
    Triple_iter it = {.ref=g};
    Triple_next(&it);
    return it;
}


int main(void)
{
    puts("Pythagorean triples; stops at 100 triples or c >= 100:");
    Triple triple = {.size=100};
    c_foreach (i, Triple, triple) {
        if (i.ref->c < 100)
            printf("%u: (%d, %d, %d)\n", i.count, i.ref->a, i.ref->b, i.ref->c);
        else
            cco_stop(&i);
    }
}