nuby: method defined in two classes

P

Peña, Botp

Hi Friends,

I have the ff code below. It works but you can see that i have =
duplicated the "is_odd?" method on both Fixnum and Bignum. I am just =
asking for something more cleaner/elegant...=20

thanks and kind regards -botp

code follows...

:~/ruby # cat test1.rb
#-----------------------------------------------
# http://acm.uva.es/p/v1/100.html
# 3n + 1 problem
#-----------------------------------------------

class Fixnum
def cycles_3n_1
n =3D self
my_loop do |i|
break i if n=3D=3D1
if n.is_odd?
n =3D 3*n + 1
else
n =3D n / 2
end
end
end

def is_odd?
self & 1 !=3D 0
end
end

class Bignum
def is_odd?
self & 1 !=3D 0
end
end

def my_loop
c =3D 1
loop do
yield c
c +=3D 1
end
end

def get_max first, last
max =3D -1
first.upto(last) do |i|
c =3D i.cycles_3n_1
max =3D c if c>max
end
max
end

puts "from \t To \t Max Cycle \t Elapsed Time (sec)"
DATA.each do |pair|
time_start =3D Time.now
i,j =3D pair.split
k =3D get_max i.to_i, j.to_i
puts "#{i} \t #{j} \t #{k} \t\t #{Time.now-time_start}"
end


__END__
1 10
100 200
201 210
900 1000
1 1_000_000


:~/ruby # ruby test1.rb
from To Max Cycle Elapsed Time (sec)
1 10 20 0.001598
100 200 125 0.073956
201 210 89 0.005831
900 1000 174 0.094012
1 1_000_000 525 1801.349531
 
J

Joel VanderWerf

Pe=F1a said:
Hi Friends,
=20
I have the ff code below. It works but you can see that i have duplicat=
ed the "is_odd?" method on both Fixnum and Bignum. I am just asking for s=
omething more cleaner/elegant...=20

Why not define #is_odd? on Integer?

--=20
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top