How to find all combinations (subset) of any size of an array in postgresql -
How to find all combinations (subset) of any size of an array in postgresql -
this question has reply here:
array combinations without repetition 1 replygiven array, how find combinations (subsets) of elements of size in postgresql. example, given array [1, 2, 3, 4] combinations of size 3 be
[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]
order not of import in combinations , hence [1, 2, 3] , [3, 2, 1] considered same combination.
update: size of combinations required must specified @ run-time parameter, same function/query can used find combinations of size n <= size of array. the existing solution works combinations of size 3 , needs 1 additional cross bring together every increment in size, not practical.
the next function produces combinations of requested size set of rows 1 combination per row:
create or replace function get_combinations(source anyarray, size int) returns setof anyarray $$ recursive combinations(combination, indices) ( select source[i:i], array[i] generate_subscripts(source, 1) union select c.combination || source[j], c.indices || j combinations c, generate_subscripts(source, 1) j j > all(c.indices) , array_length(c.combination, 1) < size ) select combination combinations array_length(combination, 1) = size; $$ language sql;
this function polymorphic in array type.
arrays postgresql combinations plpgsql
Comments
Post a Comment