summaryrefslogtreecommitdiffhomepage
path: root/misc/examples/generator.c
diff options
context:
space:
mode:
authorTyge Løvset <[email protected]>2023-03-01 14:54:36 +0100
committerTyge Løvset <[email protected]>2023-03-01 14:54:36 +0100
commita203314647b5c37c7e40230551457f006ff36cd5 (patch)
tree3d8b9b29595577bee0926434820d602a29487ea3 /misc/examples/generator.c
parent78a7e85535fd02e643bf98103223d4218e80133f (diff)
downloadSTC-modified-a203314647b5c37c7e40230551457f006ff36cd5.tar.gz
STC-modified-a203314647b5c37c7e40230551457f006ff36cd5.zip
Reverted example moves.
Diffstat (limited to 'misc/examples/generator.c')
-rw-r--r--misc/examples/generator.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/misc/examples/generator.c b/misc/examples/generator.c
new file mode 100644
index 00000000..f83ff3f2
--- /dev/null
+++ b/misc/examples/generator.c
@@ -0,0 +1,53 @@
+// https://quuxplusone.github.io/blog/2019/03/06/pythagorean-triples/
+
+#include <stc/algo/coroutine.h>
+#include <stdio.h>
+
+typedef struct {
+ int n;
+ int a, b, c;
+} Triple_value, Triple;
+
+typedef struct {
+ Triple_value* ref;
+ int cco_state;
+} Triple_iter;
+
+bool Triple_next(Triple_iter* it) {
+ Triple_value* t = it->ref;
+ cco_begin(it);
+ for (t->c = 1;; ++t->c) {
+ for (t->a = 1; t->a < t->c; ++t->a) {
+ for (t->b = t->a; t->b < t->c; ++t->b) {
+ if (t->a*t->a + t->b*t->b == t->c*t->c) {
+ cco_yield(true);
+ if (t->n-- == 1) cco_return;
+ }
+ }
+ }
+ }
+ cco_final:
+ it->ref = NULL;
+ cco_end(false);
+}
+
+Triple_iter Triple_begin(Triple* t) {
+ Triple_iter it = {t};
+ if (t->n > 0) Triple_next(&it);
+ else it.ref = NULL;
+ return it;
+}
+
+
+int main()
+{
+ puts("Pythagorean triples with c < 100:");
+ Triple t = {INT32_MAX};
+ c_foreach (i, Triple, t)
+ {
+ if (i.ref->c < 100)
+ printf("%u: (%d, %d, %d)\n", INT32_MAX - i.ref->n + 1, i.ref->a, i.ref->b, i.ref->c);
+ else
+ cco_stop(&i);
+ }
+}