Cantor_Pair/
lib.rs

1///
2/// Gets a unique value based on two inputs
3///
4fn cantor_pair(n: &usize, m: &usize) -> usize {
5    (n + m) * (n + m + 1) / 2 + m
6}
7
8///
9/// Gets the unique inputs from a cantor number
10///
11fn cantor_unpair(z: &usize) -> (usize, usize) {
12    let w64 = (8 * z + 1) as f64;
13    let w64two = ((w64.sqrt() - 1.0) / 2.0).floor() as usize;
14    let t = (w64two * w64two + w64two) / 2;
15    let m = z - t;
16    let n = w64two - m;
17    return (n, m);
18}
19
20#[cfg(test)]
21mod tests {
22    use super::*;
23
24    ///
25    /// Tests some values that I picked out
26    ///
27    #[test]
28    fn ensure_equal_values() {
29        let test_values = [(0, 0), (0, 1), (1, 0), (5, 5), (10000, 10000)];
30        for (a, b) in test_values {
31            let cantor = cantor_pair(&a, &b);
32            let (aout, bout) = cantor_unpair(&cantor);
33            dbg!(cantor, aout, bout, a, b);
34            assert_eq!((a, b), (aout, bout));
35        }
36    }
37}