Reputation: 181
I'm working on a Ruby challenge to take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
for example:
Input: 145263 Output: 654321
Input: 123456789 Output: 987654321
Currently this is what my solution looks like:
def descending_order(n)
# take any non-negative integer as an argument
# return it with digits in descending order
n.sqrt(1){ |digits| digits.sort_by.reverse }
end
However, it keeps throwing an error message saying:
`descending_order': undefined method `sqrt' for 0:Integer (NoMethodError)
Upvotes: 1
Views: 1120
Reputation: 2222
I think the easiest to understand answer is:
n = 145263
n.digits.sort.reverse.join.to_i
n.digits => [3, 6, 2, 5, 4, 1]
n.digits.sort => [1, 2, 3, 4, 5, 6]
n.digits.sort.reverse => [6, 5, 4, 3, 2, 1]
n.digits.sort.reverse.join => "654321"
n.digits.sort.reverse.join.to_i => 654321
digits => Returns the digits of ints place-value representation with radix base (default: 10). The digits are returned as an array with the least significant digit as the first array element.
sort => Returns a new array created by sorting self.
reverse => Returns a new array containing selfs elements in reverse order.
join => Returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses an empty string.
to_i => Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36).
I like Tom Lord's answer in his comment. It's a bit cryptic at first, but Stefan's explanation is excellent.
Upvotes: 1
Reputation: 22225
def descending_order(n)
n.to_s.split(//).sort.reverse.join.to_i
end
This creates an array of strings, each string being a single digit as text. We can use the normal sort here, because we can reasonably assume that the collating sequence of the digits in an encoding obeys the same order than their numeric counterpart. In particular, we know that i.e. '4' < '8'
.
Upvotes: 4