Extract 2D sub-array (without using Matrix) - ruby

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]]

Related

Is there an algorithm to find all the combinations of addends for a sum, from a given range of addends which are greater than 1?

I'm trying to create a program that takes a given sum and a given range of allowed addends and outputs the unique configurations of those addends which add up to the sum.
The use case is determining the possible combinations of different-sized multi-member districts to divide the members of a legislature into.
In a trivial example, given 15 legislators, and districts of minimum 3 and maximum 5 seats per district, the possible combinations are:
[3, 3, 3, 3, 3]
[4, 4, 4, 3]
[5, 4, 3, 3]
[5, 5, 5]
My initial thought was to start with the largest group of minimum-sized districts possible in a nested array, and add more entries by copying and modifying the previous entry. I don't know how to implement that approach, but I'm also not sure if it's even the right approach to this problem and I'm looking for suggestions.
def multi_member_districts
reps = 19
min = 3
max = 6
quomin, modmin = reps.divmod(min)
quomax, modmax = reps.divmod(max)
groups = Array.new(1) {Array.new}
(quomin - 1).times do groups[0].push(min) end
groups[0].unshift(min + modmin)
# PSEUDOCODE
# copy groups[i], insert copy at groups[i+1]
# remove the smallest element of groups[i+1] and spread it out across the other
# numbers in groups[i+1] in all configurations in which no element exceeds max
# check that there are no duplicate configurations
# repeat
puts "\nThe possible groups of districts are as follows:"
groups.each_index do |i|
(min..max).each do |j|
unless groups[i].count(j) == 0
puts ">> #{groups[i].count(j)} #{j}-member districts"
end
end
puts
puts "o-o-o-o-o-o-o-o-o-o-o-o-o-o"
end
end
multi_member_districts
EDIT_1:
A less trivial example, 19 legislators, 3-6 seats per district --
[4, 3, 3, 3, 3, 3]
[4, 4, 4, 4, 3]
[5, 5, 5, 4]
[5, 4, 4, 3, 3]
[5, 5, 3, 3, 3]
[6, 5, 5, 3]
[6, 4, 3, 3, 3]
[6, 5, 4, 4]
[6, 6, 4, 3]
EDIT_2: Clarified my question, cut down the code, hopefully more suitable
Let's first compute the combinations where each combination corresponds to an array arr where arr[i] equals the number of legislators assigned to district i. If, for example, there are 15 legislators and there must be between 3 and 5 assigned to each district, [3,3,4,5] and [5,3,4,3] would be distinct combinations. We can solve that problem using recursion.
def doit(nbr, rng)
return nil if nbr < rng.begin
recurse(nbr, rng)
end
def recurse(nbr, rng)
(rng.begin..[rng.end, nbr].min).each_with_object([]) do |n,arr|
if n == nbr
arr << [n]
elsif nbr-n >= rng.begin
recurse(nbr-n, rng).each { |a| arr << a.unshift(n) }
end
end
end
doit(15, 3..5)
#=> [[3, 3, 3, 3, 3], [3, 3, 4, 5], [3, 3, 5, 4], [3, 4, 3, 5],
# [3, 4, 4, 4], [3, 4, 5, 3], [3, 5, 3, 4], [3, 5, 4, 3], [4, 3, 3, 5],
# [4, 3, 4, 4], [4, 3, 5, 3], [4, 4, 3, 4], [4, 4, 4, 3], [4, 5, 3, 3],
# [5, 3, 3, 4], [5, 3, 4, 3], [5, 4, 3, 3], [5, 5, 5]]
doit(19, 3..6)
#=> [[3, 3, 3, 3, 3, 4], [3, 3, 3, 3, 4, 3], [3, 3, 3, 4, 3, 3],
# [3, 3, 3, 4, 6], [3, 3, 3, 5, 5], [3, 3, 3, 6, 4], [3, 3, 4, 3, 3, 3],
# ...
# [6, 5, 3, 5], [6, 5, 4, 4], [6, 5, 5, 3], [6, 6, 3, 4], [6, 6, 4, 3]]
doit(19, 3..6).size
#=> 111
The question is not concerned, however, with allocations to specific districts. To obtain the combinations of interest we may therefore write the following.
require 'set'
def really_doit(nbr, rng)
doit(nbr, rng).map(&:tally).uniq.map do |h|
h.flat_map { |k,v| [k]*v }.sort.reverse
end
end
really_doit(15, 3..5)
#=> [[3, 3, 3, 3, 3], [5, 4, 3, 3], [4, 4, 4, 3], [5, 5, 5]]
really_doit(19, 3..6)
#=> [[4, 3, 3, 3, 3, 3], [6, 4, 3, 3, 3], [5, 5, 3, 3, 3],
# [5, 4, 4, 3, 3], [4, 4, 4, 4, 3], [6, 6, 4, 3], [6, 5, 5, 3],
# [6, 5, 4, 4], [5, 5, 5, 4]]
Enumerable#tally made its debut in Ruby v2.7. To support earlier versions replace map(&:tally) with map { |a| a.each_with_object(Hash.new(0)) { |n,h| h[n] += 1 }.
Note that doit(nbr, rng).map(&:tally).uniq in returns
[{3=>5}, {3=>2, 4=>1, 5=>1}, {3=>1, 4=>3}, {5=>3}]
in really_doit(15, 3..5) and
[{3=>5, 4=>1}, {3=>3, 4=>1, 6=>1}, {3=>3, 5=>2}, {3=>2, 4=>2, 5=>1},
{3=>1, 4=>4}, {3=>1, 4=>1, 6=>2}, {3=>1, 5=>2, 6=>1}, {4=>2, 5=>1, 6=>1},
{4=>1, 5=>3}]
in really_doit(19, 3..6).
We can improve on this by constructing sets of hashes (rather than arrays of arrays) in recurse:
require 'set'
def doit(nbr, rng)
return nil if nbr < rng.begin
recurse(nbr, rng).map { |h| h.flat_map { |k,v| [k]*v }.sort.reverse }
end
def recurse(nbr, rng)
(rng.begin..[rng.end, nbr].min).each_with_object(Set.new) do |n,st|
if n == nbr
st << { n=>1 }
elsif nbr-n >= rng.begin
recurse(nbr-n, rng).each { |h| st << h.merge(n=>h[n].to_i+1 ) }
end
end
end
doit(15, 3..5)
#=> [[3, 3, 3, 3, 3], [5, 4, 3, 3], [4, 4, 4, 3], [5, 5, 5]]
doit(19, 3..6)
#=> [[4, 3, 3, 3, 3, 3], [6, 4, 3, 3, 3], [5, 5, 3, 3, 3],
# [5, 4, 4, 3, 3], [4, 4, 4, 4, 3], [6, 6, 4, 3], [6, 5, 5, 3],
# [6, 5, 4, 4], [5, 5, 5, 4]]
Note that here recurse(nbr, rng) in doit returns:
#<Set: {{3=>5}, {5=>1, 4=>1, 3=>2}, {4=>3, 3=>1}, {5=>3}}>
When executing doit(19, 3..6) recurse(nbr, rng) in doit returns:
#<Set: {{4=>1, 3=>5}, {6=>1, 4=>1, 3=>3}, {5=>2, 3=>3},
# {5=>1, 4=>2, 3=>2}, {4=>4, 3=>1}, {6=>2, 4=>1, 3=>1},
# {6=>1, 5=>2, 3=>1}, {6=>1, 5=>1, 4=>2}, {5=>3, 4=>1}}>

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.

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 combine multiple arrays of the same size in ruby

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]]

