Ruby: Multiply all elements of an array

前端 未结 4 1534
孤城傲影
孤城傲影 2021-02-19 05:20

Let\'s say I have an array A = [1, 2, 3, 4, 5]

how can I multiply all elements with ruby and get the result? 1*2*3*4*5 = 120

and what if there is an element 0 ?

相关标签:
4条回答
  • 2021-02-19 05:45

    There is also another way to calculate this factorial! Should you want to, you can define whatever your last number is as n.

    In this case, n=5.

    From there, it would go something like this:

    (1..num).inject(:*)
    

    This will give you 120. Also, .reduce() works the same way.

    0 讨论(0)
  • 2021-02-19 05:48

    Well, this is a dummy way but it works :)

    A = [1, 2, 3, 4, 5]
    result = 1
    A.each do |i|
        if i!= 0
            result = result*i
        else
            result
        end
    end
    puts result
    
    0 讨论(0)
  • 2021-02-19 05:50

    This is the textbook case for inject (also called reduce)

    [1, 2, 3, 4, 5].inject(:*)
    

    As suggested below, to avoid a zero,

    [1, 2, 3, 4, 5].reject(&:zero?).inject(:*)
    
    0 讨论(0)
  • 2021-02-19 05:51

    If you want to understand your code later on, use this: Assume A = 5, I used n instead of A

    n = 5
    n.times {|x| unless x == 0; n =  n * x; ++x; end} 
    p n
    

    To carry it forward, you would:

    A = [1,2,3,4,5]
    arb = A.first
    a = A.count
    a.times {|x| arb = arb * A[x]; ++x}
    p arb
    
    0 讨论(0)
提交回复
热议问题