[英]How to transform a Map<String, List<String>> into a List<Map<String, String>> and get Cartesian product?
[英]How to get cartesian product from Map of String Set
這可能類似於Java : Cartesian Product of a Lists但沒有回答我的問題。
我創建了以下內容
TreeMap<String, Set<String>> aMapOfSet
aMapOfSet
表示句子中的不同單詞,如果沒有變化, Set<String>
將包含單詞的所有變體,則該單詞鍵的 set 將為空/空。
我想編寫一個方法,該方法將采用 aMapOfSet 並返回一個包含所有可能句子的集合。
例如,原句可能是:
tss xes wxy xyz
假設單詞“wxy”總共有 3 個變體,單詞“xyz”總共有 2 個變體
然后 aMapOfSet 看起來像這樣
tss
xes
wxy -> [wxys,wxyes]
xyz -> [xyzs]
答案將是 resultSet 中的 6 個句子
tss xes wxy xyz
tss xes wxys xyz
tss xes wxyes xyz
tss xes wxy xyzs
tss xes wxys xyzs
tss xes wxyes xyzs
我使用 treeMap 來保留單詞的序列。
這是我正在進行的工作代碼:
Set<String> getCartesianProduct(TreeMap<String, Set<String>> wordVariationSet)
{
Set<String> resultSet =new HashSet<String>();// to store answer
for(String theOriginalWord: wordVariationSet.keySet())
{
for(String word:wordVariationSet.get(theOriginalWord))
{
// TODO create a sentence with 1 space between words and add to resultSet
}
}
return resultSet;
}
隨着我取得更多進展,我將更新代碼。
迭代所有變體的最佳方法是什么,以便獲得所有 6 個句子。
這可能是使用遞歸的好時機:
Set<String> getCartesianProduct(List<String> originalWords, TreeMap<String, Set<String>> wordVariationSet) {
Set<String> resultSet =new HashSet<String>(); // to store answer
varyWord(resultSet, "", originalWords, wordVariationSet, 0); // begin recursion with empty sentence
return resultSet; // return result
}
void varyWord(Set<String> result, String sentence, List<String> originalWords, Map<String, Set<String>> wordVariationSet, int index) {
if (index==originalWords.size()) { // no more words to vary -> sentence is complete
result.add(sentence); // add to results
return; // done (return from recursion)
}
if (index>0) sentence += " "; // add a space if working on any but first word
String theOriginalWord = originalWords.get(index); // grab original word
varyWord(result, sentence + theOriginalWord, originalWords, wordVariationSet, index+1); // add to sentence and vary next word
Set<String> wordVariations = wordVariationSet.get(theOriginalWord); // grab variations of this word
if (wordVariations!=null) // make sure they're not null
for(String word: wordVariations) // iterate over variations
varyWord(result, sentence + word, originalWords, wordVariationSet, index+1); // add to sentence and vary next word
}
我希望這段代碼是不言自明的。 如果沒有,請告訴我,我可以添加一些細節。
有幾點需要注意:
List<String> originalWords
作為參數的原因,它確實保留了順序。 因此,您還需要對其進行初始化(創建一個ArrayList
並在put(...)
一個單詞放入aMapOfSet
,還將其add(...)
到列表中)。originalWords
和wordVariationSet
的空檢查,檢查wordVariationSet
是否包含與originalWords
相同的單詞,...originalWords
wordVariationSet
兩次包含相同的單詞,則wordVariationSet
將無法處理每個單詞的不同變體。 相反,您的第二個put(...)
將覆蓋您的第一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.