23 lines
558 B
Plaintext
23 lines
558 B
Plaintext
CREATE OR REPLACE FUNCTION combinations(n, k) as table (
|
|
WITH RECURSIVE cte(current, remaining) AS (
|
|
-- start with empty combination and the full list
|
|
SELECT
|
|
[],
|
|
range(1, n + 1)
|
|
UNION ALL
|
|
-- recursive case: add one item to the current combination
|
|
SELECT
|
|
current || remaining[j:j],
|
|
remaining[j+1:]
|
|
FROM cte, range(1, length(remaining)+1) _(j)
|
|
WHERE length(current) < k
|
|
)
|
|
SELECT current AS combination
|
|
FROM cte
|
|
WHERE length(current) = k
|
|
);
|
|
|
|
## Example:
|
|
FROM combinations(5,3)
|
|
ORDER BY combination;
|