Created
July 17, 2019 13:34
-
-
Save ramprabhu-idexcel/f15d56e87c8e938d4f80b607d4a97c49 to your computer and use it in GitHub Desktop.
Implement a ruby method to find the next largest number with the same digits of the input number. Ex: 38276 would return 38627.
This file contains hidden or 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
class NextGreaterPermutation | |
attr_reader :digits | |
def initialize(number) | |
@digits = number.to_s.chars | |
end | |
def display | |
return 'Not Possible' if smaller_digit_idx.nil? | |
digits[smaller_digit_idx], digits[larger_digit_idx] = digits[larger_digit_idx], digits[smaller_digit_idx] | |
[digits[0..smaller_digit_idx], digits[smaller_digit_idx+1..-1].reverse].join.to_i | |
end | |
private | |
def smaller_digit_idx | |
@smaller_digit_idx ||= digits.each_cons(2).to_a.rindex { |a, b| a < b } | |
end | |
def larger_digit_idx | |
@larger_digit_idx ||= digits.rindex { |n| digits[smaller_digit_idx] < n } | |
end | |
end | |
p '----------------------------------------------------------' | |
p "Input: 38276" | |
next_greater_permutation = NextGreaterPermutation.new(38276) | |
p "Output: #{next_greater_permutation.display}" | |
p '----------------------------------------------------------' | |
p "Input: 218765" | |
next_greater_permutation = NextGreaterPermutation.new(218765) | |
p "Output: #{next_greater_permutation.display}" | |
p '----------------------------------------------------------' | |
p "Input: 4321" | |
next_greater_permutation = NextGreaterPermutation.new(4321) | |
p "Output: #{next_greater_permutation.display}" | |
p '----------------------------------------------------------' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment