1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//! # Hamming Distance
//!
//! Hamming Distance measures the similarity between two integer-valued vectors of the same length.
//! Given two vectors \\( x \in ℝ^n \\), \\( y \in ℝ^n \\) the hamming distance between \\( x \\) and \\( y \\), \\( d(x, y) \\), is the number of places where \\( x \\) and \\( y \\) differ.
//!
//! Example:
//!
//! ```
//! use smartcore::metrics::distance::Distance;
//! use smartcore::metrics::distance::hamming::Hamming;
//!
//! let a = vec![1, 0, 0, 1, 0, 0, 1];
//! let b = vec![1, 1, 0, 0, 1, 0, 1];
//!
//! let h: f64 = Hamming::new().distance(&a, &b);
//!
//! ```
//!
//! <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
//! <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;

use super::Distance;
use crate::linalg::basic::arrays::ArrayView1;
use crate::numbers::basenum::Number;

/// While comparing two integer-valued vectors of equal length, Hamming distance is the number of bit positions in which the two bits are different
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
pub struct Hamming<T: Number> {
    _t: PhantomData<T>,
}

impl<T: Number> Hamming<T> {
    /// instatiate the initial structure
    pub fn new() -> Hamming<T> {
        Hamming { _t: PhantomData }
    }
}

impl<T: Number> Default for Hamming<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Number, A: ArrayView1<T>> Distance<A> for Hamming<T> {
    fn distance(&self, x: &A, y: &A) -> f64 {
        if x.shape() != y.shape() {
            panic!("Input vector sizes are different");
        }

        let dist: usize = x
            .iterator(0)
            .zip(y.iterator(0))
            .map(|(a, b)| match a != b {
                true => 1,
                false => 0,
            })
            .sum();

        dist as f64 / x.shape() as f64
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg_attr(
        all(target_arch = "wasm32", not(target_os = "wasi")),
        wasm_bindgen_test::wasm_bindgen_test
    )]
    #[test]
    fn hamming_distance() {
        let a = vec![1, 0, 0, 1, 0, 0, 1];
        let b = vec![1, 1, 0, 0, 1, 0, 1];

        let h: f64 = Hamming::new().distance(&a, &b);

        assert!((h - 0.42857142).abs() < 1e-8);
    }
}