The following code produces totally unexpected/undesired behavior.
Is it a bug?
The following method adds the prime factors of two numbers which are in
the
form [prime,exponent]. It performs the operation correctly but for some
reason it changes the elements of the first array, when I would expect
it to have no effect on the input arrays.
-
Is this correct or a bug (it occurs in all Ruby version <= 2.3.1)?
-
If this is not a bug, how do I write this so as not to change the
input arrays?
def product_factors(a,b)
factors = (a + b).sort!
prod_factors = []
until factors.empty?
factor = factors.shift
factor[1] += factors.shift[1] if !factors.empty? && factor[0] ==
factors.first[0]
prod_factors << factor
end
prod_factors
end
a = [[2, 1], [3, 1], [5, 2], [7, 2], [11, 2], [41, 1], [271, 1], [9091,
1]]
b = [[2, 5], [3, 2], [5, 2], [7, 3], [11, 2], [13, 2], [37, 1], [41, 1]]
product_factors a, b
=> [[2, 6], [3, 3], [5, 4], [7, 5], [11, 4], [13, 2], [37, 1], [41, 2],
[271, 1], [9091, 1]]
a
=> [[2, 6], [3, 3], [5, 4], [7, 5], [11, 4], [41, 2], [271, 1], [9091,
1]]
b
=> [[2, 5], [3, 2], [5, 2], [7, 3], [11, 2], [13, 2], [37, 1], [41, 1]]