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

Show parent comments

2

u/Kaligraphic May 09 '15 edited May 09 '15

I did it a lazy way. I copied the numbers into a second array, but converted to floats. For each value, while that value is >10, I divided it by 10. That gave me single-digit numbers that I could sort.

Then I sorted the copy, but with a twist - I did the comparisons on the second array, but I did the moves on both arrays. This effectively sorted both arrays by the highest first digit. (I just did a bubble sort for proof of concept and because I'm a lazy git who normally uses Array.Sort() or equivalent, but a quicksort or better is fine too.)

then I spit out the string representations of every value in the first array, in order.

Then I realized that 9.1 sorts before 9, when I should put the 9 first. At this point, I realize that even if I had used a padding trick, 910 sorts before 900, so it would have been the same result, and I ended up concluding that brute force may actually be the only workable option.

0

u/[deleted] May 09 '15

[deleted]

1

u/Kaligraphic May 09 '15

True, but the constant overhead seemed like it would be greater than the average time the while loop would take, especially if we're mostly looking at one and occasionally two digit numbers. If the average expected value of n is less than 1.5, and the maximum expected value is 3, even O(n2) wouldn't seem so bad.

Then again, I could challenge myself on the grounds that CPU pipelines are long enough that the while loop might cost more in terms of branch misprediction. And now I want to devise an experiment to find out, but the results may well vary depending on the CPU that runs it. I suspect that a comparison and simple division would still be cheaper, but...

1

u/glemnar May 09 '15

log() isn't O(1) for big enough numbers.

It's all perspective : D

0

u/[deleted] May 09 '15

[deleted]

2

u/glemnar May 09 '15 edited May 09 '15

It depends. http://stackoverflow.com/questions/7317414/what-is-the-complexity-of-the-log-function

Besides, if you allow for arbitrary precision difference you just get a wrong answer. At high enough scales, even simple operations aren't O(1) is the point.

http://en.wikipedia.org/wiki/Computational_complexity_of_mathematical_operations

1

u/hpp3 May 09 '15

You've effectively done a lexigraphical sort, which is what the string sort does.

1

u/Kaligraphic May 09 '15

Yeah, which is why it fails the same way.