This is a product I made long time ago, it's only implemented for 0, 1 and 2 arguments and it works like the RGSS3's product.
class Array
#--------------------------------------------------------------------------
# product
#--------------------------------------------------------------------------
# [1,2,3].product([4,5]) #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
#
# [1,2].product([3,4],[5,6]) #=>[[1,3,5],[1,3,6],[1,4,5],[1,4,6],
# # [2,3,5],[2,3,6],[2,4,5],[2,4,6]]
#--------------------------------------------------------------------------
def product_2(array)
a = result = []
if array.is_a?(Numeric)
for i in 0...self.length
result[i] = self[i] * array
end
return result
end
return [] if array.length == 0
if array.length == 1
for i in 0...self.length
result[i] = self[i] * array[0]
end
return result
end
for i in 0..self.length-1
a = [self[i],array].flatten
result += a.combination(array.length)
result.pop
end
return result
end
def product(*args)
result = []
if args.length == 0
self.map! {|item| item.to_a }
return self
end
if args.length == 1
return self.product_2(*args)
end
if args.length == 2
resprev = self.product_2(args[0])
for i in 0..resprev.length-1
for j in 0..args[1].length-1
result.push resprev[i]+args[1][j].to_a
end
end
return result
end
raise "args.length > 2 not implemented"
end
#--------------------------------------------------------------------------
# powerset
#--------------------------------------------------------------------------
# x = [1, 2, 3]
# y = x.powerset #=> [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
#--------------------------------------------------------------------------
def powerset
num = 2**size
ps = Array.new(num, [])
self.each_index do |i|
a = 2**i
b = 2**(i+1) - 1
j = 0
while j < num-1
for j in j+a..j+b
ps[j] += [self[i]]
end
j += 1
end
end
ps
end
#--------------------------------------------------------------------------
# combination
#--------------------------------------------------------------------------
# x = [1, 2, 3]
# y = x.combination(1) #=> [[1], [2], [3]]
# y = x.combination(2) #=> [[1,2], [1,3], [2,3]]
# y = x.combination(3) #=> [[1,2,3]]
#--------------------------------------------------------------------------
def combination(n)
result = []
power = self.powerset
return if n > power.length
return [[]] if n == 0
for i in 0..power.length
if power[i].to_a.length == n
result.push power[i]
end
end
return result
end
#--------------------------------------------------------------------------
# num_prod
#--------------------------------------------------------------------------
# [1,2,3,4].num_prod #=> 24
#--------------------------------------------------------------------------
def num_prod
n = 1
each {|num| n *= num}
return n
end
end
Maybe other methods will be incompatible with RGSS3 / XPA... sort_by for example.