Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-array-ext/mrblib/array.rb

raw
1 class Array
2 ##
3 # call-seq:
4 # ary.uniq! -> ary or nil
5 # ary.uniq! { |item| ... } -> ary or nil
6 #
7 # Removes duplicate elements from +self+.
8 # Returns <code>nil</code> if no changes are made (that is, no
9 # duplicates are found).
10 #
11 # a = [ "a", "a", "b", "b", "c" ]
12 # a.uniq! #=> ["a", "b", "c"]
13 # b = [ "a", "b", "c" ]
14 # b.uniq! #=> nil
15 # c = [["student","sam"], ["student","george"], ["teacher","matz"]]
16 # c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
17 #
18 def uniq!(&block)
19 hash = {}
20 if block
21 self.each do |val|
22 key = block.call(val)
23 hash[key] = val unless hash.key?(key)
24 end
25 result = hash.values
26 else
27 hash = {}
28 self.each do |val|
29 hash[val] = val
30 end
31 result = hash.keys
32 end
33 if result.size == self.size
34 nil
35 else
36 self.replace(result)
37 end
38 end
39
40 ##
41 # call-seq:
42 # ary.uniq -> new_ary
43 # ary.uniq { |item| ... } -> new_ary
44 #
45 # Returns a new array by removing duplicate values in +self+.
46 #
47 # a = [ "a", "a", "b", "b", "c" ]
48 # a.uniq #=> ["a", "b", "c"]
49 #
50 # b = [["student","sam"], ["student","george"], ["teacher","matz"]]
51 # b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
52 #
53 def uniq(&block)
54 ary = self[0..-1]
55 ary.uniq!(&block)
56 ary
57 end
58
59 ##
60 # call-seq:
61 # ary - other_ary -> new_ary
62 #
63 # Array Difference---Returns a new array that is a copy of
64 # the original array, removing any items that also appear in
65 # <i>other_ary</i>. (If you need set-like behavior, see the
66 # library class Set.)
67 #
68 # [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
69 #
70 def -(elem)
71 raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
72
73 hash = {}
74 array = []
75 idx = 0
76 len = elem.size
77 while idx < len
78 hash[elem[idx]] = true
79 idx += 1
80 end
81 idx = 0
82 len = size
83 while idx < len
84 v = self[idx]
85 array << v unless hash[v]
86 idx += 1
87 end
88 array
89 end
90
91 ##
92 # call-seq:
93 # ary.difference(other_ary1, other_ary2, ...) -> new_ary
94 #
95 # Returns a new array that is a copy of the original array, removing all
96 # occurrences of any item that also appear in +other_ary+. The order is
97 # preserved from the original array.
98 #
99 def difference(*args)
100 ary = self
101 args.each do |x|
102 ary = ary - x
103 end
104 ary
105 end
106
107 ##
108 # call-seq:
109 # ary | other_ary -> new_ary
110 #
111 # Set Union---Returns a new array by joining this array with
112 # <i>other_ary</i>, removing duplicates.
113 #
114 # [ "a", "b", "c" ] | [ "c", "d", "a" ]
115 # #=> [ "a", "b", "c", "d" ]
116 #
117 def |(elem)
118 raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
119
120 ary = self + elem
121 ary.uniq! or ary
122 end
123
124 ##
125 # call-seq:
126 # ary.union(other_ary,...) -> new_ary
127 #
128 # Set Union---Returns a new array by joining this array with
129 # <i>other_ary</i>, removing duplicates.
130 #
131 # ["a", "b", "c"].union(["c", "d", "a"], ["a", "c", "e"])
132 # #=> ["a", "b", "c", "d", "e"]
133 #
134 def union(*args)
135 ary = self.dup
136 args.each do |x|
137 ary.concat(x)
138 ary.uniq!
139 end
140 ary
141 end
142
143 ##
144 # call-seq:
145 # ary & other_ary -> new_ary
146 #
147 # Set Intersection---Returns a new array
148 # containing elements common to the two arrays, with no duplicates.
149 #
150 # [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]
151 #
152 def &(elem)
153 raise TypeError, "cannot convert #{elem.class} into Array" unless elem.class == Array
154
155 hash = {}
156 array = []
157 idx = 0
158 len = elem.size
159 while idx < len
160 hash[elem[idx]] = true
161 idx += 1
162 end
163 idx = 0
164 len = size
165 while idx < len
166 v = self[idx]
167 if hash[v]
168 array << v
169 hash.delete v
170 end
171 idx += 1
172 end
173 array
174 end
175
176 ##
177 # call-seq:
178 # ary.intersection(other_ary,...) -> new_ary
179 #
180 # Set Intersection---Returns a new array containing elements common to
181 # this array and <i>other_ary</i>s, removing duplicates. The order is
182 # preserved from the original array.
183 #
184 # [1, 2, 3].intersection([3, 4, 1], [1, 3, 5]) #=> [1, 3]
185 #
186 def intersection(*args)
187 ary = self
188 args.each do |x|
189 ary = ary & x
190 end
191 ary
192 end
193
194 ##
195 # call-seq:
196 # ary.intersect?(other_ary) -> true or false
197 #
198 # Returns +true+ if the array and +other_ary+ have at least one element in
199 # common, otherwise returns +false+.
200 #
201 # a = [ 1, 2, 3 ]
202 # b = [ 3, 4, 5 ]
203 # c = [ 5, 6, 7 ]
204 # a.intersect?(b) #=> true
205 # a.intersect?(c) #=> false
206 def intersect?(ary)
207 raise TypeError, "cannot convert #{ary.class} into Array" unless ary.class == Array
208
209 hash = {}
210 if self.length > ary.length
211 shorter = ary
212 longer = self
213 else
214 shorter = self
215 longer = ary
216 end
217 idx = 0
218 len = shorter.size
219 while idx < len
220 hash[shorter[idx]] = true
221 idx += 1
222 end
223 idx = 0
224 len = size
225 while idx < len
226 v = longer[idx]
227 if hash[v]
228 return true
229 end
230 idx += 1
231 end
232 false
233 end
234
235 ##
236 # call-seq:
237 # ary.flatten -> new_ary
238 # ary.flatten(level) -> new_ary
239 #
240 # Returns a new array that is a one-dimensional flattening of this
241 # array (recursively). That is, for every element that is an array,
242 # extract its elements into the new array. If the optional
243 # <i>level</i> argument determines the level of recursion to flatten.
244 #
245 # s = [ 1, 2, 3 ] #=> [1, 2, 3]
246 # t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
247 # a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
248 # a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
249 # a = [ 1, 2, [3, [4, 5] ] ]
250 # a.flatten(1) #=> [1, 2, 3, [4, 5]]
251 #
252 def flatten(depth=nil)
253 res = Array.new(self)
254 res.flatten! depth
255 res
256 end
257
258 ##
259 # call-seq:
260 # ary.flatten! -> ary or nil
261 # ary.flatten!(level) -> array or nil
262 #
263 # Flattens +self+ in place.
264 # Returns <code>nil</code> if no modifications were made (i.e.,
265 # <i>ary</i> contains no subarrays.) If the optional <i>level</i>
266 # argument determines the level of recursion to flatten.
267 #
268 # a = [ 1, 2, [3, [4, 5] ] ]
269 # a.flatten! #=> [1, 2, 3, 4, 5]
270 # a.flatten! #=> nil
271 # a #=> [1, 2, 3, 4, 5]
272 # a = [ 1, 2, [3, [4, 5] ] ]
273 # a.flatten!(1) #=> [1, 2, 3, [4, 5]]
274 #
275 def flatten!(depth=nil)
276 modified = false
277 ar = []
278 idx = 0
279 len = size
280 while idx < len
281 e = self[idx]
282 if e.is_a?(Array) && (depth.nil? || depth > 0)
283 ar += e.flatten(depth.nil? ? nil : depth - 1)
284 modified = true
285 else
286 ar << e
287 end
288 idx += 1
289 end
290 if modified
291 self.replace(ar)
292 else
293 nil
294 end
295 end
296
297 # for efficiency
298 def reverse_each(&block)
299 return to_enum :reverse_each unless block
300
301 i = self.size - 1
302 while i>=0
303 block.call(self[i])
304 i -= 1
305 end
306 self
307 end
308
309 ##
310 # call-seq:
311 # ary.fetch(index) -> obj
312 # ary.fetch(index, default) -> obj
313 # ary.fetch(index) { |index| block } -> obj
314 #
315 # Tries to return the element at position +index+, but throws an IndexError
316 # exception if the referenced +index+ lies outside of the array bounds. This
317 # error can be prevented by supplying a second argument, which will act as a
318 # +default+ value.
319 #
320 # Alternatively, if a block is given it will only be executed when an
321 # invalid +index+ is referenced.
322 #
323 # Negative values of +index+ count from the end of the array.
324 #
325 # a = [ 11, 22, 33, 44 ]
326 # a.fetch(1) #=> 22
327 # a.fetch(-1) #=> 44
328 # a.fetch(4, 'cat') #=> "cat"
329 # a.fetch(100) { |i| puts "#{i} is out of bounds" }
330 # #=> "100 is out of bounds"
331 #
332
333 def fetch(n, ifnone=NONE, &block)
334 #warn "block supersedes default value argument" if !n.nil? && ifnone != NONE && block
335
336 idx = n
337 if idx < 0
338 idx += size
339 end
340 if idx < 0 || size <= idx
341 return block.call(n) if block
342 if ifnone == NONE
343 raise IndexError, "index #{n} outside of array bounds: #{-size}...#{size}"
344 end
345 return ifnone
346 end
347 self[idx]
348 end
349
350 ##
351 # call-seq:
352 # ary.fill(obj) -> ary
353 # ary.fill(obj, start [, length]) -> ary
354 # ary.fill(obj, range ) -> ary
355 # ary.fill { |index| block } -> ary
356 # ary.fill(start [, length] ) { |index| block } -> ary
357 # ary.fill(range) { |index| block } -> ary
358 #
359 # The first three forms set the selected elements of +self+ (which
360 # may be the entire array) to +obj+.
361 #
362 # A +start+ of +nil+ is equivalent to zero.
363 #
364 # A +length+ of +nil+ is equivalent to the length of the array.
365 #
366 # The last three forms fill the array with the value of the given block,
367 # which is passed the absolute index of each element to be filled.
368 #
369 # Negative values of +start+ count from the end of the array, where +-1+ is
370 # the last element.
371 #
372 # a = [ "a", "b", "c", "d" ]
373 # a.fill("x") #=> ["x", "x", "x", "x"]
374 # a.fill("w", -1) #=> ["x", "x", "x", "w"]
375 # a.fill("z", 2, 2) #=> ["x", "x", "z", "z"]
376 # a.fill("y", 0..1) #=> ["y", "y", "z", "z"]
377 # a.fill { |i| i*i } #=> [0, 1, 4, 9]
378 # a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
379 # a.fill(1, 2) { |i| i+1 } #=> [0, 2, 3, 27]
380 # a.fill(0..1) { |i| i+1 } #=> [1, 2, 3, 27]
381 #
382
383 def fill(arg0=nil, arg1=nil, arg2=nil, &block)
384 if arg0.nil? && arg1.nil? && arg2.nil? && !block
385 raise ArgumentError, "wrong number of arguments (given 0, expected 1..3)"
386 end
387
388 beg = len = 0
389 if block
390 if arg0.nil? && arg1.nil? && arg2.nil?
391 # ary.fill { |index| block } -> ary
392 beg = 0
393 len = self.size
394 elsif !arg0.nil? && arg0.kind_of?(Range)
395 # ary.fill(range) { |index| block } -> ary
396 beg = arg0.begin
397 beg += self.size if beg < 0
398 len = arg0.end
399 len += self.size if len < 0
400 len += 1 unless arg0.exclude_end?
401 elsif !arg0.nil?
402 # ary.fill(start [, length] ) { |index| block } -> ary
403 beg = arg0
404 beg += self.size if beg < 0
405 if arg1.nil?
406 len = self.size
407 else
408 len = arg0 + arg1
409 end
410 end
411 else
412 if !arg0.nil? && arg1.nil? && arg2.nil?
413 # ary.fill(obj) -> ary
414 beg = 0
415 len = self.size
416 elsif !arg0.nil? && !arg1.nil? && arg1.kind_of?(Range)
417 # ary.fill(obj, range ) -> ary
418 beg = arg1.begin
419 beg += self.size if beg < 0
420 len = arg1.end
421 len += self.size if len < 0
422 len += 1 unless arg1.exclude_end?
423 elsif !arg0.nil? && !arg1.nil?
424 # ary.fill(obj, start [, length]) -> ary
425 beg = arg1
426 beg += self.size if beg < 0
427 if arg2.nil?
428 len = self.size
429 else
430 len = beg + arg2
431 end
432 end
433 end
434
435 i = beg
436 if block
437 while i < len
438 self[i] = block.call(i)
439 i += 1
440 end
441 else
442 while i < len
443 self[i] = arg0
444 i += 1
445 end
446 end
447 self
448 end
449
450 ##
451 # call-seq:
452 # ary.delete_if { |item| block } -> ary
453 # ary.delete_if -> Enumerator
454 #
455 # Deletes every element of +self+ for which block evaluates to +true+.
456 #
457 # The array is changed instantly every time the block is called, not after
458 # the iteration is over.
459 #
460 # See also Array#reject!
461 #
462 # If no block is given, an Enumerator is returned instead.
463 #
464 # scores = [ 97, 42, 75 ]
465 # scores.delete_if {|score| score < 80 } #=> [97]
466
467 def delete_if(&block)
468 return to_enum :delete_if unless block
469
470 idx = 0
471 while idx < self.size do
472 if block.call(self[idx])
473 self.delete_at(idx)
474 else
475 idx += 1
476 end
477 end
478 self
479 end
480
481 ##
482 # call-seq:
483 # ary.reject! { |item| block } -> ary or nil
484 # ary.reject! -> Enumerator
485 #
486 # Equivalent to Array#delete_if, deleting elements from +self+ for which the
487 # block evaluates to +true+, but returns +nil+ if no changes were made.
488 #
489 # The array is changed instantly every time the block is called, not after
490 # the iteration is over.
491 #
492 # See also Enumerable#reject and Array#delete_if.
493 #
494 # If no block is given, an Enumerator is returned instead.
495
496 def reject!(&block)
497 return to_enum :reject! unless block
498
499 len = self.size
500 idx = 0
501 while idx < self.size do
502 if block.call(self[idx])
503 self.delete_at(idx)
504 else
505 idx += 1
506 end
507 end
508 if self.size == len
509 nil
510 else
511 self
512 end
513 end
514
515 ##
516 # call-seq:
517 # ary.insert(index, obj...) -> ary
518 #
519 # Inserts the given values before the element with the given +index+.
520 #
521 # Negative indices count backwards from the end of the array, where +-1+ is
522 # the last element.
523 #
524 # a = %w{ a b c d }
525 # a.insert(2, 99) #=> ["a", "b", 99, "c", "d"]
526 # a.insert(-2, 1, 2, 3) #=> ["a", "b", 99, "c", 1, 2, 3, "d"]
527
528 def insert(idx, *args)
529 idx += self.size + 1 if idx < 0
530 self[idx, 0] = args
531 self
532 end
533
534 ##
535 # call-seq:
536 # ary.bsearch {|x| block } -> elem
537 #
538 # By using binary search, finds a value from this array which meets
539 # the given condition in O(log n) where n is the size of the array.
540 #
541 # You can use this method in two use cases: a find-minimum mode and
542 # a find-any mode. In either case, the elements of the array must be
543 # monotone (or sorted) with respect to the block.
544 #
545 # In find-minimum mode (this is a good choice for typical use case),
546 # the block must return true or false, and there must be an index i
547 # (0 <= i <= ary.size) so that:
548 #
549 # - the block returns false for any element whose index is less than
550 # i, and
551 # - the block returns true for any element whose index is greater
552 # than or equal to i.
553 #
554 # This method returns the i-th element. If i is equal to ary.size,
555 # it returns nil.
556 #
557 # ary = [0, 4, 7, 10, 12]
558 # ary.bsearch {|x| x >= 4 } #=> 4
559 # ary.bsearch {|x| x >= 6 } #=> 7
560 # ary.bsearch {|x| x >= -1 } #=> 0
561 # ary.bsearch {|x| x >= 100 } #=> nil
562 #
563 # In find-any mode (this behaves like libc's bsearch(3)), the block
564 # must return a number, and there must be two indices i and j
565 # (0 <= i <= j <= ary.size) so that:
566 #
567 # - the block returns a positive number for ary[k] if 0 <= k < i,
568 # - the block returns zero for ary[k] if i <= k < j, and
569 # - the block returns a negative number for ary[k] if
570 # j <= k < ary.size.
571 #
572 # Under this condition, this method returns any element whose index
573 # is within i...j. If i is equal to j (i.e., there is no element
574 # that satisfies the block), this method returns nil.
575 #
576 # ary = [0, 4, 7, 10, 12]
577 # # try to find v such that 4 <= v < 8
578 # ary.bsearch {|x| 1 - (x / 4).truncate } #=> 4 or 7
579 # # try to find v such that 8 <= v < 10
580 # ary.bsearch {|x| 4 - (x / 2).truncate } #=> nil
581 #
582 # You must not mix the two modes at a time; the block must always
583 # return either true/false, or always return a number. It is
584 # undefined which value is actually picked up at each iteration.
585
586 def bsearch(&block)
587 return to_enum :bsearch unless block
588
589 if idx = bsearch_index(&block)
590 self[idx]
591 else
592 nil
593 end
594 end
595
596 ##
597 # call-seq:
598 # ary.bsearch_index {|x| block } -> int or nil
599 #
600 # By using binary search, finds an index of a value from this array which
601 # meets the given condition in O(log n) where n is the size of the array.
602 #
603 # It supports two modes, depending on the nature of the block and they are
604 # exactly the same as in the case of #bsearch method with the only difference
605 # being that this method returns the index of the element instead of the
606 # element itself. For more details consult the documentation for #bsearch.
607
608 def bsearch_index(&block)
609 return to_enum :bsearch_index unless block
610
611 low = 0
612 high = size
613 satisfied = false
614
615 while low < high
616 mid = ((low+high)/2).truncate
617 res = block.call self[mid]
618
619 case res
620 when 0 # find-any mode: Found!
621 return mid
622 when Numeric # find-any mode: Continue...
623 in_lower_half = res < 0
624 when true # find-min mode
625 in_lower_half = true
626 satisfied = true
627 when false, nil # find-min mode
628 in_lower_half = false
629 else
630 raise TypeError, 'invalid block result (must be numeric, true, false or nil)'
631 end
632
633 if in_lower_half
634 high = mid
635 else
636 low = mid + 1
637 end
638 end
639
640 satisfied ? low : nil
641 end
642
643 ##
644 # call-seq:
645 # ary.keep_if { |item| block } -> ary
646 # ary.keep_if -> Enumerator
647 #
648 # Deletes every element of +self+ for which the given block evaluates to
649 # +false+.
650 #
651 # See also Array#select!
652 #
653 # If no block is given, an Enumerator is returned instead.
654 #
655 # a = [1, 2, 3, 4, 5]
656 # a.keep_if { |val| val > 3 } #=> [4, 5]
657
658 def keep_if(&block)
659 return to_enum :keep_if unless block
660
661 idx = 0
662 while idx < self.size do
663 if block.call(self[idx])
664 idx += 1
665 else
666 self.delete_at(idx)
667 end
668 end
669 self
670 end
671
672 ##
673 # call-seq:
674 # ary.select! {|item| block } -> ary or nil
675 # ary.select! -> Enumerator
676 #
677 # Invokes the given block passing in successive elements from +self+,
678 # deleting elements for which the block returns a +false+ value.
679 #
680 # If changes were made, it will return +self+, otherwise it returns +nil+.
681 #
682 # See also Array#keep_if
683 #
684 # If no block is given, an Enumerator is returned instead.
685
686 def select!(&block)
687 return to_enum :select! unless block
688
689 result = []
690 idx = 0
691 len = size
692 while idx < len
693 elem = self[idx]
694 result << elem if block.call(elem)
695 idx += 1
696 end
697 return nil if len == result.size
698 self.replace(result)
699 end
700
701 ##
702 # call-seq:
703 # ary.index(val) -> int or nil
704 # ary.index {|item| block } -> int or nil
705 #
706 # Returns the _index_ of the first object in +ary+ such that the object is
707 # <code>==</code> to +obj+.
708 #
709 # If a block is given instead of an argument, returns the _index_ of the
710 # first object for which the block returns +true+. Returns +nil+ if no
711 # match is found.
712 #
713 # ISO 15.2.12.5.14
714 def index(val=NONE, &block)
715 return to_enum(:find_index, val) if !block && val == NONE
716
717 if block
718 idx = 0
719 len = size
720 while idx < len
721 return idx if block.call self[idx]
722 idx += 1
723 end
724 else
725 return self.__ary_index(val)
726 end
727 nil
728 end
729
730 ##
731 # call-seq:
732 # ary.dig(idx, ...) -> object
733 #
734 # Extracts the nested value specified by the sequence of <i>idx</i>
735 # objects by calling +dig+ at each step, returning +nil+ if any
736 # intermediate step is +nil+.
737 #
738 def dig(idx,*args)
739 n = self[idx]
740 if args.size > 0
741 n&.dig(*args)
742 else
743 n
744 end
745 end
746
747 ##
748 # call-seq:
749 # ary.permutation { |p| block } -> ary
750 # ary.permutation -> Enumerator
751 # ary.permutation(n) { |p| block } -> ary
752 # ary.permutation(n) -> Enumerator
753 #
754 # When invoked with a block, yield all permutations of length +n+ of the
755 # elements of the array, then return the array itself.
756 #
757 # If +n+ is not specified, yield all permutations of all elements.
758 #
759 # The implementation makes no guarantees about the order in which the
760 # permutations are yielded.
761 #
762 # If no block is given, an Enumerator is returned instead.
763 #
764 # Examples:
765 #
766 # a = [1, 2, 3]
767 # a.permutation.to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
768 # a.permutation(1).to_a #=> [[1],[2],[3]]
769 # a.permutation(2).to_a #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
770 # a.permutation(3).to_a #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
771 # a.permutation(0).to_a #=> [[]] # one permutation of length 0
772 # a.permutation(4).to_a #=> [] # no permutations of length 4
773 def permutation(n=self.size, &block)
774 return to_enum(:permutation, n) unless block
775 size = self.size
776 if n == 0
777 yield []
778 elsif 0 < n && n <= size
779 i = 0
780 while i<size
781 result = [self[i]]
782 if n-1 > 0
783 ary = self[0...i] + self[i+1..-1]
784 ary.permutation(n-1) do |c|
785 yield result + c
786 end
787 else
788 yield result
789 end
790 i += 1
791 end
792 end
793 self
794 end
795
796 ##
797 # call-seq:
798 # ary.combination(n) { |c| block } -> ary
799 # ary.combination(n) -> Enumerator
800 #
801 # When invoked with a block, yields all combinations of length +n+ of elements
802 # from the array and then returns the array itself.
803 #
804 # The implementation makes no guarantees about the order in which the
805 # combinations are yielded.
806 #
807 # If no block is given, an Enumerator is returned instead.
808 #
809 # Examples:
810 #
811 # a = [1, 2, 3, 4]
812 # a.combination(1).to_a #=> [[1],[2],[3],[4]]
813 # a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
814 # a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
815 # a.combination(4).to_a #=> [[1,2,3,4]]
816 # a.combination(0).to_a #=> [[]] # one combination of length 0
817 # a.combination(5).to_a #=> [] # no combinations of length 5
818
819 def combination(n, &block)
820 return to_enum(:combination, n) unless block
821 size = self.size
822 if n == 0
823 yield []
824 elsif n == 1
825 i = 0
826 while i<size
827 yield [self[i]]
828 i += 1
829 end
830 elsif n <= size
831 i = 0
832 while i<size
833 result = [self[i]]
834 self[i+1..-1].combination(n-1) do |c|
835 yield result + c
836 end
837 i += 1
838 end
839 end
840 self
841 end
842
843 ##
844 # call-seq:
845 # ary.transpose -> new_ary
846 #
847 # Assumes that self is an array of arrays and transposes the rows and columns.
848 #
849 # If the length of the subarrays don't match, an IndexError is raised.
850 #
851 # Examples:
852 #
853 # a = [[1,2], [3,4], [5,6]]
854 # a.transpose #=> [[1, 3, 5], [2, 4, 6]]
855
856 def transpose
857 return [] if empty?
858
859 column_count = nil
860 self.each do |row|
861 raise TypeError unless row.is_a?(Array)
862 column_count ||= row.size
863 raise IndexError, 'element size differs' unless column_count == row.size
864 end
865
866 Array.new(column_count) do |column_index|
867 self.map { |row| row[column_index] }
868 end
869 end
870
871 ##
872 # call-seq:
873 # ary.to_h -> Hash
874 # ary.to_h{|item| ... } -> Hash
875 #
876 # Returns the result of interpreting <i>array</i> as an array of
877 # <tt>[key, value]</tt> pairs. If a block is given, it should
878 # return <tt>[key, value]</tt> pairs to construct a hash.
879 #
880 # [[:foo, :bar], [1, 2]].to_h
881 # # => {:foo => :bar, 1 => 2}
882 # [1, 2].to_h{|x| [x, x*2]}
883 # # => {1 => 2, 2 => 4}
884 #
885 def to_h(&blk)
886 h = {}
887 self.each do |v|
888 v = blk.call(v) if blk
889 raise TypeError, "wrong element type #{v.class}" unless Array === v
890 raise ArgumentError, "wrong array length (expected 2, was #{v.length})" unless v.length == 2
891 h[v[0]] = v[1]
892 end
893 h
894 end
895
896 alias append push
897 alias prepend unshift
898 alias filter! select!
899
900 ##
901 # call-seq:
902 # ary.product(*arys) -> array
903 # ary.product(*arys) { |item| ... } -> self
904 def product(*arys, &block)
905 size = arys.size
906 i = size
907 while i > 0
908 i -= 1
909 unless arys[i].kind_of?(Array)
910 raise TypeError, "no implicit conversion into Array"
911 end
912 end
913
914 i = size
915 total = self.size
916 total *= arys[i -= 1].size while i > 0
917
918 if block
919 result = self
920 list = ->(*, e) { block.call e }
921 class << list; alias []= call; end
922 else
923 result = [nil] * total
924 list = result
925 end
926
927 i = 0
928 while i < total
929 group = [nil] * (size + 1)
930 j = size
931 n = i
932 while j > 0
933 j -= 1
934 a = arys[j]
935 b = a.size
936 group[j + 1] = a[n % b]
937 n /= b
938 end
939 group[0] = self[n]
940 list[i] = group
941 i += 1
942 end
943
944 result
945 end
946
947 ##
948 # call-seq:
949 # ary.repeated_combination(n) { |combination| ... } -> self
950 # ary.repeated_combination(n) -> enumerator
951 #
952 # A +combination+ method that contains the same elements.
953 def repeated_combination(n, &block)
954 raise TypeError, "no implicit conversion into Integer" unless 0 <=> n
955 return to_enum(:repeated_combination, n) unless block
956 __repeated_combination(n, false, &block)
957 end
958
959 ##
960 # call-seq:
961 # ary.repeated_permutation(n) { |permutation| ... } -> self
962 # ary.repeated_permutation(n) -> enumerator
963 #
964 # A +permutation+ method that contains the same elements.
965 def repeated_permutation(n, &block)
966 raise TypeError, "no implicit conversion into Integer" unless 0 <=> n
967 return to_enum(:repeated_permutation, n) unless block
968 __repeated_combination(n, true, &block)
969 end
970
971 def __repeated_combination(n, permutation, &block)
972 case n
973 when 0
974 yield []
975 when 1
976 i = 0
977 while i < self.size
978 yield [self[i]]
979 i += 1
980 end
981 else
982 if n > 0
983 v = [0] * n
984 while true
985 tmp = [nil] * n
986 i = 0
987 while i < n
988 tmp[i] = self[v[i]]
989 i += 1
990 end
991
992 yield tmp
993
994 tmp = self.size
995 i = n - 1
996 while i >= 0
997 v[i] += 1
998 break if v[i] < tmp
999 i -= 1
1000 end
1001 break unless v[0] < tmp
1002 i = 1
1003 while i < n
1004 unless v[i] < tmp
1005 if permutation
1006 v[i] = 0
1007 else
1008 v[i] = v[i - 1]
1009 end
1010 end
1011 i += 1
1012 end
1013 end
1014 end
1015 end
1016
1017 self
1018 end
1019 end