aboutsummaryrefslogtreecommitdiff
path: root/challenge-247/luca-ferrari/postgresql/ch-2.sql
blob: 040bc20a14e90596117d08f01b7147461f0e365c (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
--
-- Perl Weekly Challenge 247
-- Task 2
--
-- See <https://perlweeklychallenge.org/blog/perl-weekly-challenge-247/>
--

CREATE SCHEMA IF NOT EXISTS pwc247;

CREATE OR REPLACE FUNCTION
pwc247.task2_plpgsql( string text )
RETURNS TABLE( needle text, repetitions int )
AS $CODE$

DECLARE
	needle text;
BEGIN
	CREATE TEMPORARY TABLE IF NOT EXISTS repetitions( needle text, repetition int );
	TRUNCATE repetitions;

	FOR i IN 1 .. length( string ) LOOP
	    needle := substr( string, i, 2 );

	    INSERT INTO repetitions
	    SELECT needle, ( SELECT count(*) FROM  regexp_matches( string, needle, 'g' )f );

	END LOOP;

	RETURN QUERY
	SELECT *
	FROM repetitions
	ORDER BY repetition DESC
	LIMIT 1;

END
$CODE$
LANGUAGE plpgsql;