r2rs-nmath 0.1.1

Statistics programming for Rust based on R's nmath package
Documentation
// Translation of nmath's csignrank
//
// 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 std::{cell::RefCell, thread_local};

thread_local! {
    static W: RefCell<Vec<f64>> = RefCell::new(Vec::new());
}

pub fn reset_signrank_static() {
    W.with(|W_| *W_.borrow_mut() = Vec::new());
}

pub fn csignrank(mut k: i32, n: i32) -> f64 {
    let mut c = 0;
    let mut u = 0;
    let mut j = 0;

    u = (n * (n + 1) / 2) as usize;
    c = u / 2;

    if k < 0 || k as usize > u {
        return 0.0;
    }
    if k > c as i32 {
        k = u as i32 - k
    }

    if n == 1 {
        return 1.0;
    }
    W.with(|W_| {
        let mut w = W_.borrow_mut();
        if w.len() != u {
            w.clear();
            w.resize(u, 0.0);
        }

        if w[0] == 1.0 {
            return w[k as usize];
        }

        let ref mut fresh0 = w[1];
        *fresh0 = 1.0;
        w[0] = *fresh0;

        j = 2;
        while j < n + 1 {
            let mut i = 0;
            let end = (j * (j + 1) / 2).min(c as i32);
            i = end as usize;
            while i >= j as usize {
                w[i] += w[i - j as usize];
                i -= 1
            }
            j += 1
        }
        return w[k as usize];
    })
}