How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N [duplicate]

In The Art of Computer Programming, Volume 2: Seminumerical Algorithms, Third Edition, Knuth describes the following selection sampling algorithm: Algorithm S (Selection sampling technique). To select n records at random from a set of N, where 0 < n ≤ N. S1. [Initialize.] Set t ← 0, m ← 0. (During this algorithm, m represents … Read more

Can PostgreSQL have a uniqueness constraint on array elements?

The righteous path You might want to reconsider normalizing your schema. It is not necessary for everyone to “join for even the simplest query”. Create a VIEW for that. Table could look like this: CREATE TABLE hostname ( hostname_id serial PRIMARY KEY , host_id int REFERENCES host(host_id) ON UPDATE CASCADE ON DELETE CASCADE , hostname … Read more

Return rows matching elements of input array in plpgsql function

This works: CREATE OR REPLACE FUNCTION avg_purchases(last_names text[] = ‘{}’) RETURNS TABLE(last_name text, avg_purchase_size float8) LANGUAGE sql AS $func$ SELECT last_name, avg(purchase_size)::float8 FROM purchases WHERE last_name = ANY($1) GROUP BY last_name $func$; Call: SELECT * FROM avg_purchases(‘{foo,Bar,baz,”}weird_name”$$”}’); Or (example with dollar-quoting): SELECT * FROM avg_purchases($x${foo,Bar,baz,”}weird_name’$$”}$x$); How to quote string literals: Insert text with single quotes … Read more

How to slice an array in Bash

See the Parameter Expansion section in the Bash man page. A[@] returns the contents of the array, :1:2 takes a slice of length 2, starting at index 1. A=( foo bar “a b c” 42 ) B=(“${A[@]:1:2}”) C=(“${A[@]:1}”) # slice to the end of the array echo “${B[@]}” # bar a b c echo “${B[1]}” … Read more