現在、私が取り組んでいる小さなプロジェクトをいじっています。これはカウントダウンタイプのゲーム(テレビ番組)です。現在、このプログラムでは、ユーザーが母音または子音を9文字の制限まで選択し、これらの9文字を使用して考えられる最長の単語を入力するように求めています。
辞書として機能する大きなテキストファイルがあり、ユーザーが入力した文字列を使用して検索し、結果を照合して、入力した単語が有効な単語であるかどうかを確認します。私の問題は、9文字で構成される最長の単語を辞書で検索したいのですが、それを実装する方法が見つからないようです。
これまで、すべての単語を配列に入れ、各要素を検索して文字が含まれているかどうかを確認しようとしましたが、9文字から作成できる最長の単語が8文字の単語であるかどうかはわかりません。何か案は?現在私はこれを持っています(これはフォームの送信ボタンの下にあります。コードを提供しなかったり、Windowsフォームアプリケーションであると言って申し訳ありません):
StreamReader textFile = new StreamReader("C:/Eclipse/Personal Projects/Local_Projects/Projects/CountDown/WindowsFormsApplication1/wordlist.txt");
int counter1 = 0;
String letterlist = (txtLetter1.Text + txtLetter2.Text + txtLetter3.Text + txtLetter4.Text + txtLetter5.Text + txtLetter6.Text + txtLetter7.Text + txtLetter8.Text + txtLetter9.Text); // stores the letters into a string
char[] letters = letterlist.ToCharArray(); // reads the letters into a char array
string[] line = File.ReadAllLines("C:/Eclipse/Personal Projects/Local_Projects/Projects/CountDown/WindowsFormsApplication1/wordlist.txt"); // reads every line in the word file into a string array (there is a new word on everyline, and theres 144k words, i assume this will be a big performance hit but i've never done anything like this before so im not sure ?)
line.Any(x => line.Contains(x)); // just playing with linq, i've no idea what im doing though as i've never used before
for (int i = 0; i < line.Length; i++)// a loop that loops for every word in the string array
// if (line.Contains(letters)) //checks if a word contains the letters in the char array(this is where it gets hazy if i went this way, i'd planned on only using words witha letter length > 4, adding any words found to another text file and either finding the longest word then in this text file or keeping a running longest word i.e. while looping i find a word with 7 letters, this is now the longest word, i then go to the next word and it has 8 of our letters, i now set the longest word to this)
counter1++;
if (counter1 > 4)
txtLongest.Text + = line + Environment.NewLine;
マイクのコード:
using System;
System.Collections.Genericを使用します。System.Linqを使用します。
クラスプログラム
static void Main(string[] args) {
var letters = args[0];
var wordList = new List<string> { "abcbca", "bca", "def" }; // dictionary
var results = from string word in wordList // makes every word in dictionary into a seperate string
where IsValidAnswer(word, letters) // calls isvalid method
orderby word.Length descending // sorts the word with most letters to top
select word; // selects that word
foreach (var result in results) {
Console.WriteLine(result); // outputs the word
}
}
private static bool IsValidAnswer(string word, string letters) {
foreach (var letter in word) {
if (letters.IndexOf(letter) == -1) { // checks if theres letters in the word
return false;
}
letters = letters.Remove(letters.IndexOf(letter), 1);
}
return true;
}
}