Nested Array Initialization && Assignment Oddity [duplicate]

This question already has an answer here:
Ruby Array Initialization [duplicate]
(1 answer)
Closed 3 years ago.
What is going on in the Array initialization that's causing the disparity in int assignment?
arr = Array.new(3) { Array.new(3) { Array.new(3) } }
3.times do |x|
3.times do |y|
3.times do |z|
arr[x][y][z] = Random.rand(1..9)
end
end
end
puts arr.to_s
#=> [[[3, 3, 1], [4, 9, 6], [2, 4, 7]], [[1, 6, 8], [9, 8, 5], [1, 7, 5]], [[2, 5, 9], [2, 8, 8], [9, 1, 8]]]
#=> [[[2, 4, 4], [6, 8, 9], [6, 2, 7]], [[2, 7, 7], [2, 1, 1], [8, 7, 7]], [[5, 3, 5], [3, 8, 1], [7, 6, 6]]]
#=> [[[4, 9, 1], [1, 6, 8], [9, 2, 5]], [[3, 7, 1], [7, 5, 4], [9, 9, 9]], [[6, 8, 2], [8, 2, 8], [2, 9, 9]]]
arr = Array.new(3, Array.new(3, Array.new(3)))
3.times do |x|
3.times do |y|
3.times do |z|
arr[x][y][z] = Random.rand(1..9)
end
end
end
puts arr.to_s
#=> [[[8, 2, 4], [8, 2, 4], [8, 2, 4]], [[8, 2, 4], [8, 2, 4], [8, 2, 4]], [[8, 2, 4], [8, 2, 4], [8, 2, 4]]]
#=> [[[2, 1, 4], [2, 1, 4], [2, 1, 4]], [[2, 1, 4], [2, 1, 4], [2, 1, 4]], [[2, 1, 4], [2, 1, 4], [2, 1, 4]]]
#=> [[[2, 7, 6], [2, 7, 6], [2, 7, 6]], [[2, 7, 6], [2, 7, 6], [2, 7, 6]], [[2, 7, 6], [2, 7, 6], [2, 7, 6]]]
When you use new(size=0, obj=nil) to initialize the array:
From the doc:
In the first form, if no arguments are sent, the new array will be
empty. When a size and an optional obj are sent, an array is created
with size copies of obj. Take notice that all elements will reference
the same object obj.
If you want multiple copy, then you should use the block version which uses the result of that block each time an element of the array needs to be initialized.

Resources