Rejection Sampling


REJECTION-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 an evidence variable
                if sampled value does not match evidence
                    Abandon the sample and start over
                end
            end
            

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

        //Sample now contains the sampled values for all of the query variables
        //The sampled values are guaranteed to be consistent with the evidence
        weighted_set{sample} += 1 
    end

    return weighted_set.normalize()
end