Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  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"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement