SML循环生成随机数、统计频率并排序技术求助
完整实现代码
(* 初始化随机数生成器,传入两个整数种子可控制随机序列(替换值可生成不同结果) *) val r = Random.rand(123, 456); val nextInt = Random.randRange(1, 50); (* 1. 生成包含10个(1-50随机数, 初始频率1)元组的输入列表 *) val inputList = List.tabulate(10, fn _ => (nextInt r, 1)); (* 2. 统计每个随机数的出现频率 *) fun countFrequencies [] = [] | countFrequencies ((num, freq)::remaining) = let (* 辅助函数:更新结果列表中的频率项 *) fun update [] = [(num, freq)] | update ((currNum, currFreq)::rest) = if currNum = num then (currNum, currFreq + freq)::rest else (currNum, currFreq)::update rest in update (countFrequencies remaining) end val frequencyList = countFrequencies inputList; (* 3. 按随机数升序排序频率列表 *) val sortedFrequencyList = List.sort (fn ((x,_), (y,_)) => Int.compare(x, y)) frequencyList;
分步说明
1. 生成随机元组列表
- 用
Random.rand(seed1, seed2)初始化随机数生成器,两个整数种子可确保随机序列可复现; nextInt绑定生成1-50范围内随机整数的函数;List.tabulate(10, fn _ => (nextInt r, 1))会调用匿名函数10次,每次生成一个(随机数, 1)元组,最终组成长度为10的输入列表。
2. 统计频率
- 递归函数
countFrequencies遍历输入列表,通过辅助函数update维护结果列表:- 若当前随机数已在结果列表中,累加对应项的频率;
- 若未出现,则将当前
(随机数, 1)元组加入结果列表。
3. 升序排序
- 使用
List.sort结合自定义比较函数fn ((x,_), (y,_)) => Int.compare(x, y),仅比较元组的第一个元素(随机数),实现按随机数升序排列整个频率列表。
示例输出
运行代码后可能得到类似结果:
> val r = <rand>: Random.rand; > val nextInt = fn: Random.rand -> int; > val inputList = [(42,1),(17,1),(42,1),(3,1),(17,1),(9,1),(3,1),(3,1),(22,1),(42,1)]: (int * int) list; > val countFrequencies = fn: (int * int) list -> (int * int) list; > val frequencyList = [(42,3),(17,2),(3,3),(9,1),(22,1)]: (int * int) list; > val sortedFrequencyList = [(3,3),(9,1),(17,2),(22,1),(42,3)]: (int * int) list;
内容的提问来源于stack exchange,提问作者Em S
相关产品推荐
相关产品推荐

