Sum arrays by index using functional programming - ruby

I have several equally sized arrays containing numbers (matrix), and I want to sum them all by their index (matrix columns).
For example, if I have:
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
I want to get the result:
column_totals = [6, 8, 10, 12]
I understand how to do this imperatively, but how would I do this using functional programming? (Preferably, using built in Enumerable methods.) I wasn't very happy with any of the functional solutions I came up with.
I ended up using the Matrix class:
require 'matrix'
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
matrix = Matrix[*data]
# Added sum method to Vector class.
matrix.column_vectors.map { |column| column.sum }
I'm happy enough with that solution, but am frustrated that I couldn't wrap my mind around a good functional solution without relying on the Matrix class.
Specifically, I was tripped up on the step to transform this:
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
into this:
columns = [[1, 5], [2, 6], [3, 7], [4, 8]]

Any reason to not use Array#transpose?
data.transpose
# => [[1, 5], [2, 6], [3, 7], [4, 8]]
Alternatively, if you only want to use Enumerable methods to iterate, you can do
columns = data.inject(Array.new(data.first.length){[]}) { |matrix,row|
row.each_with_index { |e,i| matrix[i] << e }
matrix }
# => [[1, 5], [2, 6], [3, 7], [4, 8]]
or
columns = data.flatten.group_by.with_index { |e,i| i % data[0].size }.values
# => [[1, 5], [2, 6], [3, 7], [4, 8]]
To sum:
columns.map { |row| row.inject :+ }
# => [6, 8, 10, 12]
Thirdly, if you don't need the intermediate columns:
data.inject { |s,r| s.zip(r).map { |p| p.inject :+ } }
# => [6, 8, 10, 12]

You could use Array#transpose, as #Matt hinted, and then sum the arrays inside:
data.transpose.map {|a| a.reduce(:+) }

Related

How to get 'fair combination' from an array of n elements?

