Maxie and Minnie
The maxxie of a number n
is the largest number you can achieve by swapping two of its digits (in decimal) (or choosing not to swap if it is already the largest possible). The minnie is the smallest with one swap (though you can't swap a zero digit into the most significant position).
Your task is to write a function that takes an integer and returns a tuple of the maxxie and minnie.
Examples
(swapmaxmin 213) ;=> [312, 123]
(swapmaxmin 12345) ;=> [52341, 12345] ;; the number was already the smallest
(swapmaxmin 100) ;=> [100, 100] ;; no swap possible because of zeroes
Notes
- Swap any two decimal digits
- No leading zeroes
- Don't swap if you can't make it bigger/smaller
Thanks to this site for the problem idea, where it is rated Expert in Ruby. The problem has been modified.
Please submit your solutions as comments on this gist.
To subscribe: https://ericnormand.me/newsletter
I sorted the digits, bypassing one or both results depending on the presence of zeroes.
I wanted to do a single pass for both min and max values, and was looking for a
sorted-vector-by
withinclojure.core
, but couldn't find one, so translated java.util.Arrays.binSearch0 with the use ofclojure.core/comparator
An IPersistentTreeVector would be nice, maybe using IPersistentTreeMap underneath (as is done with IPersistentTreeSet.java). Then a
sorted-vector
function could yield something that is super fast and truly O(log n), instead of whatsorted-conj
below, does. Alternatively, a transient coll could be used to do each insert.