Direct Sampling


DIRECT-SAMPLING(bn, query, numSamples)
    weighted_set ← {} // A map that stores (sample, count) pairs

    for s=1...numSamples

        sample ← {}
        for node Xi in bn
            value ← randomly sample from p(Xi | parents(Xi))

            if Xi is a query variable
                sample.append(value)
            end
        end    

        //Sample now contains the sampled values for all of the query variables
        weighted_set{sample} += 1 
    end

    return weighted_set.normalize()
end