r/programming • • May 09 '15

"Real programmers can do these problems easily"; author posts invalid solution to #4

https://blog.svpino.com/2015/05/08/solution-to-problem-4
3.1k Upvotes

1.3k comments sorted by

View all comments

3

u/Dank_801 May 09 '15

Couldn't you solve this very easily by looping through every possible arrangement of values given by said numbers? Then at the end of every loop you could just check to see if the new number was greater than the old (previously biggest) number?

I mean sure it wouldn't be efficient at all. but its a simple way to solve the problem...

1

u/mplsmesh May 10 '15

The problem with this approach is that you have to permute each possible combination of the numbers, which means for a list of 6 numbers, you'll generate 720 combinations, 7 numbers = 5040 combinations, 8 numbers = 40320 combinations, 9 numbers = ~360 000 combinations, and so on. This scales up really quickly ( 20 numbers means 2*1018 combinations), so you'd want a better solution. Unless, of course, you only ever needed to sort less than, say, 5 or 6 numbers, and you could only spend ~10-30 minutes on the solution, in which case optimize for programmer time.

1

u/Dank_801 May 10 '15 edited May 10 '15

Yea that's why I said it wouldn't be efficient, but it is a solution. I did however find an efficient, 3 step solution and I'll try to explain it so anyone can understand!

starting numbers:

{3, 8, 900, 9, 8000, 800, 805, 201} 
  1. You start off sorting the array by the most significant digit in DESCENDING order

    Before: {3, 8, 900, 9, 8000, 800, 805, 201} After: {9, 900, 8, 8000, 800, 805, 3, 201}

  2. Sort significant digits in ASCENDING order based off of value in digits alone (tens, hundreds, thousands)

    Before: {900, 9, 8, 8000, 800, 805, 3, 201}

    After: {9, 900, 8, 800, 805, 8000, 3, 201}

  3. Sort each section in tens - hundreds - thousands.. etc. again in descending order.

    Before: {9, 900, 8, 800, 805, 8000, 3, 201}

    After: {9, 900, 8, 805, 800, 8000, 3, 201} //800 & 805 were swapped to reflect descending in the 800's

Result:

9,900,880,580,080,003,201