def prefix(desc_kinds, dp) desc_kinds.map{|k| k.to_s * dp[k]}.join end def second_sort(a,b,ca,cb) [a,b,a,b].zip([ca - 1, 1, 1, cb - 1]).map{|v,c| v.to_s * c }.join end S = gets.chomp dp = Array.new(10, 0) (0 ... S.size).each do |i| dp[S[i].to_i] += 1 end k = (0 .. 9).reverse_each.select{|i| dp[i] > 0 } if k.size == 1 || dp[0] + 1 == S.size puts -1 else puts prefix(k[0,k.size - 2], dp) + second_sort(k[-2], k[-1], dp[k[-2]], dp[k[-1]]) end