【发布时间】:2017-04-23 13:48:26
【问题描述】:
我面临的任务是生成 900000 个随机单词,然后打印出最常见的单词。所以这是我的算法:
1. move all number into a collection rather than printhing out them
2. for (900000...){move the frequency of Collection[i] to another collection B}
** 90W*90W is too much for a computer(lack of efficiency)
3. find the biggest number in that collection and the index.
4. then B[index] is output.
但问题是我的电脑无法处理第二步。所以我在这个网站上搜索并找到了一些关于在一堆单词中查找单词频率的答案,我查看了答案代码,但我还没有找到将它们应用于大量单词的方法。
现在我在这里展示我的代码:
/** Funny Words Generator
* Tony
*/
import java.util.*;
public class WordsGenerator {
//data field (can be accessed in whole class):
private static int xC; // define a xCurrent so we can access it all over the class
private static int n;
private static String[] consonants = {"b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","z"};
private static String[] vowels = {"a", "e", "i", "o", "u"};
private static String funnyWords = "";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = 900000; // words number
xC = sc.nextInt(); // seeds (only input)
/* Funny word list */
ArrayList<String> wordsList = new ArrayList<String>();
ArrayList<Integer> frequencies = new ArrayList<Integer>();
int maxFreq;
for (int i = 0; i < times; i++) {
n = 6; // each words are 6 characters long
funnyWords = ""; // reset the funnyWords each new time
for (int d = 0; d < n; d ++) {
int letterNum = randomGenerator(); /* random generator will generate numbers based on current x */
int letterIndex = 0; /* letterNum % 19 or % 5 based on condition */
if ((d + 1) % 2 == 0) {
letterIndex = letterNum % 5;
funnyWords += vowels[letterIndex];
}
else if ((d + 1) % 2 != 0) {
letterIndex = letterNum % 19;
funnyWords += consonants[letterIndex];
}
}
wordsList.add(funnyWords);
}
/* put all frequencies of each words into an array called frequencies */
for (int i = 0; i < 900000; i++) {
frequencies.add(Collections.frequency(wordsList, wordsList.get(i)));
}
maxFreq = Collections.max(frequencies);
int index = frequencies.indexOf(maxFreq); // get the index of the most frequent word
System.out.print(wordsList.get(index));
sc.close();
}
/** randomGenerator
* param: N(generate times), seeds
* return: update the xC and return it */
private static int randomGenerator() {
int a = 445;
int c = 700001;
int m = 2097152;
xC = (a * xC + c) % m; // update
return xC; // return
}
}
所以我意识到也许有办法以某种方式跳过第二步。任何人都可以给我一个提示?只是一个提示而不是代码,所以我可以自己尝试一下会很棒!谢谢!
修改: 我看到你的很多答案代码都包含“words.stream()”,我用谷歌搜索了它,但找不到。各位大佬能告诉我哪里可以找到这种知识吗?这个流方法在哪个类中?谢谢!
【问题讨论】:
-
使用列表会很慢。还有很多其他的收藏品需要考虑。
-
你为什么不尝试 1.) 将单词移动到列表,2.) 排序列表 (Collections.sort),3.) 遍历列表元素并且每次当前单词都相同为前一个增加一个计数器。当当前单词不同时,检查是否需要更新maxFrequency,并将计数器重置为1
标签: java algorithm arraylist collections