gpt4 book ai didi

ruby - 在 Ruby 中生成数字序列

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

我正在做旧试卷中的这道题,以复习我的 ruby​​ 编程技能。我在第 2 部分遇到了一些问题。Seq_gen_b -> 使用递归 生成序列。以下是问题本身。

基本上,它要求生成一个数字序列,方法是输入一个值 n,将其乘以 2,然后减去 3。然后使用这个新数字生成下一个数字。这些数字将存储在一个数组中。我的问题是我想不出停止递归发生的好方法。

Create two methods – seq_gen_a and seq_gen_b -- each of which will take a number, n (which is > 2), and generate an array of four elements, whose first element is n and next three elements are three numbers in a sequence that doubles the previous number and takes 3 from it; such that, (i) seq_gen_a generates the sequence using iteration, and (ii) seq_gen_b generates the sequence using recursion. For example, given the number 5, both of these methods will output: [5, 7, 11, 19] though, obviously, they will achieve this output in different ways

这是我目前所拥有的,但我无法弄清楚如何阻止它刚刚耗尽内存。这可能是完全错误的

def seq_gen_b(n)
if n < 2
n
else
(0..2).each do |i|
num = ((n * 2) -3)
seq_gen_b(num)
end
end
end

非常感谢任何帮助并提前致谢

最佳答案

我个人认为这两种设计都不是很好。生成序列和选择从中提取多少元素是两个截然不同的问题,不应该在一个方法中混为一谈。

为了生成一个序列,Ruby 已经有了 Enumerator 类:

n = 5
e = Enumerator.new do |y| loop do y << n; n = 2*n - 3 end end
e.next # => 5
e.next # => 7
e.next # => 11
e.next # => 19

我会将这两个不同的关注点拆分为两种不同的方法,一种返回生成器,另一种选择获取多少元素。 Enumerator 混合在 Enumerable 中,因此我们也可以使用所有这些方法,包括 take。这意味着我们已经为我们编写了选择要获取多少元素的方法。多好! (当您使用适当的抽象时,就会发生这种情况。)

def seq_gen(n) Enumerator.new do |y| loop do y << n; n = 2*n - 3 end end end

def seq_5_take_4; seq_gen(5).take(4) end

seq_5_take_4
# => [5, 7, 11, 19]

关于ruby - 在 Ruby 中生成数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27530098/

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