Using combination method on Ruby,
[1, 2, 3, 4, 5, 6].combination(2).to_a
#=> [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 3],
# [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6],
# [4, 5], [4, 6], [5, 6]]
we can get a 2-dimensional array having 15 (6C2) elements.
I would like to create a fair_combination method that returns an array like this:
arr = [[1, 2], [3, 5], [4, 6],
[3, 4], [5, 1], [6, 2],
[5, 6], [1, 3], [2, 4],
[2, 3], [4, 5], [6, 1],
[1, 4], [2, 5], [3, 6]]
So that every three sub-arrays (half of 6) contain all the given elements:
arr.each_slice(3).map { |a| a.flatten.sort }
#=> [[1, 2, 3, 4, 5, 6],
# [1, 2, 3, 4, 5, 6],
# [1, 2, 3, 4, 5, 6],
# [1, 2, 3, 4, 5, 6],
# [1, 2, 3, 4, 5, 6]]
This makes it kind of "fair", by using as different elements as possible as arrays go on.
To make it more general, what it needs to satisfy is as follows:
(1) As you follow the arrays from start and count how many times each number appears, at any point it should be as flat as possible;
(1..7).to_a.fair_combination(3)
#=> [[1, 2, 3], [4, 5, 6], [7, 1, 4], [2, 5, 3], [6, 7, 2], ...]
The first 7 numbers make [1,2,...,7] and so do the following 7 numbers.
(2) Once number A comes in the same array with B, A does not want to be in the same array with B if possible.
(1..10).to_a.fair_combination(4)
#=> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 1, 5], [2, 6, 9, 3], [4, 7, 10, 8], ...]
Is there any good algorithm that creates a "fair combination" like this ?
It's not guaranteed to give the best solution, but it gives a good enough one.
At each step, it chooses a minimal subpool which is the set of items of minimal height, for which there is still a combination to choose from (height is the number of times the items have been used before).
For instance, let the enumerator be
my_enum = FairPermuter.new('abcdef'.chars, 4).each
The first iteration may return
my_enum.next # => ['a', 'b', 'c', 'd']
At this point those letters have height 1, but there is not enough letters of height 0 to make a combination, so take just all of them for the next:
my_enum.next # => ['a', 'b', 'c', 'e'] for instance
Now the heights are 2 for a, b and c, 1 for d and e, and 0 for f, and still the optimal pool is the full initial set.
So this is not really optimized for combinations of large size. On the other side, if the size of the combination is at most half of the size of the initial set, then the algorithm is pretty decent.
class FairPermuter
def initialize(pool, size)
#pool = pool
#size = size
#all = Array(pool).combination(size)
#used = []
#counts = Hash.new(0)
#max_count = 0
end
def find_valid_combination
[*0..#max_count].each do |height|
candidates = #pool.select { |item| #counts[item] <= height }
next if candidates.size < #size
cand_comb = [*candidates.combination(#size)] - #used
comb = cand_comb.sample
return comb if comb
end
nil
end
def each
return enum_for(:each) unless block_given?
while combination = find_valid_combination
#used << combination
combination.each { |k| #counts[k] += 1 }
#max_count = #counts.values.max
yield combination
return if #used.size >= [*1..#pool.size].inject(1, :*)
end
end
end
Results for fair combinations of 4 over 6
[[1, 2, 4, 6], [3, 4, 5, 6], [1, 2, 3, 5],
[2, 4, 5, 6], [2, 3, 5, 6], [1, 3, 5, 6],
[1, 2, 3, 4], [1, 3, 4, 6], [1, 2, 4, 5],
[1, 2, 3, 6], [2, 3, 4, 6], [1, 2, 5, 6],
[1, 3, 4, 5], [1, 4, 5, 6], [2, 3, 4, 5]]
Results of fair combination of 2 over 6
[[4, 6], [1, 3], [2, 5],
[3, 5], [1, 4], [2, 6],
[4, 5], [3, 6], [1, 2],
[2, 3], [5, 6], [1, 6],
[3, 4], [1, 5], [2, 4]]
Results of fair combinations of 2 over 5
[[4, 5], [2, 3], [3, 5],
[1, 2], [1, 4], [1, 5],
[2, 4], [3, 4], [1, 3],
[2, 5]]
Time to get combinations of 5 over 12:
1.19 real 1.15 user 0.03 sys
Naïve implementation would be:
class Integer
# naïve factorial implementation; no checks
def !
(1..self).inject(:*)
end
end
class Range
# constant Proc instance for tests; not needed
C_N_R = -> (n, r) { n.! / ( r.! * (n - r).! ) }
def fair_combination(n)
to_a.permutation
.map { |a| a.each_slice(n).to_a }
.each_with_object([]) do |e, memo|
e.map!(&:sort)
memo << e if memo.all? { |me| (me & e).empty? }
end
end
end
▶ (1..6).fair_combination(2)
#⇒ [
# [[1, 2], [3, 4], [5, 6]],
# [[1, 3], [2, 5], [4, 6]],
# [[1, 4], [2, 6], [3, 5]],
# [[1, 5], [2, 4], [3, 6]],
# [[1, 6], [2, 3], [4, 5]]]
▶ (1..6).fair_combination(3)
#⇒ [
# [[1, 2, 3], [4, 5, 6]],
# [[1, 2, 4], [3, 5, 6]],
# [[1, 2, 5], [3, 4, 6]],
# [[1, 2, 6], [3, 4, 5]],
# [[1, 3, 4], [2, 5, 6]],
# [[1, 3, 5], [2, 4, 6]],
# [[1, 3, 6], [2, 4, 5]],
# [[1, 4, 5], [2, 3, 6]],
# [[1, 4, 6], [2, 3, 5]],
# [[1, 5, 6], [2, 3, 4]]]
▶ Range::C_N_R[6, 3]
#⇒ 20
Frankly, I do not understand how this function should behave for 10 and 4, but anyway this implementation is too memory consuming to work properly on big ranges (on my machine it gets stuck on ranges of size > 8.)
To adjust this to more robust solution one needs to get rid of permutation there in favor of “smart concatenate permuted arrays.”
Hope this is good for starters.

How to access a nested element, passing array with coordinates

Is there any short way to access an element of a nested array, passing the array with coordinates? I mean something like:
matrix = [[1,2,3,4],[5,6,7,8]]
array = [1,1]
matrix [array]
# => 6
I just wonder if there is a shorter version than:
matrix [array[0]][array[1]]
I believe you want to use the Matrix class:
require 'matrix'
arr = [[1,2,3,4],[5,6,7,8]]
matrix = Matrix[*arr] #=> Matrix[[1, 2, 3, 4], [5, 6, 7, 8]]
matrix[1,1] #=> 6
matrix.row(1) #=> Vector[5, 6, 7, 8]
c = matrix.column(1) #=> Vector[2, 6]
c.to_a #=> [2, 6]
m = matrix.transpose #=> Matrix[[1, 5], [2, 6], [3, 7], [4, 8]]
m.to_a #=> [[1, 5], [2, 6], [3, 7], [4, 8]]
array.inject(matrix, :fetch)
# => 6
matrix[1][1]
should equal 6. matrix[1] is the 2nd array, matrix[1][1] is the second element in that array.

Merge array values to form a new array based on Index using Ruby [duplicate]

If I have 3 or more arrays I want to combine into one, how do I do that in ruby? Would it be a variation on zip?
For example, I have
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
and I would like to have an array that looks like
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[a,b,c].transpose
is all you need. I prefer this to zip 50% of the time.
I would use Array#zip as below:
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
a.zip(b, c)
#=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

How to perform function to subarray inside ruby multidimensional array

I have a multidimensional array in ruby like this one:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
How do I add "1" to each element. For instance, I want to end up with something like this:
a = [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
Thanks in advance!
There might be a slightly more clever one liner but this is fairly clear.
a.map { |ar| ar.map { |e| e + 1 } }
Just for fun :
class Array
def increment
map(&:next)
end
end
#Tada!
a.map(&:increment)
a.map { |xs| xs.map(&:succ) }
#=> [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Extract 2D sub-array (without using Matrix)

In Ruby, given an array-of-arrays representing a 2D grid of numbers, how would you extract a specific sub-2D array?
a = [[0, 3, 1, 5, 5],
[4, 6, 8, 3, 5],
[7, 1, 4, 0, 8],
[0, 8, 8, 7, 4],
[7, 2, 4, 5, 4]]
require 'pp'
pp sub_array(a,1..4,2..4)
#=> [[8, 3, 5],
#=> [4, 0, 8],
#=> [8, 7, 4],
#=> [4, 5, 4]]
This is 'easy' to do using the Matrix library:
m = Matrix[*a]
p m.minor(1..4,2..4).to_a
#=> [[8, 3, 5], [4, 0, 8], [8, 7, 4], [4, 5, 4]]
However, I feel certain that there's an elegant way to do this without using the Matrix, perhaps involving zip or transpose :)
I'm including the words "two-dimensional" here for search hits.
def sub_array(xs, rows, columns)
xs[rows].map { |row| row[columns] }
end
sub_array(a, 1..4, 2..4)
#=> [[8, 3, 5], [4, 0, 8], [8, 7, 4], [4, 5, 4]]

Resources