Skip to content

Instantly share code, notes, and snippets.

@orihpt
Created February 11, 2023 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orihpt/462acf6985e3c63744dac36528543598 to your computer and use it in GitHub Desktop.
Save orihpt/462acf6985e3c63744dac36528543598 to your computer and use it in GitHub Desktop.
This code demonstrates how it's possible to compress two numbers into one and then convert it back to two numbers.
public class TwoNumbersCompression {
public static void main(String[] args) {
double compressed = compress(-5.57,8);
System.out.println("Compressed: " + compressed);
double[] decompressed = decompress(compressed);
System.out.println("Decompressed: " + decompressed[0] + ", " + decompressed[1]);
}
// Convert to between 0 and 1
public static double convert(double a) {
// 0.5 + tan^-1(a) / pi
return 0.5 + Math.atan(a) / Math.PI;
}
// Convert back to original number
public static double convertBack(double a) {
// tan(pi * (a - 0.5))
return Math.tan(Math.PI * (a - 0.5));
}
// Compress two numbers into one
public static double compress(double a, double b) {
double a1 = convert(a);
double b1 = convert(b);
// Compression algorithm
// (0.abcde, 0.fghij) -> 0.afbgchdiej
// Explanation: a and f are the first digits, b and g are the second, etc.
// Convert a1 to string
String a1s = Double.toString(a1);
// Convert b1 to string
String b1s = Double.toString(b1);
// Remove the 0. from the beginning of the strings
a1s = a1s.substring(2);
b1s = b1s.substring(2);
// Create a new string to store the compressed number
String c = "0.";
// Loop through the strings
for (int i = 0; i < Math.min(a1s.length(), b1s.length()); i++) {
// Add the first digit of a1s to c
c += a1s.charAt(i);
// Add the first digit of b1s to c
c += b1s.charAt(i);
}
// Convert c to a double and return it
return Double.parseDouble(c);
}
// Decompress a number into two numbers
public static double[] decompress(double c) {
// Convert c to string
String cs = Double.toString(c);
// Remove the 0. from the beginning of the string
cs = cs.substring(2);
// Create two new strings to store the decompressed numbers
String a1s = "0.";
String b1s = "0.";
// Loop through the string
for (int i = 0; i < cs.length(); i++) {
// If i is even, add the digit to a1s
if (i % 2 == 0) {
a1s += cs.charAt(i);
}
// If i is odd, add the digit to b1s
else {
b1s += cs.charAt(i);
}
}
// Convert a1s and b1s to doubles
double a1 = Double.parseDouble(a1s);
double b1 = Double.parseDouble(b1s);
// Convert a1 and b1 back to the original numbers
double a = convertBack(a1);
double b = convertBack(b1);
// Round the numbers to 5 decimal places
a = Math.round(a * 100000) / 100000.0;
b = Math.round(b * 100000) / 100000.0;
// Return the decompressed numbers
return new double[] {a, b};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment