aios 2007-12-8 15:30
multiplication 乘法口诀
#filename:
# multiplication.rb
for x in 1..9
for y in 1..x
if x==y
print x,"*",y,"=",x*y,"\n"
else
print x,"*",y,"=",x*y," "
end
end
end
xavier 2007-12-8 15:45
不错,就是代码很没有ruby味~
参考这个
[url]http://www.javaeye.com/topic/24642[/url]
aios 2007-12-8 15:56
#filename:
# multiplication.rb
def multiplication(x,y)
s1=x,"*",y,"=",x*y,"\n"
s2=x,"*",y,"=",x*y," "
x==y ?s1:s2
end
(1..9).each{|x|
(1..x).each{|y| print multiplication(x,y)}
}
lgn21st 2007-12-9 03:27
这个问题非常有趣,我来一个我写的,看看是不是ruby味:
[code]
def multiplication(n)
(1..n).each do |i|
puts((1..i).map{|f| [i,'*',f,'=',i*f,' ']}.join)
end
end
multiplication(9)
[/code]
[[i] 本帖最后由 lgn21st 于 2007-12-9 04:07 编辑 [/i]]
xavier 2007-12-9 09:27
回复 #4 lgn21st 的帖子
生成数组再join是不是会慢一些?
drive2me 2007-12-9 10:59
五花八门,各显其能!
鼓励大家多来给出自己的方法!
lgn21st 2007-12-9 12:27
我也有此疑问,但效率好坏不能考经验跟知觉来猜,profile it!
[code]
require 'benchmark'
Benchmark.bm do |bm|
report1 = bm.report('aios') do
for x in 1..99
for y in 1..x
if x==y
print x,"*",y,"=",x*y,"\n"
else
print x,"*",y,"=",x*y," "
end
end
end
end
report2 = bm.report('aios2') do
def multiplication(x,y)
s1=x,"*",y,"=",x*y,"\n"
s2=x,"*",y,"=",x*y," "
x==y ?s1:s2
end
(1..99).each{|x|
(1..x).each{|y| print multiplication(x,y)}
}
end
report3 = bm.report('lgn21st') do
def multiplication(n)
(1..n).each do |i|
puts((1..i).map{|f| [i,'*',f,'=',i*f,' ']}.join)
end
end
multiplication(99)
end
puts "aios1" + report1.to_s
puts "aios2" + report2.to_s
puts "lgn21st" + report3.to_s
end
[/code]
在我的电脑上生成结果(PentiumM 1.8G)
[code]
aios1 0.050000 0.040000 0.090000 ( 0.222583)
aios2 0.050000 0.000000 0.050000 ( 0.146146)
lgn21st 0.040000 0.000000 0.040000 ( 0.071117)
[/code]
结果让我赶到惊讶,数组join的效率是最高的,其次是楼主改进算法,在次是楼主第一次算法
效率瓶颈在于楼主用print输出string时,会有连续的string append方法调用产生
数组join一次性生成string然后输出效率最高