gpt4 book ai didi

ruby - 数组中的 NoMemoryError#max

转载 作者:数据小太阳 更新时间:2023-10-29 08:35:34 26 4
gpt4 key购买 nike

我正在研究一个代码战问题来解析一个整数并按降序重新排列它的数字。我的工作解决方案如下;我决定使用字符串方法来快速解析数字(而不是 mods 或 log_10s):

# descending_order : int => int
# Takes an int, re-orders its digits in descending order, and returns that

# ex. descending_order(1234) => 4321

def descending_order(n)
n.to_s.chars.sort.reverse.join.to_i
end

但是,在尝试解决方案时,我还尝试了以下变体,它为相当小的输入抛出了一个 NoMemoryError:

def descending_order(n)
n.to_s.chars.max(n).join.to_i
end

产量:

descending_order(456454576895645)
NoMemoryError: failed to allocate memory
from (pry):129:in `max'

显然,sort 是通过 max(<array_length>) 对数组进行排序的正确方法,但我很好奇为什么 max 在这里占用了这么多内存。是什么导致了这种行为,我是否需要小心处理类似情况(例如,从 100 个整数的数组中取出 max(20))?

最佳答案

记录在案here ,如果给出 n,则返回最大 n 个元素,本质上也是分配大小为 n 的数组,这就是 NoMemoryError 的原因。

关于ruby - 数组中的 NoMemoryError#max,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46617655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com