我不明白为什么,但是当我嵌套这两个循环时,我得到了太多的插入和匹配。任何帮助表示赞赏!
伪代码两个数组-嵌套for循环搜索第二个数组以匹配第一个数组中的每个元素如果在第二个数组中有匹配项,则取匹配后的数字在第一个数组中匹配的单词后插入数字结束
问题代码:
ary1 = ['a','b','c','d']
ary2 = ['e','f','g', 'a']
limit = ary1.count - 1
limit2 = ary2.count - 1
(0..limit).each do |i|
(0..limit2).each do |j|
if ary1[i] == ary2[j]
ary1.insert(i,ary2[j])
puts 'match!'
end
end
end
puts ary1
输出:匹配!匹配!匹配!匹配!a a a a b c d
临时解决方案:
ary1 = ['a','b','c','d']
ary2 = ['e','f','g', 'a']
# have to make a copy to avoid excessive matches
ary_dup = Array.new(ary1)
limit = ary1.count - 1
limit2 = ary2.count - 1
(0..limit).each do |i|
(0..limit2).each do |j|
if ary1[i] == ary2[j]
ary_dup.insert(i,ary2[j])
puts 'match!'
end
end
end
puts ary_dup
输出:匹配!a a b c d