Last active
February 26, 2023 20:30
-
-
Save carl-mastrangelo/7449e3bb3f92b7cc06fc6ab7117de6ad to your computer and use it in GitHub Desktop.
Small number encoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Writes numbers less than 172 in one byte, numbers less than 1936 in 2 bytes. | |
private static void writeInt(OutputStream os, int i) throws IOException { | |
if (i < 0) { | |
throw new UnsupportedOperationException("no neg"); | |
} else if (i < 172) { | |
os.write((byte) i); | |
} else if (i < 1936) { | |
i -= 172; | |
os.write((byte)(172 + 42 + (i % 42))); | |
os.write((byte)(172 + (i / 42))); | |
} else { | |
throw new UnsupportedOperationException("too big"); | |
} | |
} | |
@Test | |
public void run() throws IOException { | |
var baos = new ByteArrayOutputStream(); | |
List<Integer> ints = new ArrayList<>(); | |
SplittableRandom s = new SplittableRandom(1); | |
for (int i = 0; i < 10_000; i++) { | |
final double mean = 150; | |
final double max = 1936; | |
var r = -Math.log(s.nextDouble(Math.nextUp(0.0), 1)) * mean; | |
ints.add(Math.toIntExact(Math.round(Math.max(Math.min(max, r), 0)))); | |
} | |
for (Integer i : ints) { | |
writeInt(baos, i); | |
} | |
System.out.println(baos.size()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment