[前][次][番号順一覧][スレッド一覧]

ruby-changes:33748

From: akr <ko1@a...>
Date: Mon, 5 May 2014 23:12:08 +0900 (JST)
Subject: [ruby-changes:33748] akr:r45829 (trunk): [DOC]

akr	2014-05-05 23:12:03 +0900 (Mon, 05 May 2014)

  New Revision: 45829

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=45829

  Log:
    [DOC]

  Modified files:
    trunk/enum.c
Index: enum.c
===================================================================
--- enum.c	(revision 45828)
+++ enum.c	(revision 45829)
@@ -1777,6 +1777,51 @@ max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, a https://github.com/ruby/ruby/blob/trunk/enum.c#L1777
  *
  *     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

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]