Created
March 25, 2016 18:38
-
-
Save knugie/4d8d27225b0ad3e04479 to your computer and use it in GitHub Desktop.
Cluster numbers by their distance to each other
This file contains 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
values = 20.times.map{rand(100)+200} | |
delta = 10 | |
min, max = values.minmax | |
offset = min - delta / 2 | |
grouped = values.group_by { |value| (value - offset) / delta } | |
Hash[grouped.sort] | |
=begin | |
[1] pry(main)> values = 20.times.map{rand(100)+200} | |
=> [238, | |
231, | |
293, | |
243, | |
256, | |
228, | |
256, | |
256, | |
234, | |
206, | |
258, | |
217, | |
215, | |
294, | |
207, | |
204, | |
226, | |
292, | |
285, | |
205] | |
[2] pry(main)> delta = 10 | |
=> 10 | |
[3] pry(main)> min, max = values.minmax | |
=> [204, 294] | |
[4] pry(main)> offset = min - delta / 2 | |
=> 199 | |
[5] pry(main)> grouped = values.group_by { |value| (value - offset) / delta } | |
=> {3=>[238, 231, 234], | |
9=>[293, 294, 292], | |
4=>[243], | |
5=>[256, 256, 256, 258], | |
2=>[228, 226], | |
0=>[206, 207, 204, 205], | |
1=>[217, 215], | |
8=>[285]} | |
[6] pry(main)> Hash[grouped.sort] | |
=> {0=>[206, 207, 204, 205], | |
1=>[217, 215], | |
2=>[228, 226], | |
3=>[238, 231, 234], | |
4=>[243], | |
5=>[256, 256, 256, 258], | |
8=>[285], | |
9=>[293, 294, 292]} | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment