Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

one-line solution #1

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Conversation

fsferrara
Copy link

thanks to Marco Sciamanna... my first solution was actually a bubble-sort 馃憥

@msciamanna
Copy link

msciamanna commented Aug 4, 2016

The idea was to put on left the highest digits.

So:

  1. Turn every element of the array (integer) in its string representation.
  2. Sort the array elements (strings) in reverse alphabetical order
  3. Concatenate the array elements
  4. Cast the result (string) into an integer

The instructions:

Step Instruction Result
0 sourceArray = [10, 51, 17, 8, 75, 9] // input array [10, 51, 17, 8, 75, 9]
1 sourceArray.map{String($0)} ["10", "51", "17", "8", "75", "9"]
2 sourceArray.map{String($0)}.sort(>) ["9", "8", "75", "51", "17", "10"]
3 sourceArray.map{String($0)}.sort(>).joinWithSeparator("") "9875511710"
4 Int(sourceArray.map{String($0)}.sort(>).joinWithSeparator(""))! 9875511710

@msciamanna
Copy link

msciamanna commented Aug 9, 2016

I realised that it doesn't work for some particular inputs :(.

Input array: [ ..., n, ..., nm, ... ] where n > m.

The algorithm sorts the array this way:

[ ..., "nm", "n", ... ], because "nm" > "n"

and then produces the output:

...nm n... that is wrong, because ...n nm... would have been higher.

Example. Using the input array: [9, 90]

The script gives 909 (because "90" > "9" in the alphabetical order) instead of the expected result 990.

@@ -17,5 +15,5 @@ XCTAssertEqual(90, largestNumberComposed(from: [9,0]))

XCTAssertEqual(910, largestNumberComposed(from: [10,9]))

XCTAssertEqual(95021, largestNumberComposed(from: [50,2,1,9]))
XCTAssertEqual(56554, largestNumberComposed(from: [54,5,56]))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you have pointed out, a lexicographic sort and concatenation is close, but not quite correct. For example, for the numbers 5, 54, and 56 a lexicographic sort will produce {5, 54, 56} (in increasing order) or {56, 54, 5} (in decreasing order), but what we really want is {56, 5, 54}, since that produces the largest number possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants