Created
September 29, 2020 12:06
-
-
Save deftfitf/f71e73087d87c77cec62f563f76151df to your computer and use it in GitHub Desktop.
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
import java.util.ArrayList; | |
import java.util.List; | |
import org.apache.commons.lang3.StringUtils; | |
import org.apache.commons.lang3.tuple.Pair; | |
public class UUIDUtil { | |
public static List<Pair<String, String>> uuidSplit(int n) { | |
if (n < 2 || n > 256) { | |
throw new IllegalArgumentException("The number of divisions n supports between 2 and 256"); | |
} | |
final var acm = new ArrayList<Pair<String, String>>(); | |
recursiveSplit(0, log2(n), 0, 0, acm); | |
return acm; | |
} | |
private static int log2(double a) { | |
return (int) Math.ceil(Math.log(a) / Math.log(2)); | |
} | |
private static void recursiveSplit( | |
int i, int upper, long _start, long _end, | |
List<Pair<String, String>> acm | |
) { | |
if (i >= upper) { | |
final int digits = (int) Math.ceil((double) upper / 4); | |
final var startHex = Long.toHexString(_start); | |
final var endHexArr = Long.toHexString(_end).toCharArray(); | |
endHexArr[endHexArr.length - 1] += 1; | |
acm.add(Pair.of( | |
StringUtils.repeat('0', digits - startHex.length()) + startHex, | |
StringUtils.repeat('0', digits - endHexArr.length) + new String(endHexArr))); | |
return; | |
} | |
long start = _start; | |
long end = _end; | |
if (i % 4 == 0) { | |
start <<= 4; | |
end = (end << 4) | 0xf; | |
} | |
final long mid = start + ((end & 0xf) - (start & 0xf)) / 2; | |
recursiveSplit(i + 1, upper, start, mid, acm); | |
recursiveSplit(i + 1, upper, mid + 1, end, acm); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment