Files
rand-cli/README.md
T

113 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# rand
一个快速、可组合的命令行随机数生成器,支持 6 种概率分布,原生管道语法。
## 安装
```bash
# 源码运行
bun install
bun run index.ts
# 构建独立二进制
bun run build # → dist/rand
sudo cp dist/rand /usr/local/bin/
```
## 快速开始
```bash
rand # 0100 的随机整数
rand 50 # 050
rand 10 20 # 1020
rand -c 5 # 生成 5 个数
rand -f2 # 保留 2 位小数
```
## 选项
| 选项 | 说明 |
|------|------|
| `-c, --count <n>` | 生成个数,默认 1 |
| `-f[N]` | 小数位数:`-f` 默认 2 位,`-f1` = 1 位,`-f3` = 3 位 |
| `--float [N]` | `-f` 的长形式 |
| `-d, --dist <name>` | 概率分布,默认 `uniform` |
| `-h, --help` | 帮助信息 |
| `--` | 之后所有参数视为位置参数(用于负数) |
## 概率分布
| 分布 | 命令 | 参数 | 默认值 |
|------|------|------|--------|
| uniform | `rand` | `[min] [max]` | 0, 100 |
| normal | `rand -d normal` | `[μ] [σ]` | 0, 1 |
| binomial | `rand -d binomial` | `[n] [p]` | 10, 0.5 |
| poisson | `rand -d poisson` | `[λ]` | 1 |
| exponential | `rand -d exponential` | `[λ]` | 1 |
| hypergeometric | `rand -d hypergeometric` | `[N] [K] [n]` | 100, 50, 10 |
### 采样算法
| 分布 | 算法 |
|------|------|
| normal | Box-Muller 变换 |
| binomial | Bernoulli 试验求和 |
| poisson | Knuth 算法 |
| exponential | 逆 CDF 变换 |
| hypergeometric | 不放回抽样模拟 |
## 管道
stdout 输出纯数据,stderr 输出诊断信息,天然支持管道组合:
```bash
rand | xargs echo # 管道输出
echo 50 | rand # stdin 提供上限
echo "5 2" | rand -d normal -f1 # stdin 覆盖分布参数
rand -c 100 | sort -n | head -5 # 生成 100 个,取最小的 5 个
```
## 示例
```bash
# 正态分布:均值 100,标准差 15
rand -d normal 100 15 -f1
# 二项分布:20 次试验,成功概率 0.3,生成 5 个样本
rand -d binomial 20 0.3 -c 5
# 泊松分布:λ=3
rand -d poisson 3
# 指数分布:λ=0.5,保留 1 位小数
rand -d exponential 0.5 -f1
# 超几何分布:总体 100,成功 30,抽取 5 次
rand -d hypergeometric 100 30 5
# 负数范围(用 -- 分隔标志和参数)
rand -- -10 -5
rand -d normal -- 0 -1 # stddev 必须 > 0,会报错
```
## 项目结构
```
index.ts # 入口
src/
types.ts # 类型定义与默认值
help.ts # 帮助文本
args.ts # 参数解析与校验
stdin.ts # 管道输入读取
dist.ts # 分布采样器与调度
main.ts # 编排逻辑
```
## 构建
```bash
bun run build # → dist/rand(独立二进制,约 74MB
```
基于 [Bun](https://bun.com) 构建,零外部依赖。