Last active
February 24, 2019 20:14
-
-
Save k06a/a7e3fb97e0303bb05f776cfbce801540 to your computer and use it in GitHub Desktop.
n2-to-n
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
typedef unsigned __int64 u64; | |
// | |
// i\j 0 1 2 3 4 | |
// 0 0 2 5 9 | |
// 1 1 4 8 | |
// 2 3 7 | |
// 3 6 | |
// 4 | |
// | |
u64 ijton(u64 i, u64 j) { | |
return (i + j) * (i + j + 1) / 2 + j; | |
} | |
// i\j 0 1 2 3 4 | |
// 0 0 2 5 9 | |
// 1 1 4 8 | |
// 2 3 7 | |
// 3 6 | |
// 4 | |
pair<u64,u64> ntoij(u64 n) { | |
u64 w = (u64)((sqrt(8.0 * n + 1.0) - 1.0) / 2.0); | |
u64 t = w * (w + 1) / 2; | |
return make_pair(w - (n - t), n - t); | |
} |
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
void ijton_tests() { | |
#define EXPECT_EQ(expected, actual, error) \ | |
do if (expected != actual) cout << error; while (0) | |
// i\j 0 1 2 3 4 | |
// 0 0 2 5 9 | |
// 1 1 4 8 | |
// 2 3 7 | |
// 3 6 | |
// 4 | |
EXPECT_EQ(0, ijton(0,0), "Error ijton(i,j) on 0,0\n"); | |
EXPECT_EQ(1, ijton(1,0), "Error ijton(i,j) on 1,0\n"); | |
EXPECT_EQ(2, ijton(0,1), "Error ijton(i,j) on 0,1\n"); | |
EXPECT_EQ(3, ijton(2,0), "Error ijton(i,j) on 2,0\n"); | |
EXPECT_EQ(4, ijton(1,1), "Error ijton(i,j) on 1,1\n"); | |
EXPECT_EQ(5, ijton(0,2), "Error ijton(i,j) on 0,2\n"); | |
} | |
void ntoij_tests() { | |
#define EXPECT_EQ(expected, actual, error) \ | |
do if (expected != actual) cout << error; while (0) | |
// i\j 0 1 2 3 4 | |
// 0 0 2 5 9 | |
// 1 1 4 8 | |
// 2 3 7 | |
// 3 6 | |
// 4 | |
pair<u64,u64> p(0,0); | |
EXPECT_EQ(p, ntoij(0), "Error ntoij(n) on 0\n"); | |
p = pair<u64,u64>(1,0); | |
EXPECT_EQ(p, ntoij(1), "Error ntoij(n) on 1\n"); | |
p = pair<u64,u64>(0,1); | |
EXPECT_EQ(p, ntoij(2), "Error ntoij(n) on 2\n"); | |
p = pair<u64,u64>(2,0); | |
EXPECT_EQ(p, ntoij(3), "Error ntoij(n) on 3\n"); | |
p = pair<u64,u64>(1,1); | |
EXPECT_EQ(p, ntoij(4), "Error ntoij(n) on 4\n"); | |
p = pair<u64,u64>(0,2); | |
EXPECT_EQ(p, ntoij(5), "Error ntoij(n) on 5\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment