![](/img/trans.png)
[英]Java Best way to extract words or (search for characters) from a text file that contains senteces
[英]How to create a random string rotation from senteces in a file?
如何使用隨機方式在文件中的句子創建特定順序的句子? 例如:假設我有一個帶有“香蕉橙蘋果桃子”的 txt 文件
我想用“橙子、蘋果、桃子、香蕉”、“蘋果、桃子、香蕉、橙子”等創建一個數組。 這就像讓它們以新的隨機順序重新組織並將其存儲到新文件或數組或其他任何東西。 我的主要問題是每次都下一個新的隨機訂單。 我該怎么做?
到目前為止,我編寫的代碼僅按順序返回文件中的內容。
private static void sendSentences() {
String sentence;
try{
try(
InputStream fis = new FileInputStream("C:\\Users\\.....tweets.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);
){
while ((sentence = br.readLine()) != null){
sendTweet(sentence, thandle);
System.out.println("sent " + sentence + ".");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
這是使用Fisher-Yates shuffle algorithm的解決方案的概要。 這個想法是為每個生成的隨機訂單計算 hash 並使用該 hash 來檢查訂單是否重復
public static void main(String[] args) {
String[] words = new String[] {"bananas", "oranges", "apples", "peaches"};
int randomCount = 10; //this needs to <= (words.length)!
Iterator<String[]> randomIterator = new Iterator<>() {
Set<Integer> hashes = new HashSet<>();
@Override
public boolean hasNext() {
return hashes.size() < randomCount;
}
@Override
public String[] next() {
int i = words.length;
while(i > 1) {
i--;
int j = new Random().nextInt(i + 1);
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
int h = Arrays.hashCode(words);
if(hashes.contains(h)) next();
hashes.add(h);
return words;
}
};
int c = 1;
while(randomIterator.hasNext()) {
System.out.println(c++ + " " + Arrays.toString(randomIterator.next()));
}
}
這輸出:
1 [apples, oranges, bananas, peaches]
2 [apples, peaches, bananas, oranges]
3 [oranges, apples, peaches, bananas]
4 [bananas, peaches, oranges, apples]
5 [bananas, oranges, apples, peaches]
6 [oranges, bananas, apples, peaches]
7 [apples, bananas, peaches, oranges]
8 [peaches, apples, oranges, bananas]
9 [peaches, oranges, bananas, apples]
10 [bananas, apples, peaches, oranges]
使用迭代器,我們可以確保在我們必須重復一個模式之前,只根據需要執行洗牌算法的次數。 您可以將輸入/輸出機制更改為您想要的方法。
這可以根據用例進行改進。 例如,您可以在所有模式生成一次時清空哈希集,並通過遍歷n!來避免StackOverflow Error
錯誤! 重復。 您還可以使用List
而不是Array
並使用Collections.shuffle()
來獲得新的隨機順序,如另一個答案所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.