我有一个字符串数组dictionary
和一个字符串target
:
dictionary = ['a', 'b', 'c', 'ab', 'abc']
target = 'abba'
我的目标是返回dictionary
可以组成的单词组合target
。它应该返回这样的东西
['a abc', 'a a b c', 'a ab c']
这就是我所拥有的:
def possible_combinations(dictionary, target)
results = [] #eventually an array of results
i = 0 #to go through the dictionary index starting at 0
t = 0 #to go through the target index starting at 0
while i < dictionary.count #while 0 is less than the total index in dict
while t < target.length
if dictionary[i] == target[t]#dict is not changing but target[t] is changing
puts 'I am ' + dictionary[i] + ' at DICT for now'
puts 'I am ' + target[t] + ' at t for now'
puts 'I match somewhere in target so I am added.'#dict[1] is not happening here.
# results.push(dictionary[i])
if results.empty?
results.push(dictionary[i])
puts results
else
results = results[0] + ' ' + dictionary[i] #this is not entirely working?
puts results
end
else
puts 'forget about me'
end
t = t + 1
end
i = i + 1
end
end
当我运行它时,我得到了这个:
I am a at DICT for now
I am a at t for now
I match somewhere in target so I am added.
a
forget about me
forget about me
I am a at DICT for now
I am a at t for now
I match somewhere in target so I am added.
a a
我注意到这种target[t]
情况正在改变,但dictionary[i]
没有。我不明白嵌套的while循环。我认为内部的while循环必须在它到达外部之前完成,所以dictionary[i]
被卡住了。i
我想对dictionary
and进行迭代target
,所以我使用嵌套的 while 循环。
如果target = 'aaaba'
,我得到这个:
I am a at DICT for now
I am a at t for now
I match somewhere in target so I am added.
a
I am a at DICT for now
I am a at t for now
I match somewhere in target so I am added.
a a
I am a at DICT for now
I am a at t for now
I match somewhere in target so I am added.
a a
forget about me
I am a at DICT for now
I am a at t for now
I match somewhere in target so I am added.
a a
注意结果是如何卡在两个'a'
而不是三个或四个上的?