Chris
Chris

Reputation: 1229

clever way to write numbers as sortable text?

The naive approach is printf("%10d",num) but if number is greater than 10 digits then this process will fail.

Take printf("%2d",num) for example and these numbers 1, 12, 100 They will write out as: 01,12 and 100 but will sort alphanumerically as 01, 100, 12 which is wrong.

To get the answer right, it must be sortable as plain ASCII text.

Most of the numbers written out will be small and occasionally it will be large numbers written out. For space concerns padding with zeros isn't that great way of doing it.

Is this possible?

Upvotes: 0

Views: 85

Answers (2)

Chris
Chris

Reputation: 1229

Inspired by Stephan Lechner's insight,

String sortable(long n) {
    int radix = 36;
    int exponent= (int) floor(log10(n));
    String x = Long.toString(exponent, radix)+Long.toString(n, radix);
    return x;
}

@Test
public void test() {        
    out.println(sortable(1));
    out.println(sortable(20));      
    out.println(sortable(200));
    out.println(sortable(100000));
    out.println(sortable(10000000));
    out.println(sortable(12466521));
    out.println(sortable(20000000));
}

Which outputs:

01
1k
25k
5255s
75yc1s
77f789
7bwo3k

That's far shorter than outputting 00000000000000000001 for 1 and the rest. (A 64 long can take up to 20 chars.)

Upvotes: 1

Stephan Lechner
Stephan Lechner

Reputation: 35154

If large numbers appear only occasionally, than you could prefix your small numbers with '+', and for your large numbers, use as many leading zeros such that the group of large numbers is sorted correctly. For example, the following list is sorted 'correctly':

+01
+12
000100

Of course, you have to proof that the "trick" of preceding a number with '+' does not break any code reading in these lists again.

Upvotes: 1

Related Questions