aboutsummaryrefslogtreecommitdiff
path: root/challenge-194/luca-ferrari/postgresql/ch-2.sql
blob: e918f5b89b9194eab6d922543bda903bb0de3b43 (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
-- Perl Weekly Challenge 194
-- Task 2

CREATE SCHEMA IF NOT EXISTS pwc194;

CREATE OR REPLACE FUNCTION
pwc194.task2_plpgsql( what text)
RETURNS int
AS $CODE$
DECLARE
	t text;
	current_max int;
	current_min int;
	current_count int;
BEGIN
	CREATE TEMPORARY TABLE IF NOT EXISTS counter ( l char, c int, PRIMARY KEY(l) );
	TRUNCATE counter;

	FOR t IN SELECT v FROM regexp_split_to_table( what, '' ) v LOOP
	    INSERT INTO counter AS cnt ( l, c )
	    VALUES ( t, 1 )
	    ON CONFLICT (l)
	    DO UPDATE SET c = cnt.c + 1;
	END LOOP;

	SELECT max(c), min(c)
	INTO current_max, current_min
	FROM counter;

	IF current_max - current_min <> 1 THEN
	   RETURN 0;
	END IF;

	SELECT count(*)
	INTO current_count
	FROM counter
	WHERE c = current_max;

	IF current_count <> 1 THEN
	   RETURN 0;
	END IF;

	RETURN 1;
END
$CODE$
LANGUAGE plpgsql;