Jump to content

Set of real numbers: Difference between revisions

→‎{{header|Ruby}}: bug fix, change display format.
(→‎{{header|Ruby}}: add length method and Optional work)
(→‎{{header|Ruby}}: bug fix, change display format.)
Line 1,233:
end
def to_s
"%s%s,%s%s" % [#{inc_lo ? "'["' : "'(", '}#{lo}, #{hi, }#{inc_hi ? "']"' : "')'}"]
end
end
Line 1,251:
end
def self.from_sparse(str)
raise ArgumentError unless str =~ /(\[|\()(.+),(.+)(\]|\))/
b0, lo, hi, b1 = $~.captures # $~ : Regexp.last_match
Line 1,261:
end
def dupinitialize_copy(obj)
super
new_Rset(@sets = @sets.map(&:dup))
end
Line 1,362 ⟶ 1,363:
def ==(other)
return false if self.class !== other.class and @sets == other.sets
@sets == other.sets
end
Line 1,371:
def to_s
"#{self.class}" + #{@sets.map(&:to_s).join(',')}"
end
alias inspect to_s
Line 1,424:
test_set.each do |sa,ope,sb|
str = "#{sa} #{ope} #{sb}"
e = eval("Rset.from_sparse(sa) #{ope} Rset.from_sparse(sb)")
puts "%s -> %s" % [str, e]
(0..2).each{|i| puts " #{i} : #{e.include?(i)}"}
Line 1,440:
inf = 1.0 / 0.0 # infinity
puts "a = #{a = Rset(-inf,inf)}"
puts "b = #{b = Rset.from_sparse('[1/3,11/7)')}"
puts "a - b -> #{a - b}"</lang>
 
Line 1,451:
 
Rset[0,2) | Rset(1,3) -> Rset[0,3)
Rset[0,1) | Rset(2,3] -> Rset[0,1),(2,3]
 
Rset[0,2) & Rset(1,3) -> Rset(1,2)
Line 1,459:
Rset[0,2) - Rset(1,3) -> Rset[0,1]
Rset[0,2) - Rset[0,2) -> Rset
Rset(0,3] - Rset[1,2] -> Rset(0,1),(2,3]
 
Test :
Line 1,470:
1 : false
2 : false
[0, 3) - (0, 1) -> Rset[0,0],[1,3)
0 : true
1 : true
Line 1,479:
2 : true
 
x = Rset[0,2] | Rset(3,7) | Rset[8,10] -> Rset[0,2],(3,7),[8,10]
y = Rset(7,9) | Rset(5,6) | Rset[1,4] -> Rset[1,4],(5,6),(7,9)
x | y -> Rset[0,7),(7,10]
x & y -> Rset[1,2],(3,4],(5,6),[8,9)
x - y -> Rset[0,1),(4,5],[6,7),[9,10]
y - x -> Rset(2,3],(7,8)
x ^ y -> Rset[0,1),(2,3],(4,5],[6,7),(7,8),[9,10]
y ^ x == (x | y) - (x & y) -> true
 
a = Rset(-Infinity,Infinity)
b = Rset[1/3,11/7)
a - b -> Rset(-Infinity,1/3),[11/7,Infinity)
</pre>
 
'''Optional work:'''
{{works with|Ruby|2.1+}}
(with Rational suffix.)
<lang ruby>str, e = "e = Rset.new", nil
puts "#{str} -> #{eval(str)}\t\t# create empty set"
Line 1,532 ⟶ 1,533:
e.empty? -> true
 
a : Rset(0.4082482904638631,0.912870929175277),(1.0801234497346435,1.3540064007726602),(1.4719601443879746,1.6832508230603467), ... (9.907909298467901,9.941495528004495),(9.958246164193106,9.991663191547909)
a.length : 6.50103079235655
b : Rset(1/6,5/6),(7/6,11/6),(13/6,17/6),(19/6,23/6),(25/6,29/6),(31/6,35/6),(37/6,41/6),(43/6,47/6),(49/6,53/6),(55/6,59/6)
b.length : 20/3
a - b : Rset[5/6,0.912870929175277),(1.0801234497346435,7/6],[11/6,1.9578900207451218),(2.041241452319315,13/6], ... (9.907909298467901,9.941495528004495),(9.958246164193106,9.991663191547909)
(a-b).length : 2.0758648411846745
</pre>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.