aboutsummaryrefslogtreecommitdiffstats
path: root/enum.c
diff options
context:
space:
mode:
authorakr <akr@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-05-05 14:12:03 +0000
committerakr <akr@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-05-05 14:12:03 +0000
commit693703c3918d5ea89997acd21ea335f8b98bf980 (patch)
treebac2edc512561276d4e4322bf1da950ce257c71d /enum.c
parent7a69a3583c2235c0ad3ad0705aa2f08cbe2d76bb (diff)
downloadruby-693703c3918d5ea89997acd21ea335f8b98bf980.tar.gz
[DOC]
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@45829 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'enum.c')
-rw-r--r--enum.c45
1 files changed, 45 insertions, 0 deletions
diff --git a/enum.c b/enum.c
index 8496636877..d9ae1e3df6 100644
--- a/enum.c
+++ b/enum.c
@@ -1777,6 +1777,51 @@ max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
*
* a = %w[albatross dog horse]
* a.max_by(2) {|x| x.length } #=> ["horse", "albatross"]
+ *
+ * enum.max_by(n) can be used to implement weighted random sampling.
+ * Following example implements and use Enumerable#wsample.
+ *
+ * module Enumerable
+ * # weighted random sampling.
+ * #
+ * # Pavlos S. Efraimidis, Paul G. Spirakis
+ * # Weighted random sampling with a reservoir
+ * # Information Processing Letters
+ * # Volume 97, Issue 5 (16 March 2006)
+ * def wsample(n)
+ * self.max_by(n) {|v| rand ** (1.0/yield(v)) }
+ * end
+ * end
+ * e = (-20..20).to_a*10000
+ * a = e.wsample(20000) {|x|
+ * Math.exp(-(x/5.0)**2) # normal distribution
+ * }
+ * # a is 20000 samples from e.
+ * p a.length #=> 20000
+ * h = a.group_by {|x| x }
+ * -10.upto(10) {|x| puts "*" * (h[x].length/30.0).to_i if h[x] }
+ * #=> *
+ * # ***
+ * # ******
+ * # ***********
+ * # ******************
+ * # *****************************
+ * # *****************************************
+ * # ****************************************************
+ * # ***************************************************************
+ * # ********************************************************************
+ * # ***********************************************************************
+ * # ***********************************************************************
+ * # **************************************************************
+ * # ****************************************************
+ * # ***************************************
+ * # ***************************
+ * # ******************
+ * # ***********
+ * # *******
+ * # ***
+ * # *
+ *
*/
static VALUE