5 of 6
Changed 31 by 9 because a number will never contain more than 7 digits (see requirements).
Olivier Grégoire
- 14.5k
- 3
- 33
- 56
Java (JDK), 98 bytes
l->l.sort((a,b)->{int r=0,i=58;for(;r==0&i-->48;)r=(b.indexOf(i)>>9)-(a.indexOf(i)>>9);return r;})
Explanation
l-> // Consumer<List<String>>
l.sort( // Use the incorporated sort method which uses a...
(a,b)->{ // Comparator of Strings
int r=0, // define r as the result, initiated to 0
i=58; // i as the codepoint to test for.
for(;r==0&i-->48;) // for each digit codepoint from '9' to '0',
// and while no difference was found.
r= // set r as the difference between
(b.indexOf(i)>>9)- // was the digit found in b? then 0 else 1 using the bit-shift operator
(a.indexOf(i)>>9); // and was the digit found in a? then 0 else 1.
return r; // return the comparison result.
}
)
Note:
I needed a way to map numbers to either 0/1 or 0/-1.
indexOf has the nice property that it's consistently returning -1 for characters not found. -1 right-shifted by any number is always -1. Any positive number right-shifted by a big enough number will always produce 0.
So here we are:
input input.indexOf('9') input.indexOf('9')>>9
"999" 0 0
"111119" 5 0
"123456" -1 -1
Olivier Grégoire
- 14.5k
- 3
- 33
- 56