[英]What is wrong with my && operator?
I would like to know why this is outputting false
when I input 1982
. 我想知道为什么当我输入
1982
时这会输出false
。 Is there something wrong with my &&
statement? 我的
&&
语句有问题吗? I tried using !(t==r)
, but it didn't work; 我尝试使用
!(t==r)
,但是没有用; for some reason, it keeps outputting false
. 由于某种原因,它会一直输出
false
。
def no_repeats?(year)
out=true
t=0
while t<4
r=0
while r<4
if (year[t] == year[r]) && t != r
out=false
end
r+=1
end
t+=1
end
out
end
You're probably complicating this a bit more than it needs to be. 您可能使它变得复杂了很多。
2.2.0-preview1 :001 > load 'no_repeat.rb'
=> true
Testing as a string 字符串测试
2.2.0-preview1 :002 > no_repeats?("1981")
=> false
2.2.0-preview1 :003 > no_repeats?("1983")
=> true
Testing as an integer 测试为整数
2.2.0-preview1 :004 > no_repeats?(1981)
=> false
2.2.0-preview1 :005 > no_repeats?(1983)
=> true
and no_repeat.rb
looks like 和
no_repeat.rb
看起来像
def no_repeats?(year)
digits = year.to_s.split(//)
digits.size == digits.uniq.size
end
Edit: Benchmarks 编辑:基准
Using Original Post
real 0m0.598s
user 0m0.583s
sys 0m0.015s
Using .split(//)
real 0m1.322s
user 0m1.321s
sys 0m0.000s
Using .chars.to_a
real 0m0.562s
user 0m0.557s
sys 0m0.004s
So, in efforts to make this more of a complete answer, I've included my benchmarks, each using the method 400,000 times. 因此,为了使这个问题更完整,我将基准测试包括在内,每个基准测试使用了40万次。 By using
split(//)
, you will be taking almost a 2x performance hit. 通过使用
split(//)
,您将获得几乎2倍的性能提升。 By using chars.to_a
instead, you'll be up with your original speeds. 通过使用
chars.to_a
,您将可以保持原来的速度。
def no_repeats?(year)
digits = year.to_s.chars.to_a
digits.size == digits.uniq.size
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.