ユーザーに 9 文字のプロンプトを表示するプログラムがあります。これらの文字がプログラムに含まれると、プログラムは辞書ファイルと比較して、これらの文字を使用して可能な限り長い単語を作成する必要があります。
プログラムは現在、9文字を保存し、辞書ファイルを読み取りますが、単語の作成に関してどこから始めればよいかわかりません。
助けが必要なのはクリエーターという言葉だけです。誰かが配列内の文字から単語を作成する方法を知っているなら、私に手を差し伸べてもらえますか
逆に、辞書ファイルを反復処理して、各単語が指定された文字だけで構成されているかどうかを確認します。
解決策が得られないように思われるため、これが私のものです。動作するはずです
import java.util.ArrayList;
public class Test{
public String[] dict = new String[] {"hi","das","bad","fenster","esel","bahi","tfshi"};
public char[] input = new char[]{'a','b','d','h','i','s','f','t'};
public String longestString = dict[0];
public Test() {
System.out.println(longestString);
ArrayList<String> convert = new ArrayList<String>();
for(String counter : dict)
convert.add(counter);
getInstance(convert, 0, input.length, 0, 0);
System.out.println("\n\n\n" + longestString);
}
private void getInstance(ArrayList<String> searching, int pos, int length, int starter, int currentI) {
int i = starter;
do{
ArrayList<String> matched = new ArrayList<String>();
for(String counter : searching) {
if(counter.length() > pos) {
if(counter.charAt(pos) == input[i]){
matched.add(counter);
}
}
}
if(matched.size() > 0) {
getInstance(matched, pos+1,length,(i+1)%length, i%length);
}
else if(currentI != i && matched.size() > 0) {
getInstance(searching,pos,length,(i+1)%length, i%length);
}
if(matched.size() > 0 && longestString.length() < matched.get(0).length()){
longestString = searching.get(0);
}
++i;
i %= length;
}while(i != currentI);
}
public static void main(String[] args) {
new Test();
}
}
編集:少し修正する必要があります。そこに間違いが見つかりました
ユーザー Allrdy が 9 文字を入力し、辞書が配列に格納されているとします。
あなたは私が推測するchar配列を使用していますか?辞書は通常ソートされていると思いますので、配列は私の条件のいずれかになります。
forループで配列をスキャンする必要があります
// these are the scanned chars
char[] char = new chars[];
// has to be loaded from somewhere.
String[] dic = new String[100];
String found = "";
//.....reading chars
String longest = "";
for(int i = 0 : i<9;++i) {
// look if an element exists, matching the letter a at the beginning
if(exists) {
// you found a word? nice safe it in a variable called found otherise compare longest and found, to check which once length is greater
found = foundWordBefore;
for(int j = (i+1)%10;j!=i+9%10;++j) {
// look if there is another word matching the first letter and the second one
if(exists) {
for(int k = (i+2)%10;k!=i+9%10;++k) {
//same again as before, continue until you reached last (i+8)%9
}
}
}
}
else {
// if you found the nothing, compare the longest you found yet, to the longest you found before
if(longest.length < found.length) {
longest = found;
}
}
}
この擬似が役立ち、機能することを願っています:D