Created
October 19, 2015 14:23
-
-
Save sairam/11d670729c87c6992b6f to your computer and use it in GitHub Desktop.
Find Missing Number from a string sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pry' | |
=begin | |
x =(1..400).to_a ; deleted = x.delete(Random.rand(400)); data= x.join("") | |
counter = 0 | |
prev_no = 0 | |
offset = 0 | |
loop do | |
current_no = (data[offset..(offset+counter)]).to_i | |
puts "current_no is #{current_no}" | |
# considering case where we need to find numbers which jump digits | |
if prev_no > current_no.to_i | |
puts "incr counter to #{counter+1}" | |
counter += 1 | |
current_no = (data[offset..(offset+counter)]).to_i | |
puts "current_no is #{current_no}" | |
end | |
if current_no - prev_no != 1 | |
puts "number missing is #{prev_no+1} and current_no is #{current_no}" | |
break | |
end | |
offset += 1+counter | |
prev_no = current_no | |
end | |
=end | |
# if offset is 0, start from 0 of data | |
# if current_no is nil, there is no prev no. this is the start of the loop | |
# returns a sequence | |
def find_next_number(current_no, length, offset, data) | |
puts "input is current_no #{current_no}, length #{length}, offset #{offset}, data #{data}" | |
if length == nil | |
length = 1 | |
end | |
loop do | |
if current_no != nil | |
# assuming length has not increased or to change | |
if (current_no + 1).to_s.length == current_no.to_s.length | |
length = length | |
else | |
length +=1 | |
end | |
end | |
possible_no = (data[0..(0+length-1)]).to_i | |
if !current_no.nil? | |
diff = possible_no - current_no | |
if diff == 1 | |
# happy case | |
elsif diff == 2 | |
puts "The no. is #{current_no+1}" | |
exit(2) | |
else | |
raise "err" | |
end | |
end | |
begin | |
find_next_number(possible_no, length, offset, data[length..-1]) | |
rescue => e | |
length += 1 | |
end | |
if length >= data.length | |
puts "Err. could not find a seq" | |
raise "errr" | |
end | |
end | |
end | |
data="1000 1002".gsub(" ","") | |
find_next_number(nil, nil, 0, data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ismert problémák,