使用不同排序的等效数组ruby查找数组中特定字符串的索引

时间:2013-09-26 15:12:43

标签: ruby arrays string loops bioinformatics

我有两个数组:fasta_ids& frags_by_density。两者都包含相同的≈1300个字符串集。 fasta_ids按数字顺序排序,例如['frag1','frag2','frag3'......] frags_by_density包含以不同方式排序的相同字符串,例如['frag14','frag1000'...]

frag_by_density的排序方式与问题无关(但对于任何生物信息学家来说,'frags'是由snp密度排序的重叠群)。

我想要做的是找到frag_by_density数组中的索引,其中包含fasta_ids中的每个字符串。我想最终得到一个新的阵列(索引),它们与fasta_ids数组的顺序相同。

例如,如果fasta_ids和frags_by_density数组中'frag'字符串的顺序相同,则输出数组将为:[0,1,2,3 ...]。 在此示例中,输出数组(2)的索引2处的值对应于fasta_ids('frag3')的索引2处的值 - 因此我可以从中推断出'frag3'字符串在frags_by_density中的索引2处

下面是我提出的代码,目前它被卡在我认为无限循环中。我已经注释了每个部分应该做什么:

x = 0 #the value of x will represent the position (index) in the density array
position_each_frag_id_in_d = [] #want to get positions of the values in frag_ids in frags_by_density
iteration = []
fasta_ids.each do |i|
    if frags_by_density[x] == i
        position_each_frag_id_in_d << x #if the value at position x matches the value at i, add it to the new array
        iteration << i
    else
        until frags_by_density[x] == i #otherwise increment x until they do match, and add the position
            x +=1
        end
        position_each_frag_id_in_d << x
        iteration << i
    end
    x = iteration.length # x should be incremented, however I cannot simply do: x += 1, as x may have been incremented by the until loop
end
puts position_each_frag_id_in_d

这是一个非常复杂的问题。希望有一个更简单的解决方案,或者至少有人可以修改我已经开始的内容。

更新:重命名数组fasta_ids,因为它在代码中(对不起,如果有任何混淆)             fasta_id = frag_id

1 个答案:

答案 0 :(得分:0)

非优化版本。 array.index(x)返回数组中x的索引,如果未找到则返回nil。 compact然后从数组中删除nil元素。

position_of_frag_id_in_d = frag_ids.map{|x| frag_by_density.index(x)}.compact