Created
December 9, 2008 02:23
-
-
Save besquared/33727 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def histogram(numbers) | |
| hist = {} | |
| numbers.each do |n| | |
| hist[n] = 0 if hist[n].nil? | |
| hist[n] += 1 | |
| end | |
| hist | |
| end | |
| # | |
| # Returns the index of the | |
| # | |
| def quantiles(histogram, percentage) | |
| quantiles = [] | |
| sum = histogram.values.inject(0){|n, i| n += i} | |
| total = 0 | |
| histogram.keys.sort.each do |key| | |
| total += histogram[key] | |
| quantiles << key if total >= ((quantiles.length * percentage) * sum) | |
| end | |
| quantiles | |
| end | |
| numbers = [] | |
| 0.upto(100) do |i| | |
| numbers << i | |
| end | |
| #[0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5] | |
| hist = histogram(numbers) | |
| puts quantiles(hist, 0.25) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment