1

Given the following variables divisor_array, low, high define a method that

  1. Prints all numbers from low to high
  2. If the any number being printed is divisible by any divisor number in divisor_array, print the number + the word "fizzy"
  3. If the number being printed is divisible by ALL the numbers in the array, it should output the number + "reallyfizzy".

Testing Values: generally_fizzy([2,3],1,7)

My initial solution:

def generally_fizzy(divisor_array, low, high)
    divisors = Hash[*divisor_array]
    low.upto(high) do |i|
        divisors.each_pair do |k,v|
            if((i % k == 0) && (i % v == 0))
                puts "#{i} reallyfizzy"
            elsif ((i % k == 0) || (i % v == 0))
                puts "#{i} fizzy" 
            else
                puts i 
            end          
        end
    end
end

this solution passes the tests given, but when the divisor_array size is increased from 2 values to 3 and over it prints out duplicates. In addition to that, the code is not very elegant.

Looking for a working alternative, that can deal with divisor_array size changes.

4

2 回答 2

5

只需计算数组中有多少除数将除以该值。我们关心三种情况:

  • 他们全部
  • 至少其中一个
  • 他们都没有。
def fizzy(divisors, lo, hi)
  lo.upto(hi) do |value|
    puts case divisors.count{ |div| value % div == 0 }
         when divisors.length      # all divisors
           "#{value} really fizzy"
         when 0                    # no divisors
           value
         else                      # at least one divisor
           "#{value} fizzy"
         end
  end
end
于 2014-01-20T16:22:02.777 回答
1

这是一个有点修改的答案。它使用方法的一个退出点,我发现它更具可读性和健壮性(如果性能是一个问题,可以优化)。

def fizzy(divisors, low, high)
  low.upto(high) do |value|
    print "#{value} "
    print "really" unless divisors.detect{ |div| value % div != 0}
    print "fizzy" if divisors.detect{ |div| value % div == 0}
    print "\n"
  end
end

fizzy([2,3],1,7) #=>
1 
2 fizzy
3 fizzy
4 fizzy
5 
6 reallyfizzy
7 
于 2014-01-20T17:38:57.913 回答