Skip to content

Instantly share code, notes, and snippets.

@IlyaOrson
Created March 4, 2020 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IlyaOrson/22b08dc0a6882b52c8083cc95cb66098 to your computer and use it in GitHub Desktop.
Save IlyaOrson/22b08dc0a6882b52c8083cc95cb66098 to your computer and use it in GitHub Desktop.
Chinese restaurant process
"""
Generate table assignments for 'n' customers,
according to a Chinese Restaurant Process with dispersion parameter 'α'
Returns an array of integer table assignments
"""
function crp(n, α)
@assert n > 0
table_assignments = zeros(Int, n)
table_assignments[1] = 1 # first customer sits at table 1
next_open_table = 2
for i in 2:n
if rand() < α/(α+i)
# Customers sits at new table.
table_assignments[i] = next_open_table
next_open_table += 1
else
# Customer sits at an existing table.
# He chooses which table to sit at by giving equal weight to each
# customer already sitting at a table.
which_table = rand(view(table_assignments,1:i-1))
table_assignments[i] = which_table
end
end
return table_assignments
end
using Plots
gr()
@time sample = crp(10^7, 10)
Plots.histogram(sample)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment