I wrote below function to return unique years (with unrepeated digits) in a range of years. My results turned out to be fine, however, the spec requires a certain format which my join function returned array of string instead of numbers. How do I convert the end result to an array of numbers as spec required?
def no_repeat?(year)
idx = 1
str = year.to_s
while idx < str.length
if str[0] == str[idx]
return false
end
idx += 1
end
return true
end
def no_repeats(year_start, year_end)
diff = year_end - year_start
idx = 0
new = []
while idx <= diff
year = year_start + idx
if no_repeat?(year)
new.push(year.to_i)
end
idx += 1
end
return [new.join(",")]
end
Test Results:
#no_repeats
should return a no repeat year (FAILED - 1)
should not return a repeat year (FAILED - 2)
should return only those years that have no repeated digits (FAILED - 3)
Failures:
1) #no_repeats should return a no repeat year
Failure/Error: no_repeats(1234, 1234).should == [1234]
expected: [1234]
got: ["1234"] (using ==)
# ./spec/01_no_repeats_spec.rb:16:in `block (2 levels) in <top (required)>'
2) #no_repeats should not return a repeat year
Failure/Error: no_repeats(1123, 1123).should == []
expected: []
got: [""] (using ==)
# ./spec/01_no_repeats_spec.rb:20:in `block (2 levels) in <top (required)>'
3) #no_repeats should return only those years that have no repeated digits
Failure/Error: ]
expected: [1980, 1982, 1983, 1984, 1985, 1986, 1987]
got: ["1980,1982,1983,1984,1985,1986,1987"] (using ==)
# ./spec/01_no_repeats_spec.rb:32:in `block (2 levels) in <top (required)>'
Finished in 0.00139 seconds
3 examples, 3 failures
Failed examples:
rspec ./spec/01_no_repeats_spec.rb:15 # #no_repeats should return a no repeat year
rspec ./spec/01_no_repeats_spec.rb:19 # #no_repeats should not return a repeat year
rspec ./spec/01_no_repeats_spec.rb:23 # #no_repeats should return only those years that have no repeated digits
def no_repeats(start_year, end_year); (start_year..end_year).select { |year| year.to_s == year.to_s.split('').uniq.join }; end