PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/TDDBC_Yokohama2_PCUnit/Ruby/lib/ruby/1.9.1/set.rb

https://bitbucket.org/aetos/tddbc_yokohama2
Ruby | 1349 lines | 819 code | 219 blank | 311 comment | 39 complexity | c0eddd61cd869b94d848b5e6a8419734 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, AGPL-3.0, 0BSD, Unlicense
  1. #!/usr/bin/env ruby
  2. #--
  3. # set.rb - defines the Set class
  4. #++
  5. # Copyright (c) 2002-2008 Akinori MUSHA <knu@iDaemons.org>
  6. #
  7. # Documentation by Akinori MUSHA and Gavin Sinclair.
  8. #
  9. # All rights reserved. You can redistribute and/or modify it under the same
  10. # terms as Ruby.
  11. #
  12. # $Id: set.rb 28095 2010-05-30 13:15:17Z marcandre $
  13. #
  14. # == Overview
  15. #
  16. # This library provides the Set class, which deals with a collection
  17. # of unordered values with no duplicates. It is a hybrid of Array's
  18. # intuitive inter-operation facilities and Hash's fast lookup. If you
  19. # need to keep values ordered, use the SortedSet class.
  20. #
  21. # The method +to_set+ is added to Enumerable for convenience.
  22. #
  23. # See the Set and SortedSet documentation for examples of usage.
  24. #
  25. # Set implements a collection of unordered values with no duplicates.
  26. # This is a hybrid of Array's intuitive inter-operation facilities and
  27. # Hash's fast lookup.
  28. #
  29. # The equality of each couple of elements is determined according to
  30. # Object#eql? and Object#hash, since Set uses Hash as storage.
  31. #
  32. # Set is easy to use with Enumerable objects (implementing +each+).
  33. # Most of the initializer methods and binary operators accept generic
  34. # Enumerable objects besides sets and arrays. An Enumerable object
  35. # can be converted to Set using the +to_set+ method.
  36. #
  37. # == Example
  38. #
  39. # require 'set'
  40. # s1 = Set.new [1, 2] # -> #<Set: {1, 2}>
  41. # s2 = [1, 2].to_set # -> #<Set: {1, 2}>
  42. # s1 == s2 # -> true
  43. # s1.add("foo") # -> #<Set: {1, 2, "foo"}>
  44. # s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}>
  45. # s1.subset? s2 # -> false
  46. # s2.subset? s1 # -> true
  47. #
  48. # == Contact
  49. #
  50. # - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
  51. #
  52. class Set
  53. include Enumerable
  54. # Creates a new set containing the given objects.
  55. def self.[](*ary)
  56. new(ary)
  57. end
  58. # Creates a new set containing the elements of the given enumerable
  59. # object.
  60. #
  61. # If a block is given, the elements of enum are preprocessed by the
  62. # given block.
  63. def initialize(enum = nil, &block) # :yields: o
  64. @hash ||= Hash.new
  65. enum.nil? and return
  66. if block
  67. do_with_enum(enum) { |o| add(block[o]) }
  68. else
  69. merge(enum)
  70. end
  71. end
  72. def do_with_enum(enum, &block)
  73. if enum.respond_to?(:each_entry)
  74. enum.each_entry(&block)
  75. elsif enum.respond_to?(:each)
  76. enum.each(&block)
  77. else
  78. raise ArgumentError, "value must be enumerable"
  79. end
  80. end
  81. private :do_with_enum
  82. # Copy internal hash.
  83. def initialize_copy(orig)
  84. @hash = orig.instance_eval{@hash}.dup
  85. end
  86. def freeze # :nodoc:
  87. super
  88. @hash.freeze
  89. self
  90. end
  91. def taint # :nodoc:
  92. super
  93. @hash.taint
  94. self
  95. end
  96. def untaint # :nodoc:
  97. super
  98. @hash.untaint
  99. self
  100. end
  101. # Returns the number of elements.
  102. def size
  103. @hash.size
  104. end
  105. alias length size
  106. # Returns true if the set contains no elements.
  107. def empty?
  108. @hash.empty?
  109. end
  110. # Removes all elements and returns self.
  111. def clear
  112. @hash.clear
  113. self
  114. end
  115. # Replaces the contents of the set with the contents of the given
  116. # enumerable object and returns self.
  117. def replace(enum)
  118. if enum.class == self.class
  119. @hash.replace(enum.instance_eval { @hash })
  120. else
  121. clear
  122. merge(enum)
  123. end
  124. self
  125. end
  126. # Converts the set to an array. The order of elements is uncertain.
  127. def to_a
  128. @hash.keys
  129. end
  130. def flatten_merge(set, seen = Set.new)
  131. set.each { |e|
  132. if e.is_a?(Set)
  133. if seen.include?(e_id = e.object_id)
  134. raise ArgumentError, "tried to flatten recursive Set"
  135. end
  136. seen.add(e_id)
  137. flatten_merge(e, seen)
  138. seen.delete(e_id)
  139. else
  140. add(e)
  141. end
  142. }
  143. self
  144. end
  145. protected :flatten_merge
  146. # Returns a new set that is a copy of the set, flattening each
  147. # containing set recursively.
  148. def flatten
  149. self.class.new.flatten_merge(self)
  150. end
  151. # Equivalent to Set#flatten, but replaces the receiver with the
  152. # result in place. Returns nil if no modifications were made.
  153. def flatten!
  154. if detect { |e| e.is_a?(Set) }
  155. replace(flatten())
  156. else
  157. nil
  158. end
  159. end
  160. # Returns true if the set contains the given object.
  161. def include?(o)
  162. @hash.include?(o)
  163. end
  164. alias member? include?
  165. # Returns true if the set is a superset of the given set.
  166. def superset?(set)
  167. set.is_a?(Set) or raise ArgumentError, "value must be a set"
  168. return false if size < set.size
  169. set.all? { |o| include?(o) }
  170. end
  171. # Returns true if the set is a proper superset of the given set.
  172. def proper_superset?(set)
  173. set.is_a?(Set) or raise ArgumentError, "value must be a set"
  174. return false if size <= set.size
  175. set.all? { |o| include?(o) }
  176. end
  177. # Returns true if the set is a subset of the given set.
  178. def subset?(set)
  179. set.is_a?(Set) or raise ArgumentError, "value must be a set"
  180. return false if set.size < size
  181. all? { |o| set.include?(o) }
  182. end
  183. # Returns true if the set is a proper subset of the given set.
  184. def proper_subset?(set)
  185. set.is_a?(Set) or raise ArgumentError, "value must be a set"
  186. return false if set.size <= size
  187. all? { |o| set.include?(o) }
  188. end
  189. # Calls the given block once for each element in the set, passing
  190. # the element as parameter. Returns an enumerator if no block is
  191. # given.
  192. def each
  193. block_given? or return enum_for(__method__)
  194. @hash.each_key { |o| yield(o) }
  195. self
  196. end
  197. # Adds the given object to the set and returns self. Use +merge+ to
  198. # add many elements at once.
  199. def add(o)
  200. @hash[o] = true
  201. self
  202. end
  203. alias << add
  204. # Adds the given object to the set and returns self. If the
  205. # object is already in the set, returns nil.
  206. def add?(o)
  207. if include?(o)
  208. nil
  209. else
  210. add(o)
  211. end
  212. end
  213. # Deletes the given object from the set and returns self. Use +subtract+ to
  214. # delete many items at once.
  215. def delete(o)
  216. @hash.delete(o)
  217. self
  218. end
  219. # Deletes the given object from the set and returns self. If the
  220. # object is not in the set, returns nil.
  221. def delete?(o)
  222. if include?(o)
  223. delete(o)
  224. else
  225. nil
  226. end
  227. end
  228. # Deletes every element of the set for which block evaluates to
  229. # true, and returns self.
  230. def delete_if
  231. block_given? or return enum_for(__method__)
  232. to_a.each { |o| @hash.delete(o) if yield(o) }
  233. self
  234. end
  235. # Deletes every element of the set for which block evaluates to
  236. # false, and returns self.
  237. def keep_if
  238. block_given? or return enum_for(__method__)
  239. to_a.each { |o| @hash.delete(o) unless yield(o) }
  240. self
  241. end
  242. # Replaces the elements with ones returned by collect().
  243. def collect!
  244. block_given? or return enum_for(__method__)
  245. set = self.class.new
  246. each { |o| set << yield(o) }
  247. replace(set)
  248. end
  249. alias map! collect!
  250. # Equivalent to Set#delete_if, but returns nil if no changes were
  251. # made.
  252. def reject!
  253. block_given? or return enum_for(__method__)
  254. n = size
  255. delete_if { |o| yield(o) }
  256. size == n ? nil : self
  257. end
  258. # Equivalent to Set#keep_if, but returns nil if no changes were
  259. # made.
  260. def select!
  261. block_given? or return enum_for(__method__)
  262. n = size
  263. keep_if { |o| yield(o) }
  264. size == n ? nil : self
  265. end
  266. # Merges the elements of the given enumerable object to the set and
  267. # returns self.
  268. def merge(enum)
  269. if enum.instance_of?(self.class)
  270. @hash.update(enum.instance_variable_get(:@hash))
  271. else
  272. do_with_enum(enum) { |o| add(o) }
  273. end
  274. self
  275. end
  276. # Deletes every element that appears in the given enumerable object
  277. # and returns self.
  278. def subtract(enum)
  279. do_with_enum(enum) { |o| delete(o) }
  280. self
  281. end
  282. # Returns a new set built by merging the set and the elements of the
  283. # given enumerable object.
  284. def |(enum)
  285. dup.merge(enum)
  286. end
  287. alias + | ##
  288. alias union | ##
  289. # Returns a new set built by duplicating the set, removing every
  290. # element that appears in the given enumerable object.
  291. def -(enum)
  292. dup.subtract(enum)
  293. end
  294. alias difference - ##
  295. # Returns a new set containing elements common to the set and the
  296. # given enumerable object.
  297. def &(enum)
  298. n = self.class.new
  299. do_with_enum(enum) { |o| n.add(o) if include?(o) }
  300. n
  301. end
  302. alias intersection & ##
  303. # Returns a new set containing elements exclusive between the set
  304. # and the given enumerable object. (set ^ enum) is equivalent to
  305. # ((set | enum) - (set & enum)).
  306. def ^(enum)
  307. n = Set.new(enum)
  308. each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
  309. n
  310. end
  311. # Returns true if two sets are equal. The equality of each couple
  312. # of elements is defined according to Object#eql?.
  313. def ==(other)
  314. if self.equal?(other)
  315. true
  316. elsif other.instance_of?(self.class)
  317. @hash == other.instance_variable_get(:@hash)
  318. elsif other.is_a?(Set) && self.size == other.size
  319. other.all? { |o| @hash.include?(o) }
  320. else
  321. false
  322. end
  323. end
  324. def hash # :nodoc:
  325. @hash.hash
  326. end
  327. def eql?(o) # :nodoc:
  328. return false unless o.is_a?(Set)
  329. @hash.eql?(o.instance_eval{@hash})
  330. end
  331. # Classifies the set by the return value of the given block and
  332. # returns a hash of {value => set of elements} pairs. The block is
  333. # called once for each element of the set, passing the element as
  334. # parameter.
  335. #
  336. # e.g.:
  337. #
  338. # require 'set'
  339. # files = Set.new(Dir.glob("*.rb"))
  340. # hash = files.classify { |f| File.mtime(f).year }
  341. # p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
  342. # # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
  343. # # 2002=>#<Set: {"f.rb"}>}
  344. def classify # :yields: o
  345. block_given? or return enum_for(__method__)
  346. h = {}
  347. each { |i|
  348. x = yield(i)
  349. (h[x] ||= self.class.new).add(i)
  350. }
  351. h
  352. end
  353. # Divides the set into a set of subsets according to the commonality
  354. # defined by the given block.
  355. #
  356. # If the arity of the block is 2, elements o1 and o2 are in common
  357. # if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
  358. # in common if block.call(o1) == block.call(o2).
  359. #
  360. # e.g.:
  361. #
  362. # require 'set'
  363. # numbers = Set[1, 3, 4, 6, 9, 10, 11]
  364. # set = numbers.divide { |i,j| (i - j).abs == 1 }
  365. # p set # => #<Set: {#<Set: {1}>,
  366. # # #<Set: {11, 9, 10}>,
  367. # # #<Set: {3, 4}>,
  368. # # #<Set: {6}>}>
  369. def divide(&func)
  370. func or return enum_for(__method__)
  371. if func.arity == 2
  372. require 'tsort'
  373. class << dig = {} # :nodoc:
  374. include TSort
  375. alias tsort_each_node each_key
  376. def tsort_each_child(node, &block)
  377. fetch(node).each(&block)
  378. end
  379. end
  380. each { |u|
  381. dig[u] = a = []
  382. each{ |v| func.call(u, v) and a << v }
  383. }
  384. set = Set.new()
  385. dig.each_strongly_connected_component { |css|
  386. set.add(self.class.new(css))
  387. }
  388. set
  389. else
  390. Set.new(classify(&func).values)
  391. end
  392. end
  393. InspectKey = :__inspect_key__ # :nodoc:
  394. # Returns a string containing a human-readable representation of the
  395. # set. ("#<Set: {element1, element2, ...}>")
  396. def inspect
  397. ids = (Thread.current[InspectKey] ||= [])
  398. if ids.include?(object_id)
  399. return sprintf('#<%s: {...}>', self.class.name)
  400. end
  401. begin
  402. ids << object_id
  403. return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
  404. ensure
  405. ids.pop
  406. end
  407. end
  408. def pretty_print(pp) # :nodoc:
  409. pp.text sprintf('#<%s: {', self.class.name)
  410. pp.nest(1) {
  411. pp.seplist(self) { |o|
  412. pp.pp o
  413. }
  414. }
  415. pp.text "}>"
  416. end
  417. def pretty_print_cycle(pp) # :nodoc:
  418. pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
  419. end
  420. end
  421. #
  422. # SortedSet implements a Set that guarantees that it's element are
  423. # yielded in sorted order (according to the return values of their
  424. # #<=> methods) when iterating over them.
  425. #
  426. # All elements that are added to a SortedSet must respond to the <=>
  427. # method for comparison.
  428. #
  429. # Also, all elements must be <em>mutually comparable</em>: <tt>el1 <=>
  430. # el2</tt> must not return <tt>nil</tt> for any elements <tt>el1</tt>
  431. # and <tt>el2</tt>, else an ArgumentError will be raised when
  432. # iterating over the SortedSet.
  433. #
  434. # == Example
  435. #
  436. # require "set"
  437. #
  438. # set = SortedSet.new([2, 1, 5, 6, 4, 5, 3, 3, 3])
  439. # ary = []
  440. #
  441. # set.each do |obj|
  442. # ary << obj
  443. # end
  444. #
  445. # p ary # => [1, 2, 3, 4, 5, 6]
  446. #
  447. # set2 = SortedSet.new([1, 2, "3"])
  448. # set2.each { |obj| } # => raises ArgumentError: comparison of Fixnum with String failed
  449. #
  450. class SortedSet < Set
  451. @@setup = false
  452. class << self
  453. def [](*ary) # :nodoc:
  454. new(ary)
  455. end
  456. def setup # :nodoc:
  457. @@setup and return
  458. module_eval {
  459. # a hack to shut up warning
  460. alias old_init initialize
  461. remove_method :old_init
  462. }
  463. begin
  464. require 'rbtree'
  465. module_eval %{
  466. def initialize(*args, &block)
  467. @hash = RBTree.new
  468. super
  469. end
  470. def add(o)
  471. o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
  472. super
  473. end
  474. alias << add
  475. }
  476. rescue LoadError
  477. module_eval %{
  478. def initialize(*args, &block)
  479. @keys = nil
  480. super
  481. end
  482. def clear
  483. @keys = nil
  484. super
  485. end
  486. def replace(enum)
  487. @keys = nil
  488. super
  489. end
  490. def add(o)
  491. o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
  492. @keys = nil
  493. super
  494. end
  495. alias << add
  496. def delete(o)
  497. @keys = nil
  498. @hash.delete(o)
  499. self
  500. end
  501. def delete_if
  502. block_given? or return enum_for(__method__)
  503. n = @hash.size
  504. super
  505. @keys = nil if @hash.size != n
  506. self
  507. end
  508. def keep_if
  509. block_given? or return enum_for(__method__)
  510. n = @hash.size
  511. super
  512. @keys = nil if @hash.size != n
  513. self
  514. end
  515. def merge(enum)
  516. @keys = nil
  517. super
  518. end
  519. def each
  520. block_given? or return enum_for(__method__)
  521. to_a.each { |o| yield(o) }
  522. self
  523. end
  524. def to_a
  525. (@keys = @hash.keys).sort! unless @keys
  526. @keys
  527. end
  528. }
  529. end
  530. @@setup = true
  531. end
  532. end
  533. def initialize(*args, &block) # :nodoc:
  534. SortedSet.setup
  535. initialize(*args, &block)
  536. end
  537. end
  538. module Enumerable
  539. # Makes a set from the enumerable object with given arguments.
  540. # Needs to +require "set"+ to use this method.
  541. def to_set(klass = Set, *args, &block)
  542. klass.new(self, *args, &block)
  543. end
  544. end
  545. # =begin
  546. # == RestricedSet class
  547. # RestricedSet implements a set with restrictions defined by a given
  548. # block.
  549. #
  550. # === Super class
  551. # Set
  552. #
  553. # === Class Methods
  554. # --- RestricedSet::new(enum = nil) { |o| ... }
  555. # --- RestricedSet::new(enum = nil) { |rset, o| ... }
  556. # Creates a new restricted set containing the elements of the given
  557. # enumerable object. Restrictions are defined by the given block.
  558. #
  559. # If the block's arity is 2, it is called with the RestrictedSet
  560. # itself and an object to see if the object is allowed to be put in
  561. # the set.
  562. #
  563. # Otherwise, the block is called with an object to see if the object
  564. # is allowed to be put in the set.
  565. #
  566. # === Instance Methods
  567. # --- restriction_proc
  568. # Returns the restriction procedure of the set.
  569. #
  570. # =end
  571. #
  572. # class RestricedSet < Set
  573. # def initialize(*args, &block)
  574. # @proc = block or raise ArgumentError, "missing a block"
  575. #
  576. # if @proc.arity == 2
  577. # instance_eval %{
  578. # def add(o)
  579. # @hash[o] = true if @proc.call(self, o)
  580. # self
  581. # end
  582. # alias << add
  583. #
  584. # def add?(o)
  585. # if include?(o) || !@proc.call(self, o)
  586. # nil
  587. # else
  588. # @hash[o] = true
  589. # self
  590. # end
  591. # end
  592. #
  593. # def replace(enum)
  594. # enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
  595. # clear
  596. # enum.each_entry { |o| add(o) }
  597. #
  598. # self
  599. # end
  600. #
  601. # def merge(enum)
  602. # enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
  603. # enum.each_entry { |o| add(o) }
  604. #
  605. # self
  606. # end
  607. # }
  608. # else
  609. # instance_eval %{
  610. # def add(o)
  611. # if @proc.call(o)
  612. # @hash[o] = true
  613. # end
  614. # self
  615. # end
  616. # alias << add
  617. #
  618. # def add?(o)
  619. # if include?(o) || !@proc.call(o)
  620. # nil
  621. # else
  622. # @hash[o] = true
  623. # self
  624. # end
  625. # end
  626. # }
  627. # end
  628. #
  629. # super(*args)
  630. # end
  631. #
  632. # def restriction_proc
  633. # @proc
  634. # end
  635. # end
  636. if $0 == __FILE__
  637. eval DATA.read, nil, $0, __LINE__+4
  638. end
  639. __END__
  640. require 'test/unit'
  641. class TC_Set < Test::Unit::TestCase
  642. def test_aref
  643. assert_nothing_raised {
  644. Set[]
  645. Set[nil]
  646. Set[1,2,3]
  647. }
  648. assert_equal(0, Set[].size)
  649. assert_equal(1, Set[nil].size)
  650. assert_equal(1, Set[[]].size)
  651. assert_equal(1, Set[[nil]].size)
  652. set = Set[2,4,6,4]
  653. assert_equal(Set.new([2,4,6]), set)
  654. end
  655. def test_s_new
  656. assert_nothing_raised {
  657. Set.new()
  658. Set.new(nil)
  659. Set.new([])
  660. Set.new([1,2])
  661. Set.new('a'..'c')
  662. }
  663. assert_raises(ArgumentError) {
  664. Set.new(false)
  665. }
  666. assert_raises(ArgumentError) {
  667. Set.new(1)
  668. }
  669. assert_raises(ArgumentError) {
  670. Set.new(1,2)
  671. }
  672. assert_equal(0, Set.new().size)
  673. assert_equal(0, Set.new(nil).size)
  674. assert_equal(0, Set.new([]).size)
  675. assert_equal(1, Set.new([nil]).size)
  676. ary = [2,4,6,4]
  677. set = Set.new(ary)
  678. ary.clear
  679. assert_equal(false, set.empty?)
  680. assert_equal(3, set.size)
  681. ary = [1,2,3]
  682. s = Set.new(ary) { |o| o * 2 }
  683. assert_equal([2,4,6], s.sort)
  684. end
  685. def test_clone
  686. set1 = Set.new
  687. set2 = set1.clone
  688. set1 << 'abc'
  689. assert_equal(Set.new, set2)
  690. end
  691. def test_dup
  692. set1 = Set[1,2]
  693. set2 = set1.dup
  694. assert_not_same(set1, set2)
  695. assert_equal(set1, set2)
  696. set1.add(3)
  697. assert_not_equal(set1, set2)
  698. end
  699. def test_size
  700. assert_equal(0, Set[].size)
  701. assert_equal(2, Set[1,2].size)
  702. assert_equal(2, Set[1,2,1].size)
  703. end
  704. def test_empty?
  705. assert_equal(true, Set[].empty?)
  706. assert_equal(false, Set[1, 2].empty?)
  707. end
  708. def test_clear
  709. set = Set[1,2]
  710. ret = set.clear
  711. assert_same(set, ret)
  712. assert_equal(true, set.empty?)
  713. end
  714. def test_replace
  715. set = Set[1,2]
  716. ret = set.replace('a'..'c')
  717. assert_same(set, ret)
  718. assert_equal(Set['a','b','c'], set)
  719. end
  720. def test_to_a
  721. set = Set[1,2,3,2]
  722. ary = set.to_a
  723. assert_equal([1,2,3], ary.sort)
  724. end
  725. def test_flatten
  726. # test1
  727. set1 = Set[
  728. 1,
  729. Set[
  730. 5,
  731. Set[7,
  732. Set[0]
  733. ],
  734. Set[6,2],
  735. 1
  736. ],
  737. 3,
  738. Set[3,4]
  739. ]
  740. set2 = set1.flatten
  741. set3 = Set.new(0..7)
  742. assert_not_same(set2, set1)
  743. assert_equal(set3, set2)
  744. # test2; destructive
  745. orig_set1 = set1
  746. set1.flatten!
  747. assert_same(orig_set1, set1)
  748. assert_equal(set3, set1)
  749. # test3; multiple occurrences of a set in an set
  750. set1 = Set[1, 2]
  751. set2 = Set[set1, Set[set1, 4], 3]
  752. assert_nothing_raised {
  753. set2.flatten!
  754. }
  755. assert_equal(Set.new(1..4), set2)
  756. # test4; recursion
  757. set2 = Set[]
  758. set1 = Set[1, set2]
  759. set2.add(set1)
  760. assert_raises(ArgumentError) {
  761. set1.flatten!
  762. }
  763. # test5; miscellaneous
  764. empty = Set[]
  765. set = Set[Set[empty, "a"],Set[empty, "b"]]
  766. assert_nothing_raised {
  767. set.flatten
  768. }
  769. set1 = empty.merge(Set["no_more", set])
  770. assert_nil(Set.new(0..31).flatten!)
  771. x = Set[Set[],Set[1,2]].flatten!
  772. y = Set[1,2]
  773. assert_equal(x, y)
  774. end
  775. def test_include?
  776. set = Set[1,2,3]
  777. assert_equal(true, set.include?(1))
  778. assert_equal(true, set.include?(2))
  779. assert_equal(true, set.include?(3))
  780. assert_equal(false, set.include?(0))
  781. assert_equal(false, set.include?(nil))
  782. set = Set["1",nil,"2",nil,"0","1",false]
  783. assert_equal(true, set.include?(nil))
  784. assert_equal(true, set.include?(false))
  785. assert_equal(true, set.include?("1"))
  786. assert_equal(false, set.include?(0))
  787. assert_equal(false, set.include?(true))
  788. end
  789. def test_superset?
  790. set = Set[1,2,3]
  791. assert_raises(ArgumentError) {
  792. set.superset?()
  793. }
  794. assert_raises(ArgumentError) {
  795. set.superset?(2)
  796. }
  797. assert_raises(ArgumentError) {
  798. set.superset?([2])
  799. }
  800. assert_equal(true, set.superset?(Set[]))
  801. assert_equal(true, set.superset?(Set[1,2]))
  802. assert_equal(true, set.superset?(Set[1,2,3]))
  803. assert_equal(false, set.superset?(Set[1,2,3,4]))
  804. assert_equal(false, set.superset?(Set[1,4]))
  805. assert_equal(true, Set[].superset?(Set[]))
  806. end
  807. def test_proper_superset?
  808. set = Set[1,2,3]
  809. assert_raises(ArgumentError) {
  810. set.proper_superset?()
  811. }
  812. assert_raises(ArgumentError) {
  813. set.proper_superset?(2)
  814. }
  815. assert_raises(ArgumentError) {
  816. set.proper_superset?([2])
  817. }
  818. assert_equal(true, set.proper_superset?(Set[]))
  819. assert_equal(true, set.proper_superset?(Set[1,2]))
  820. assert_equal(false, set.proper_superset?(Set[1,2,3]))
  821. assert_equal(false, set.proper_superset?(Set[1,2,3,4]))
  822. assert_equal(false, set.proper_superset?(Set[1,4]))
  823. assert_equal(false, Set[].proper_superset?(Set[]))
  824. end
  825. def test_subset?
  826. set = Set[1,2,3]
  827. assert_raises(ArgumentError) {
  828. set.subset?()
  829. }
  830. assert_raises(ArgumentError) {
  831. set.subset?(2)
  832. }
  833. assert_raises(ArgumentError) {
  834. set.subset?([2])
  835. }
  836. assert_equal(true, set.subset?(Set[1,2,3,4]))
  837. assert_equal(true, set.subset?(Set[1,2,3]))
  838. assert_equal(false, set.subset?(Set[1,2]))
  839. assert_equal(false, set.subset?(Set[]))
  840. assert_equal(true, Set[].subset?(Set[1]))
  841. assert_equal(true, Set[].subset?(Set[]))
  842. end
  843. def test_proper_subset?
  844. set = Set[1,2,3]
  845. assert_raises(ArgumentError) {
  846. set.proper_subset?()
  847. }
  848. assert_raises(ArgumentError) {
  849. set.proper_subset?(2)
  850. }
  851. assert_raises(ArgumentError) {
  852. set.proper_subset?([2])
  853. }
  854. assert_equal(true, set.proper_subset?(Set[1,2,3,4]))
  855. assert_equal(false, set.proper_subset?(Set[1,2,3]))
  856. assert_equal(false, set.proper_subset?(Set[1,2]))
  857. assert_equal(false, set.proper_subset?(Set[]))
  858. assert_equal(false, Set[].proper_subset?(Set[]))
  859. end
  860. def test_each
  861. ary = [1,3,5,7,10,20]
  862. set = Set.new(ary)
  863. ret = set.each { |o| }
  864. assert_same(set, ret)
  865. e = set.each
  866. assert_instance_of(Enumerator, e)
  867. assert_nothing_raised {
  868. set.each { |o|
  869. ary.delete(o) or raise "unexpected element: #{o}"
  870. }
  871. ary.empty? or raise "forgotten elements: #{ary.join(', ')}"
  872. }
  873. end
  874. def test_add
  875. set = Set[1,2,3]
  876. ret = set.add(2)
  877. assert_same(set, ret)
  878. assert_equal(Set[1,2,3], set)
  879. ret = set.add?(2)
  880. assert_nil(ret)
  881. assert_equal(Set[1,2,3], set)
  882. ret = set.add(4)
  883. assert_same(set, ret)
  884. assert_equal(Set[1,2,3,4], set)
  885. ret = set.add?(5)
  886. assert_same(set, ret)
  887. assert_equal(Set[1,2,3,4,5], set)
  888. end
  889. def test_delete
  890. set = Set[1,2,3]
  891. ret = set.delete(4)
  892. assert_same(set, ret)
  893. assert_equal(Set[1,2,3], set)
  894. ret = set.delete?(4)
  895. assert_nil(ret)
  896. assert_equal(Set[1,2,3], set)
  897. ret = set.delete(2)
  898. assert_equal(set, ret)
  899. assert_equal(Set[1,3], set)
  900. ret = set.delete?(1)
  901. assert_equal(set, ret)
  902. assert_equal(Set[3], set)
  903. end
  904. def test_delete_if
  905. set = Set.new(1..10)
  906. ret = set.delete_if { |i| i > 10 }
  907. assert_same(set, ret)
  908. assert_equal(Set.new(1..10), set)
  909. set = Set.new(1..10)
  910. ret = set.delete_if { |i| i % 3 == 0 }
  911. assert_same(set, ret)
  912. assert_equal(Set[1,2,4,5,7,8,10], set)
  913. end
  914. def test_collect!
  915. set = Set[1,2,3,'a','b','c',-1..1,2..4]
  916. ret = set.collect! { |i|
  917. case i
  918. when Numeric
  919. i * 2
  920. when String
  921. i.upcase
  922. else
  923. nil
  924. end
  925. }
  926. assert_same(set, ret)
  927. assert_equal(Set[2,4,6,'A','B','C',nil], set)
  928. end
  929. def test_reject!
  930. set = Set.new(1..10)
  931. ret = set.reject! { |i| i > 10 }
  932. assert_nil(ret)
  933. assert_equal(Set.new(1..10), set)
  934. ret = set.reject! { |i| i % 3 == 0 }
  935. assert_same(set, ret)
  936. assert_equal(Set[1,2,4,5,7,8,10], set)
  937. end
  938. def test_merge
  939. set = Set[1,2,3]
  940. ret = set.merge([2,4,6])
  941. assert_same(set, ret)
  942. assert_equal(Set[1,2,3,4,6], set)
  943. end
  944. def test_subtract
  945. set = Set[1,2,3]
  946. ret = set.subtract([2,4,6])
  947. assert_same(set, ret)
  948. assert_equal(Set[1,3], set)
  949. end
  950. def test_plus
  951. set = Set[1,2,3]
  952. ret = set + [2,4,6]
  953. assert_not_same(set, ret)
  954. assert_equal(Set[1,2,3,4,6], ret)
  955. end
  956. def test_minus
  957. set = Set[1,2,3]
  958. ret = set - [2,4,6]
  959. assert_not_same(set, ret)
  960. assert_equal(Set[1,3], ret)
  961. end
  962. def test_and
  963. set = Set[1,2,3,4]
  964. ret = set & [2,4,6]
  965. assert_not_same(set, ret)
  966. assert_equal(Set[2,4], ret)
  967. end
  968. def test_xor
  969. set = Set[1,2,3,4]
  970. ret = set ^ [2,4,5,5]
  971. assert_not_same(set, ret)
  972. assert_equal(Set[1,3,5], ret)
  973. end
  974. def test_eq
  975. set1 = Set[2,3,1]
  976. set2 = Set[1,2,3]
  977. assert_equal(set1, set1)
  978. assert_equal(set1, set2)
  979. assert_not_equal(Set[1], [1])
  980. set1 = Class.new(Set)["a", "b"]
  981. set2 = Set["a", "b", set1]
  982. set1 = set1.add(set1.clone)
  983. # assert_equal(set1, set2)
  984. # assert_equal(set2, set1)
  985. assert_equal(set2, set2.clone)
  986. assert_equal(set1.clone, set1)
  987. assert_not_equal(Set[Exception.new,nil], Set[Exception.new,Exception.new], "[ruby-dev:26127]")
  988. end
  989. # def test_hash
  990. # end
  991. # def test_eql?
  992. # end
  993. def test_classify
  994. set = Set.new(1..10)
  995. ret = set.classify { |i| i % 3 }
  996. assert_equal(3, ret.size)
  997. assert_instance_of(Hash, ret)
  998. ret.each_value { |value| assert_instance_of(Set, value) }
  999. assert_equal(Set[3,6,9], ret[0])
  1000. assert_equal(Set[1,4,7,10], ret[1])
  1001. assert_equal(Set[2,5,8], ret[2])
  1002. end
  1003. def test_divide
  1004. set = Set.new(1..10)
  1005. ret = set.divide { |i| i % 3 }
  1006. assert_equal(3, ret.size)
  1007. n = 0
  1008. ret.each { |s| n += s.size }
  1009. assert_equal(set.size, n)
  1010. assert_equal(set, ret.flatten)
  1011. set = Set[7,10,5,11,1,3,4,9,0]
  1012. ret = set.divide { |a,b| (a - b).abs == 1 }
  1013. assert_equal(4, ret.size)
  1014. n = 0
  1015. ret.each { |s| n += s.size }
  1016. assert_equal(set.size, n)
  1017. assert_equal(set, ret.flatten)
  1018. ret.each { |s|
  1019. if s.include?(0)
  1020. assert_equal(Set[0,1], s)
  1021. elsif s.include?(3)
  1022. assert_equal(Set[3,4,5], s)
  1023. elsif s.include?(7)
  1024. assert_equal(Set[7], s)
  1025. elsif s.include?(9)
  1026. assert_equal(Set[9,10,11], s)
  1027. else
  1028. raise "unexpected group: #{s.inspect}"
  1029. end
  1030. }
  1031. end
  1032. def test_inspect
  1033. set1 = Set[1]
  1034. assert_equal('#<Set: {1}>', set1.inspect)
  1035. set2 = Set[Set[0], 1, 2, set1]
  1036. assert_equal(false, set2.inspect.include?('#<Set: {...}>'))
  1037. set1.add(set2)
  1038. assert_equal(true, set1.inspect.include?('#<Set: {...}>'))
  1039. end
  1040. # def test_pretty_print
  1041. # end
  1042. # def test_pretty_print_cycle
  1043. # end
  1044. end
  1045. class TC_SortedSet < Test::Unit::TestCase
  1046. def test_sortedset
  1047. s = SortedSet[4,5,3,1,2]
  1048. assert_equal([1,2,3,4,5], s.to_a)
  1049. prev = nil
  1050. s.each { |o| assert(prev < o) if prev; prev = o }
  1051. assert_not_nil(prev)
  1052. s.map! { |o| -2 * o }
  1053. assert_equal([-10,-8,-6,-4,-2], s.to_a)
  1054. prev = nil
  1055. ret = s.each { |o| assert(prev < o) if prev; prev = o }
  1056. assert_not_nil(prev)
  1057. assert_same(s, ret)
  1058. s = SortedSet.new([2,1,3]) { |o| o * -2 }
  1059. assert_equal([-6,-4,-2], s.to_a)
  1060. s = SortedSet.new(['one', 'two', 'three', 'four'])
  1061. a = []
  1062. ret = s.delete_if { |o| a << o; o.start_with?('t') }
  1063. assert_same(s, ret)
  1064. assert_equal(['four', 'one'], s.to_a)
  1065. assert_equal(['four', 'one', 'three', 'two'], a)
  1066. s = SortedSet.new(['one', 'two', 'three', 'four'])
  1067. a = []
  1068. ret = s.reject! { |o| a << o; o.start_with?('t') }
  1069. assert_same(s, ret)
  1070. assert_equal(['four', 'one'], s.to_a)
  1071. assert_equal(['four', 'one', 'three', 'two'], a)
  1072. s = SortedSet.new(['one', 'two', 'three', 'four'])
  1073. a = []
  1074. ret = s.reject! { |o| a << o; false }
  1075. assert_same(nil, ret)
  1076. assert_equal(['four', 'one', 'three', 'two'], s.to_a)
  1077. assert_equal(['four', 'one', 'three', 'two'], a)
  1078. end
  1079. end
  1080. class TC_Enumerable < Test::Unit::TestCase
  1081. def test_to_set
  1082. ary = [2,5,4,3,2,1,3]
  1083. set = ary.to_set
  1084. assert_instance_of(Set, set)
  1085. assert_equal([1,2,3,4,5], set.sort)
  1086. set = ary.to_set { |o| o * -2 }
  1087. assert_instance_of(Set, set)
  1088. assert_equal([-10,-8,-6,-4,-2], set.sort)
  1089. set = ary.to_set(SortedSet)
  1090. assert_instance_of(SortedSet, set)
  1091. assert_equal([1,2,3,4,5], set.to_a)
  1092. set = ary.to_set(SortedSet) { |o| o * -2 }
  1093. assert_instance_of(SortedSet, set)
  1094. assert_equal([-10,-8,-6,-4,-2], set.sort)
  1095. end
  1096. end
  1097. # class TC_RestricedSet < Test::Unit::TestCase
  1098. # def test_s_new
  1099. # assert_raises(ArgumentError) { RestricedSet.new }
  1100. #
  1101. # s = RestricedSet.new([-1,2,3]) { |o| o > 0 }
  1102. # assert_equal([2,3], s.sort)
  1103. # end
  1104. #
  1105. # def test_restriction_proc
  1106. # s = RestricedSet.new([-1,2,3]) { |o| o > 0 }
  1107. #
  1108. # f = s.restriction_proc
  1109. # assert_instance_of(Proc, f)
  1110. # assert(f[1])
  1111. # assert(!f[0])
  1112. # end
  1113. #
  1114. # def test_replace
  1115. # s = RestricedSet.new(-3..3) { |o| o > 0 }
  1116. # assert_equal([1,2,3], s.sort)
  1117. #
  1118. # s.replace([-2,0,3,4,5])
  1119. # assert_equal([3,4,5], s.sort)
  1120. # end
  1121. #
  1122. # def test_merge
  1123. # s = RestricedSet.new { |o| o > 0 }
  1124. # s.merge(-5..5)
  1125. # assert_equal([1,2,3,4,5], s.sort)
  1126. #
  1127. # s.merge([10,-10,-8,8])
  1128. # assert_equal([1,2,3,4,5,8,10], s.sort)
  1129. # end
  1130. # end