SHARE
TWEET

Untitled

a guest Apr 26th, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ##
  2. # This doesn't work! :-(
  3. ##
  4.  
  5. def max_concat_number(list)
  6.   # Find the "length" of the maximum number.
  7.   length = list.max.to_s.length
  8.  
  9.   # Normalize the list by padding every number to the maximum length.
  10.   padded = list.map(&:to_s).map { |n| n.ljust(length, "0") }
  11.  
  12.   # Create a hash with the padded numbers as keys and the "actual" numbers as values.
  13.   arranged = padded.each_with_index.each_with_object({}) do |(element, index), arranged_hash|
  14.     arranged_hash[element] = list[index]
  15.   end
  16.  
  17.   # Sort the hash by the keys, then pick up just the numbers.
  18.   sorted = arranged.sort.reverse.map { |a| a[1] }
  19.  
  20.   # Finally, join the sorted list.
  21.   sorted.map(&:to_s).join
  22. end
  23.  
  24. list = [50, 2, 99, 1, 958, 9, 6, 80]
  25. p max_concat_number(list)
  26. # => "9995898065021"
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top