I will address the crux of your problem only, without reference to a class DNA
. It should be easy to reorganize what follows quite easily.
Code
def match_kmers(s1, s2, k)
h1 = dna_to_index(s1, k)
h2 = dna_to_index(s2, k)
h1.flat_map { |k,_| h1[k].product(h2[k] || []) }
end
def dna_to_index(dna, k)
dna.each_char.
with_index.
each_cons(k).
with_object({}) {|arr,h| (h[arr.map(&:first).join] ||= []) << arr.first.last}
end
Examples
dna1 = 'GCCCAC'
dna2 = 'CCACGC'
match_kmers(dna1, dna2, 2)
#=> [[0, 4], [1, 0], [2, 0], [3, 1], [4, 2]]
match_kmers(dna2, dna1, 2)
#=> [[0, 1], [0, 2], [1, 3], [2, 4], [4, 0]]
match_kmers(dna1, dna2, 3)
#=> [[2, 0], [3, 1]]
match_kmers(dna2, dna1, 3)
#=> [[0, 2], [1, 3]]
match_kmers(dna1, dna2, 4)
#=> [[2, 0]]
match_kmers(dna2, dna1, 4)
#=> [[0, 2]]
match_kmers(dna1, dna2, 5)
#=> []
match_kmers(dna2, dna1, 5)
#=> []
match_kmers(dna1, dna2, 6)
#=> []
match_kmers(dna2, dna1, 6)
#=> []
Explanation
Consider dna1 = 'GCCCAC'
. This contains 5 2-mers (k = 2
):
dna1.each_char.each_cons(2).to_a.map(&:join)
#=> ["GC", "CC", "CC", "CA", "AC"]
Similarly, for dna2 = 'CCACGC'
:
dna2.each_char.each_cons(2).to_a.map(&:join)
#=> ["CC", "CA", "AC", "CG", "GC"]
These are the keys of the hashes produced by dna_to_index
for dna1
and dna2
, respectively. The hash values are arrays of indices of where the corresponding key begins in the DNA string. Let's compute those hashes for k = 2
:
h1 = dna_to_index(dna1, 2)
#=> {"GC"=>[0], "CC"=>[1, 2], "CA"=>[3], "AC"=>[4]}
h2 = dna_to_index(dna2, 2)
#=> {"CC"=>[0], "CA"=>[1], "AC"=>[2], "CG"=>[3], "GC"=>[4]}
h1
shows that:
"GC"
begins at index 0 of dna1
"CC"
begins at indices 1 and 2 of dna1
"CA"
begins at index 3 of dna1
"CC"
begins at index 4 of dna1
h2
has a similar interpretation. See Enumerable#flat_map and Array#product.
The method match_kmers
is then used to construct the desired array of pairs of indices [i, j]
such that h1[i] = h2[j]
.
Now let's look at the hashes produced for 3-mers (k = 3
):
h1 = dna_to_index(dna1, 3)
#=> {"GCC"=>[0], "CCC"=>[1], "CCA"=>[2], "CAC"=>[3]}
h2 = dna_to_index(dna2, 3)
#=> {"CCA"=>[0], "CAC"=>[1], "ACG"=>[2], "CGC"=>[3]}
We see that the first 3-mer in dna1
is "GCC"
, beginning at index 0. This 3-mer does not appear in dna2
, however, so there are no elements [0, X]
in the array returned (X
being just a placeholder). Nor is "CCC"
a key in the second hash. "CCA"
and "CAC"
are present in the second hash, however, so the array returned is:
h1["CCA"].product(h2["CCA"]) + h1["CAC"].product(h2["CAC"])
#=> [[2, 0]] + [[3, 1]]
#=> [[2, 0], [3, 1]]