biased 0.1.2

A Rust library for generating biased random numbers, useful for simulations and weighted selections. 一个用于生成偏向性随机数的 Rust 库,适用于模拟和加权选择场景。
Documentation
use std::collections::BTreeMap;

use anyhow::Result;
use biased::biased_random;
use log::info;

#[static_init::constructor(0)]
extern "C" fn _log_init() {
  log_init::init();
}

#[test]
fn test_biased_random_histogram() -> Result<()> {
  const N: u32 = 20; // English: Upper bound | Chinese: 上限
  const BIAS: f64 = 3.0; // English: Bias factor | Chinese: 偏向因子
  const SAMPLES: u32 = 10000; // English: Number of samples | Chinese: 采样次数

  info!(
    "> Generating {} biased random numbers (n={}, bias={})",
    SAMPLES, N, BIAS
  );

  let mut histogram = BTreeMap::new();
  for _ in 0..SAMPLES {
    let num = biased_random(N, BIAS);
    *histogram.entry(num).or_insert(0) += 1;
  }

  // English: Find the maximum frequency to scale the histogram bars
  // Chinese: 找到最大频率用于缩放直ra图的条形
  let max_freq = histogram.values().max().cloned().unwrap_or(0);
  const MAX_BAR_WIDTH: usize = 20;

  info!("> ASCII Histogram of the results:");

  for i in 0..N {
    let freq = histogram.get(&i).cloned().unwrap_or(0);
    let bar_width = if max_freq > 0 {
      (freq as usize * MAX_BAR_WIDTH) / max_freq as usize
    } else {
      0
    };
    let bar: String = "".repeat(bar_width);
    let percentage = (freq as f64 / SAMPLES as f64) * 100.0;
    // English: Use info! to print, as the existing test does.
    // Chinese: 使用 info! 打印,与现有测试保持一致。
    println!("{:>3}: {:<5} ({:>5.2}%) |{}", i, freq, percentage, bar);
  }

  Ok(())
}