r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
// Translation of nmath's rwilcox
//
// Copyright (C) 2020 neek-sss
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use strafe_type::{FloatConstraint, Natural64, Real64};

use crate::traits::RNG;

/// Random variates from the Wilcoxon distribution.
pub fn rwilcox<N1: Into<Natural64>, N2: Into<Natural64>, R: RNG>(
    m: N1,
    n: N2,
    rng: &mut R,
) -> Real64 {
    let mut m = m.into().unwrap();
    let mut n = n.into().unwrap();

    let mut i = 0;
    let mut j = 0;
    let mut k = 0;
    let mut r = 0.0;

    m = m.round();
    n = n.round();

    r = 0.0;
    k = (m + n) as usize;
    let mut x = vec![0; k];
    i = 0;
    while i < k {
        x[i] = i;
        i += 1
    }
    i = 0;
    while (i as f64) < n {
        j = rng.unif_index(k as f64) as usize;
        r += x[j] as f64;
        k -= 1;
        x[j] = x[k];
        i += 1
    }
    (r - n * (n - 1.0) / 2.0).into()
}