FizzBuzz Explained

FizzBuzz Explained

FizzBuzz is a classic programming challenge often used in coding interviews to test basic logic and looping skills. The task is simple:

  1. Print numbers from 1 to N.
  2. If a number is divisible by 3, print "Fizz" instead of the number.
  3. If a number is divisible by 5, print "Buzz".
  4. If a number is divisible by both 3 and 5, print "FizzBuzz".
  5. Otherwise, print the number itself.

FizzBuzz in Ruby

Here’s a simple Ruby implementation:

#!/usr/bin/env ruby

require "minitest/autorun"

class Array
  @exam = false
  def exam n
    @flatten = self.flatten
    @combination = @flatten.combination(2).to_a

    @combination.each { |slice| @exam = @exam || (slice[0].to_i + slice[1].to_i == n.to_i) }
    @exam
  end
end        

Spec:

class TestExam < Minitest::Test
  def original
    @original = [[30, 501, [22]], 4, [38, 2]]
    assert_equal true, @original.exam(531)
  end
  def test_22
    @by_test = [1, [[20],[[43],[[10], [99]]], [5],[6]]]
    assert_equal false, @by_test.exam(22)
  end
  def test_21
    @by_test = [1, [[20],[[43],[[10], [99]]], [5],[6]]]
    assert_equal true, @by_test.exam(21)
  end
  def test_104
    @by_test = [1, [[20],[[43],[[10], [99]]], [5],[6]]]
    assert_equal true, @by_test.exam(104)
  end
  def test_111
    @by_test = [1, [[20],[[43],[[10], [99]]], [5],[6]]]
    assert_equal false, @by_test.exam(111)
  end
end        


要查看或添加评论,请登录

Germán Silva的更多文章

社区洞察

其他会员也浏览了