![](/img/trans.png)
[英]How to check if a string of 7 random letters can form a word that exists in a file
[英]Implement Markov's algorithm using random letters till letters makeup one word in the string?
我試圖使用馬爾可夫鏈顯示隨機字母,直到字母組成字符串中找到的單詞之一。 我認為我走在正確的軌道上,但是它不會在到達一個單詞時停下來,而是會打印整個隨機字符串。
我相信將會檢查字符是否與打印件匹配,但不確定...
我在這里做錯了什么?
public class Main {
public static void main(String[] args) {
final int NUMBER_OF_CHARS = 100000;
String[] words = { "at", "is", "he", "we", "up", "on" };
for (int i = 0; i < NUMBER_OF_CHARS; i++) {
char ch = main.getRandomLowerCaseLetter();
if ((i + 1) % 40 == 0)
System.out.println(ch);
else
System.out.print(ch);
}
}
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
}
public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
}
我沒有看到任何if語句來檢查字符是否已經組成單詞。 換句話說,循環永遠不會退出,因為您還沒有為此編寫邏輯。
您可能想隨即將生成的每個字符存儲在String中,如下所示:
String chars = "";
...
for(...){
...
chars.append(ch);
...
}
您還應該編寫如下代碼來打破循環:
for(String word : words){
if(chars.contains(word){
break outerLoop;
}
}
像這樣標記外部的for循環,以便break語句可以脫離兩個循環,而不僅僅是內部的for循環:
outerLoop: while(...){}
可能有更好的方法可以執行此操作,但是可以通過一些快速的方法解決您的問題,正如Keara所建議的那樣,您需要隨身存儲每個字符,然后遍歷並檢查是否找到了所要查找的東西。 因為(無論如何,在您給出的示例中)您要查找的單詞的最大長度為2個字符,因此每次找到無效組合時都可以輕松重置字符串。
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
final int NUMBER_OF_CHARS = 100000;
String[] words = {"at", "is", "he", "we", "up", "on"};
List<Character> characters = new ArrayList<>();
for (int i = 0; i < NUMBER_OF_CHARS; i++) {
char ch = getRandomLowerCaseLetter();
characters.add(ch);
if ((i + 1) % 40 == 0) {
System.out.println(ch);
if (contains(characters, words)) {
System.exit(0);
}
} else {
System.out.print(ch);
if (contains(characters, words)) {
System.exit(0);
}
}
}
}
public static boolean contains(List<Character> characters, String[] words) {
String st = "";
int count = 0;
for (Character c : characters) {
st += c;
count++;
if (count == 2) {
for (String s : words) {
if (st.equals(s)) {
System.out.println(" Found: " + s);
return true;
}
}
count = 0;
st = "";
}
}
return false;
}
public static char getRandomCharacter(char ch1, char ch2) {
return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}
public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
}
親切的問候和快樂的編程!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.