From b91c8355370302f29a2380e43685737ff644b9f2 Mon Sep 17 00:00:00 2001
From: Luca Ferrari <fluca1978@gmail.com>
Date: Mon, 4 Apr 2022 10:21:30 +0200
Subject: Task 1 done in Pl/Perl

---
 challenge-159/luca-ferrari/postgresql/ch-1.sql | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 challenge-159/luca-ferrari/postgresql/ch-1.sql

(limited to 'challenge-159/luca-ferrari/postgresql/ch-1.sql')

diff --git a/challenge-159/luca-ferrari/postgresql/ch-1.sql b/challenge-159/luca-ferrari/postgresql/ch-1.sql
new file mode 100644
index 0000000000..da8824c0c2
--- /dev/null
+++ b/challenge-159/luca-ferrari/postgresql/ch-1.sql
@@ -0,0 +1 @@
+-- Perl Weekly Challenge 159
-- 
cgit 


From 8409efbb8a1f588f4bb1d0e4134cdc03b6c6d7f8 Mon Sep 17 00:00:00 2001
From: Luca Ferrari <fluca1978@gmail.com>
Date: Mon, 4 Apr 2022 10:34:19 +0200
Subject: Task 1 done in plpgsql

---
 challenge-159/luca-ferrari/postgresql/ch-1.sql | 69 ++++++++++++++++++++++++++
 1 file changed, 69 insertions(+)

(limited to 'challenge-159/luca-ferrari/postgresql/ch-1.sql')

diff --git a/challenge-159/luca-ferrari/postgresql/ch-1.sql b/challenge-159/luca-ferrari/postgresql/ch-1.sql
index da8824c0c2..1ebd6c5112 100644
--- a/challenge-159/luca-ferrari/postgresql/ch-1.sql
+++ b/challenge-159/luca-ferrari/postgresql/ch-1.sql
@@ -1 +1,70 @@
 -- Perl Weekly Challenge 159
+
+
+CREATE SCHEMA IF NOT EXISTS pwc159;
+
+
+CREATE OR REPLACE FUNCTION
+pwc159.farey_not_unique( n int )
+RETURNS TABLE( f text, v numeric )
+AS $CODE$
+DECLARE
+     numerator   int;
+     denominator int;
+     dd          int;
+     nn          int;
+BEGIN
+
+        -- bootstrap term
+        SELECT '0/1', 0
+        INTO f, v;
+
+        RETURN NEXT;
+
+
+        FOR denominator IN 2 .. n  LOOP
+            FOR numerator IN  1 .. denominator  LOOP
+                nn := numerator;
+                dd := denominator;
+
+                IF dd % nn = 0 THEN
+                   dd := dd / nn;
+                   nn := 1;
+                END IF;
+
+                IF nn % dd = 0 THEN
+                   nn := nn / dd;
+                   dd := 1;
+                END IF;
+
+                IF nn / dd = 1 THEN
+                   CONTINUE;
+                END IF;
+
+                SELECT nn || '/' || dd, nn/dd::numeric
+                INTO  f, v;
+
+                RETURN NEXT;
+
+            END LOOP;
+        END LOOP;
+
+        -- end term
+        SELECT '1/1', 1
+        INTO f, v;
+
+        RETURN NEXT;
+
+RETURN;
+END
+$CODE$
+LANGUAGE plpgsql;
+
+
+WITH farey AS (
+     SELECT distinct( f ), v
+     FROM pwc159.farey_not_unique( 5 )
+     ORDER BY v
+)
+SELECT f
+FROM farey;
-- 
cgit 

