Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

nuby: method defined in two classes

0 views
Skip to first unread message

Peña, Botp

unread,
Dec 7, 2005, 2:06:56 AM12/7/05
to
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...

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 = self
my_loop do |i|
break i if n==1
if n.is_odd?
n = 3*n + 1
else
n = n / 2
end
end
end

def is_odd?
self & 1 != 0
end
end

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

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

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

puts "from \t To \t Max Cycle \t Elapsed Time (sec)"
DATA.each do |pair|
time_start = Time.now
i,j = pair.split
k = 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


Trans

unread,
Dec 7, 2005, 2:13:26 AM12/7/05
to
Facets:

Integer#odd?

T.

Joel VanderWerf

unread,
Dec 7, 2005, 2:14:01 AM12/7/05
to
Peña wrote:
> 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...

Why not define #is_odd? on Integer?

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


Peña, Botp

unread,
Dec 7, 2005, 2:55:50 AM12/7/05
to
#From: Trans [mailto:tran...@gmail.com]

# Integer#

i was a dumber :) Thanks for the tip, Trans.


Peña, Botp

unread,
Dec 7, 2005, 2:55:50 AM12/7/05
to
Joel VanderWerf [mailto:vj...@path.berkeley.edu]

#Why not define #is_odd? on Integer?

yap, that was my fault :)) Thanks.


0 new messages