我有2个清单
allWords [book, pen, pencil]
subsetString [book pen , book pencil , pen pencil ]
我期望我的输出为
book pen => pencil
book pencil => pen
pen pencil => book
即对于subsetString中的每个元素,我将使用所有单词对其进行检查。
一旦找不到匹配项,所有单词的字符串将被添加到输出的RHS中
但是我的问题是
现在我只得到2个输出而不是3个
allWords [book, pen, pencil]
subsetString [book pen , book pencil , pen pencil ]
pen pencil => book
book pen => pencil
原因是进入
book pencil
时会被allWords [book, pen, pencil]
检查一旦涉及到笔包含
book pencil
-它就会变得令人满意(因为pencil
包含子字符串pen
)。码
public void getStrongRules2(ArrayList<String> allWords,String delim) {
ArrayList<ArrayList<String>> subsets = BTSum(allWords);
ArrayList<String> subsetString = new ArrayList<String>();
for (int j = 0; j < subsets.size(); j++) {
String substring = "";
for (int k = 0; k < subsets.get(j).size(); k++) {
substring += subsets.get(j).get(k) + " ";
}
subsetString.add(substring);
}
System.out.println("allWords "+allWords);
System.out.println("subsetString "+subsetString);
for(String a : allWords){
for (int j = 0; j < subsetString.size(); j++) {
if (!(subsetString.get(j).contains(a))) {
System.out.println(subsetString.get(j)+" => "+a);
}
}
}
}
public static ArrayList<ArrayList<String>> BTSum(ArrayList<String> numbers) {
int n = numbers.size();
ArrayList<ArrayList<String>> powerSet = new ArrayList<ArrayList<String>>();
for (long i = 0; i < (1 << n); i++) {
ArrayList<String> element = new ArrayList<String>();
for (int j = 0; j < n; j++)
if ((i >> j) % 2 == 1) {
element.add(numbers.get(j));
}
if (element.size() > 1 && element.size() < n) {
powerSet.add(element);
}
}
return powerSet;
}
}
但这在我的情况下不应该发生。
如何纠正。
请建议
最佳答案
考虑
List<String> allWords = new ArrayList<>();
allWords.add("Book"); allWords.add("Pen"); allWords.add("Pencil") ;
如果您能够将您的子集拆分为三个不同的列表,而不是单个arrayList,请执行拆分操作
list1 [Book,Pen]
list2 [Book,Pencil]
list3 [Pen,Pencil]
您无需循环即可遵循
Set<String> results1 = new HashSet<String>(allWords);
results1.removeAll(list1);
System.out.println("result1 : "+ list1 +" ===> "+ results1);
Set<String> results2 = new HashSet<String>(allWords);
results2.removeAll(list2);
System.out.println("result2 : "+ list2 +" ===> "+ results2);
Set<String> results3 = new HashSet<String>(allWords);
results3.removeAll(list3);
System.out.println("result3 : "+ list3 +" ===> "+ results3);
输出量
result1 : [Book, Pen] ===> [Pencil]
result2 : [Book, Pencil] ===> [Pen]
result3 : [Pen, Pencil] ===> [Book]
希望这可以帮助