Refactor HistogramNd for better code reuse