inverse pairing function

This commit is contained in:
boy0001 2015-03-26 21:44:31 +11:00
parent abe9d9f5ac
commit e039bbd56a

View File

@ -83,6 +83,47 @@ public class PlotId {
return this.x + ";" + this.y;
}
public PlotId unpair(int hash) {
if (hash >= 0) {
if (hash % 2 == 0) {
// + +
hash /= 2;
int i = (int) (Math.abs(-1 + Math.sqrt(1 + 8 * hash)) / 2);
int idx = hash - ((i * (1 + i)) / 2);
int idy = ((i * (3 + i)) / 2) - hash;
return new PlotId(idx, idy);
}
else {
// + -
hash -= 1;
hash /= 2;
int i = (int) (Math.abs(-1 + Math.sqrt(1 + 8 * hash)) / 2);
int idx = hash - ((i * (1 + i)) / 2);
int idy = ((i * (3 + i)) / 2) - hash;
return new PlotId(idx, -idy);
}
}
else {
if (hash % 2 == 0) {
// - +
hash /= -2;
int i = (int) (Math.abs(-1 + Math.sqrt(1 + 8 * hash)) / 2);
int idx = hash - ((i * (1 + i)) / 2);
int idy = ((i * (3 + i)) / 2) - hash;
return new PlotId(-idx, idy);
}
else {
// - -
hash += 1;
hash /= -2;
int i = (int) (Math.abs(-1 + Math.sqrt(1 + 8 * hash)) / 2);
int idx = hash - ((i * (1 + i)) / 2);
int idy = ((i * (3 + i)) / 2) - hash;
return new PlotId(-idx, -idy);
}
}
}
@Override
public int hashCode() {
if (this.x >= 0) {