如何推进多个枚举器,或者“但是 FizzBu​​zzBoozz 呢?”

发布于 2024-10-02 08:51:21 字数 524 浏览 2 评论 0原文

这是进行经典 FizzBu​​zz 练习的一种相当非正统的方法,但这只是为了说明问题(嘿,如果你想达到十亿,它可能会很快)。

fizzer = ( Array.new( 2, '' ) << 'Fizz' ).cycle
buzzer = ( Array.new( 4, '' ) << 'Buzz' ).cycle

(1..100).each do |number|
  fizzbuzz = fizzer.next + buzzer.next # this line is giving me problems.
  puts ( fizzbuzz.empty? ? number : fizzbuzz )
end

如何概括此代码以接受类似 {3 =>; 的哈希值'嘶嘶', 5 => '嗡嗡', 7 => ‘嘘’}?

This is a rather unorthodox way to do the classic FizzBuzz exercise, but it's just to illustrate the problem (and hey, it might be fast if you want to fizzbuzz to a billion).

fizzer = ( Array.new( 2, '' ) << 'Fizz' ).cycle
buzzer = ( Array.new( 4, '' ) << 'Buzz' ).cycle

(1..100).each do |number|
  fizzbuzz = fizzer.next + buzzer.next # this line is giving me problems.
  puts ( fizzbuzz.empty? ? number : fizzbuzz )
end

How to generalize this code to accept a hash like {3 => 'Fizz', 5 => 'Buzz', 7 => 'Boozz'} ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

止于盛夏 2024-10-09 08:51:21

创建 Fizzers、Buzzers 和 Boozzer 数组。然后在循环中对该数组中的每个 fooer 调用 next ,然后使用 inject 将结果相加:

# The sort is needed so it prints fizzbuzz, not buzzfizz
# (hashes being unordered and all)
fooers = the_hash.sort_by {|k,v| k}.map do |k,v|
  ( Array.new(k - 1, '') << v ).cycle
end

(1..100).each do |number|
  fizzbuzz = fooers.map(&:next).inject(:+)
  puts ( fizzbuzz.empty? ? number : fizzbuzz )
end

Create an array of Fizzers, Buzzers, and Boozzers. Then in the loop call next on each fooer in that array and then sum the results with inject:

# The sort is needed so it prints fizzbuzz, not buzzfizz
# (hashes being unordered and all)
fooers = the_hash.sort_by {|k,v| k}.map do |k,v|
  ( Array.new(k - 1, '') << v ).cycle
end

(1..100).each do |number|
  fizzbuzz = fooers.map(&:next).inject(:+)
  puts ( fizzbuzz.empty? ? number : fizzbuzz )
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文