Saturday, June 25, 2022

Friday, May 27, 2022

reorder an int as big as possible

 I found https://www.codewars.com/ and solving a algorithm question, reorder given number as big as possible, example given 123, ordered biggest version is 321, so we just need to order digits separately and concatenate them, I wrote 2 approaches

public void testStreamCode() {
int num = 123;
AtomicReference<String> str = new AtomicReference<>();
String.valueOf(num).chars().boxed().sorted(Collections.reverseOrder()).forEach(c -> str.updateAndGet(v -> v + (c - 48)));
int parseInt = Integer.parseInt(str.get().replaceAll("null", ""));
assert parseInt == 321;
}

public void testArraysSortCode() {
int num = 7657585;
char[] c = String.valueOf(num).toCharArray();
Arrays.sort(c);
String s = "";
for (int i = c.length - 1; i >= 0; i--)
s += c[i];
Integer integer = Integer.valueOf(s);
assert integer == 8776555;
}
then CW gave another solution
public void cw() {
int num = 7657585;
int i1 = Integer.parseInt(String.valueOf(num)
.chars()
.mapToObj(i -> String.valueOf(Character.getNumericValue(i)))
.sorted(Comparator.reverseOrder())
.collect(Collectors.joining()));
assert i1 == 8776555;
}

I know java stream api looks cool and I decided to benchmark this. here is the result
Benchmark                                Mode  Cnt  Score   Error  Units
DemoApplicationTests.cw avgt 2 0.808 us/op
DemoApplicationTests.testArraysSortCode avgt 2 0.194 us/op
DemoApplicationTests.testStreamCode avgt 2 0.884 us/op
 
fastest is using arrays.sort(0.194) second is CW and last one is "testStreamCode".