Last active
July 3, 2016 19:40
-
-
Save jooeycheng/d3e04f6931e6cdcd360336ac919b73c6 to your computer and use it in GitHub Desktop.
Function that rearranges an array of positive integers to produce largest possible integer when concatenated
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# === Program | |
class Main | |
def compare(n1, n2) | |
(n1 + n2).to_i > (n2 + n1).to_i | |
end | |
def special_sort(arr) | |
result = [] | |
temp = [] | |
arr.each do |el| | |
el = el.to_s | |
while result.length > 0 && compare(el, result[-1]) | |
temp.push(result.pop) | |
end | |
result.push(el) | |
while temp.length > 0 | |
result.push(temp.pop) | |
end | |
end | |
result.join.to_i | |
end | |
end | |
# === Unit Tests | |
require 'minitest/autorun' | |
require 'minitest/reporters' | |
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new | |
class TestMain < Minitest::Test | |
def setup | |
@main = Main.new | |
@data = [ | |
{ arr: [47, 2, 3, 8], ans: 84732 }, | |
{ arr: [47, 40, 4], ans: 47440 }, | |
{ arr: [42, 40, 4], ans: 44240 }, | |
{ arr: [421, 42, 423], ans: 42423421 }, | |
{ arr: [47, 2, 3, 8, 47, 40, 4, 42, 40, 4, 421, 42, 423], ans: 84747444242423421404032 } | |
] | |
end | |
def test_compare | |
assert_equal false, @main.compare("421", "42") | |
assert_equal true , @main.compare("42", "421") | |
end | |
def test_special_sort | |
@data.each do |el| | |
assert_equal el[:ans], @main.special_sort(el[:arr]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment