Reputation: 361
I would like to know why this is outputting false
when I input 1982
. Is there something wrong with my &&
statement? I tried using !(t==r)
, but it didn't work; for some reason, it keeps outputting 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
Upvotes: 0
Views: 68
Reputation: 7070
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
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. By using split(//)
, you will be taking almost a 2x performance hit. By using chars.to_a
instead, you'll be up with your original speeds.
def no_repeats?(year)
digits = year.to_s.chars.to_a
digits.size == digits.uniq.size
end
Upvotes: 2