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

ruby-changes:25444

From: marcandre <ko1@a...>
Date: Wed, 7 Nov 2012 02:11:14 +0900 (JST)
Subject: [ruby-changes:25444] marcandRe: r37501 (trunk): * array.c (rb_ary_permutation): Support for Array#permutation.size

marcandre	2012-11-07 02:11:06 +0900 (Wed, 07 Nov 2012)

  New Revision: 37501

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

  Log:
    * array.c (rb_ary_permutation): Support for Array#permutation.size
      [Feature #6636]

  Modified files:
    trunk/array.c
    trunk/test/ruby/test_enumerator.rb

Index: array.c
===================================================================
--- array.c	(revision 37500)
+++ array.c	(revision 37501)
@@ -4324,6 +4324,29 @@
 }
 
 /*
+ * Returns the product of from, from-1, ..., from - how_many + 1.
+ * http://en.wikipedia.org/wiki/Pochhammer_symbol
+ */
+static VALUE
+descending_factorial(long from, long how_many)
+{
+    VALUE cnt = LONG2FIX(how_many >= 0);
+    while(how_many-- > 0) {
+        cnt = rb_funcall(cnt, '*', 1, LONG2FIX(from--));
+    }
+    return cnt;
+}
+
+static VALUE
+rb_ary_permutation_size(VALUE ary, VALUE args)
+{
+    long n = RARRAY_LEN(ary);
+    long k = (args && (RARRAY_LEN(args) > 0)) ? NUM2LONG(RARRAY_PTR(args)[0]) : n;
+
+    return descending_factorial(n, k);
+}
+
+/*
  *  call-seq:
  *     ary.permutation { |p| block }          -> ary
  *     ary.permutation                        -> Enumerator
@@ -4358,7 +4381,7 @@
     long r, n, i;
 
     n = RARRAY_LEN(ary);                  /* Array length */
-    RETURN_ENUMERATOR(ary, argc, argv);   /* Return Enumerator if no block */
+    RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_permutation_size);   /* Return enumerator if no block */
     rb_scan_args(argc, argv, "01", &num);
     r = NIL_P(num) ? n : NUM2LONG(num);   /* Permutation size from argument */
 
Index: test/ruby/test_enumerator.rb
===================================================================
--- test/ruby/test_enumerator.rb	(revision 37500)
+++ test/ruby/test_enumerator.rb	(revision 37501)
@@ -429,5 +429,18 @@
     end
   end
 
+  def check_consistency_for_combinatorics(method)
+    [ [], [:a, :b, :c, :d, :e] ].product([-2, 0, 2, 5, 6]) do |array, arg|
+      assert_equal array.send(method, arg).to_a.size, array.send(method, arg).size,
+        "inconsistent size for #{array}.#{method}(#{arg})"
+    end
+  end
+
+  def test_size_for_array_combinatorics
+    check_consistency_for_combinatorics(:permutation)
+    assert_equal 24, [0, 1, 2, 4].permutation.size
+    assert_equal 2933197128679486453788761052665610240000000,
+      (1..42).to_a.permutation(30).size # 1.upto(42).inject(:*) / 1.upto(12).inject(:*)
+  end
 end
 

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

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