给出两个文件
random_letters.txt
AABBBBB
FLOWERS
BACKGFD
TOBEACH
dictionary.txt
flowers
to
beach
back
我需要检查random_letters与字典的每个组合,看看是否有任何常见的东西。它可以是一个至少包含6个字符的单词或两个至少等于6个字符的单词。哪个会成为FLOWERS
或TOBEACH
。
我很难搞清楚自己需要做什么。我可以让它用于7个字符的单词,因为我使用了字符串。我知道我需要使用char才能使它工作。
到目前为止:
public static void compare() {
private static String stringToWrite2 = "";
private static String[] allWords = new String[2187];
private static String[] diction = new String[79765];
private static char[][] test = new char[2187][7];
private static char[][] test2 = new char[79765][7];
public static void main(String args[])
try {
Scanner file1 = new Scanner(new File("random_letters.txt"));
Scanner file2 = new Scanner(new File("dictionary.txt"));
for(int i = 0; i < 2187; i++) {
allWords[i] = file1.next();
test[i] = allWords[i].toCharArray();
}
for(int i = 0; i < 79765; i++) {
diction[i] = file2.next();
diction[i] = diction[i].toUpperCase();
test2[i] = diction[i].toCharArray();
}
for(int i = 0; i < 2187; i++) {
for (int j = 0; j < 79765; j++) {
if(allWords[i].equals(diction[j])) {
stringToWrite2 += diction[j];
}
}
}
} catch (IOException e) {
System.out.println("could not find file");
}
System.out.println("-------------------");
System.out.println(stringToWrite2);
for(int i = 0; i < 6; i++) {
for (int j = 0; j < 7; j++)
System.out.println(test2[i][j]);
}
}}
答案 0 :(得分:0)
这里有两个稍微不同的任务:确定字典中是否还有任何单词也是random_letters(长度> = 6),并确定字典中是否有任何两个单词的集合,以便它们的并集random_letters中的一个单词。
我们不使用数组,而是使用HashSets进行存储,因为这里最常用的操作可能是.contains(...)。它还允许我们访问.retainAll(...),这对于找到交叉点非常有用。
对于任务的后半部分,我最初的想法是创建一个数据结构,其中包含所有词汇中的单词排列,并与allWords相交。我很快意识到(可能)会变得多大。相反,我使用了一个更丑陋但更节省空间的解决方案。
private static HashSet<String> allWords = new HashSet<String>();
private static HashSet<String> diction = new HashSet<String>();
public static void compare() {
try {
Scanner file1 = new Scanner(new File("random_letters.txt"));
Scanner file2 = new Scanner(new File("dictionary.txt"));
for(int i = 0; i < 2187; i++) {
allWords.add(file1.next());
}
for(int i = 0; i < 79765; i++) {
diction.add(file2.next().toUpperCase());
}
//Compile set of words that are in both
HashSet<String> intersect = new HashSet<String>();
intersect.addAll(allWords);
intersect.retainAll(diction);
for (String s : intersect){
System.out.println(s);
}
//For every word in random_letters, see if there is a word in diction that is the start of it
HashSet<String> couplesIntersect = new HashSet<String>();
for(String s : allWords){
for(String d : diction){
if(s.startsWith(d)){
//If so, check every word in diction again to see if there is a word that is the remainder
String remainder = s.subString(d.length());
for(String d2 : diction){
if(d2.equals(remainder))
//If so, store this word
couplesIntersect.add(s);
}
}
}
}
//Print those results
for (String s : couplesIntersect){
System.out.println(s);
}
} catch (IOException e) {
System.out.println("could not find file");
}
}
}