2016-11-23 118 views
3

嗨即時嘗試讓用戶列出單詞。下一步是用戶再次鍵入其中一個單詞,然後程序將檢查列表中的字母。我找到了一種方法來解決它,但只有當檢查我自己的列表。 我想知道如何去做我需要的。不需要精確的代碼,只需要一些幫助。在C#和編碼方面仍然是新的。不介意瑞典的評論。如何將用戶輸入註冊到列表C#

static void Main(string[] args) 
    { 
     Console.WriteLine("Skriv lite olika ord:"); 
     string[] words = Console.ReadLine().Split(null); 
     Console.WriteLine("Tackar! Välj ett av orden för att kolla ifall det finns Anagram ordet:"); 
     string[] word = Console.ReadLine().Split(null); 

     List<string> result = new List<string>(); 
     bool match = false; 


     for (int i = 0; i < words.Length; i++) 
      words[i] = words[i].Trim(); 

     //Loopar igenom alla ord i arrayen, börjar med första ordet. 
     for (int i = 0; i < words.Length - 1; i++) 
     { 
      result.Add(words[i]); 
      //Loopar igenom arrays med nästkommande ord. 
      for (int c = 2; c < words.Length; c++) 
      { 
       //Gämför bara ifall orden har lika många bokstäver och struntar i "tomma" ord 
       if(words[i].Length == words[c].Length && words[i] !="") 
       { 
        //Konverterar orden till CharArray 
        char[] a = words[i].ToUpper().ToCharArray(); 
        char[] b = words[c].ToUpper().ToCharArray(); 
        //Soreterar orden i bokstavsordning 
        Array.Sort(a); 
        Array.Sort(b); 

        match = false; 
        //sätter en counter för att kunna räkna 
        int counter = 0; 
        //Loppar igen alla bokstäver i orden man jämför 
        // Om den hittar någon bokstav som inte stämmer överens så returners False. 
        // Om alla bokstäver mathar så return true. 
        foreach(char x in a) 
        { 
         if (x == b[counter]) 
          match = true; 
         else 
         { 
          match = false; 
          break; 
         } 
         counter++; 
        } 
        // om alla bokstäver "matchar" så läggs de till i listan 
        // har words[c] = ""; ifall den hittar tomma strings 
        if(match) 
        { 
         result.Add(words[c]); 
         words[c] = ""; 
        } 
       } 
      } 
      // om listan bara blir 1 ord så hittas ingen match 
      if (result.Count() > 1 && result[0] != "") 
      { 
       Console.Write("Anagrams: "); 
       foreach (string s in result) 
        Console.Write(s + " "); 
       Console.WriteLine(); 
      } 
      //återställer listan 
      result.Clear(); 
     } 
     Console.ReadKey(); 
+0

如果你想讓用戶輸入一個單詞,你可以直接調用Console.ReadLine。我建議你檢查空字符串以退出程序。順便使用words.Length而不是words.Count() – bikeman868

回答

1

該解決方案其實很簡單。
你只需要檢查每個字符適合的字母數量,如果他們共享相同的字母。

E.g. word有4封信件。如果用戶輸入有5個字母的what,他們不可能匹配。但如果他輸入darn這也是4你只需檢查是否所有字母匹配。

每個人都應該保持對案例的敏感度,我離開了,使答案更簡單的眼睛。
以及有很多方法可以改善我遺漏的代碼。所有簡單:)

static void Main(string[] param) 
    { 
     //The list of Words which are anagrams 
     List<string> solutions = new List<string>(); 

     //get the user input 
     string userInput = "User writes arm ram kola like hi"; //Replace with Console.ReadLine().ToLower(); and don't forget to prompt the userwith input 

     //split it into the diffrent words 
     string[] words = userInput.Split(' '); 

     //get the users "match want" 
     string userMatchWant = "mar"; //Replace with Console.ReadLine().ToLower(); and don't forget to prompt the userwith input 

     //Find words wich are as long as mar 
     foreach (string word in words) 
     { 
      //if they arn't the same length it can't be an anagramm 
      if (word.Length != userMatchWant.Length) 
       continue; 

      //To Determin if all characters of the words are the same 
      bool hasOnlyTheSameLetters = false; 

      //now check if all characters contains 
      foreach (char c in word) 
      { 
       //If The lette is in the word assume it contains only of the letters that we are looking for, because 
       if (userMatchWant.Contains(c.ToString())) 
        hasOnlyTheSameLetters = true; 
       //else we know it has a different word so we can breack and check the other input words. 
       else 
       { 
        hasOnlyTheSameLetters = false; 
        break; 
       }       
      } 

      //if there is a diffrence in letters contine 
      if (hasOnlyTheSameLetters == false) 
       continue; 
      //else add the word to the solution 
      else 
       solutions.Add(word); 
     } 

     //Print the solutions 
     if(solutions.Count > 0) 
     { 
      Console.Write("Anagrams: "); 
      foreach (string s in solutions) 
       Console.Write(s + " "); 
      Console.WriteLine(); 
     } 

     Console.ReadKey(); 
    } 

爲了你LINQ狂熱分子在那裏的名字,這是我能想出,以取代(文字串詞)在foreach的最短途徑 - 循環:
var totalMatches = words.Where(p => p.Length == userMatchWant.Length).Where(p => p.All(c => userMatchWant.Contains(c.ToString())));

2

你的問題是不完全清楚,但我懷疑你正在尋找Console.ReadLine()string.Split(),組合爲:

string[] words = Console.ReadLine().Split(null); 

將返回由空格分隔所有子。

還有其他形式的string.Split您應該探索在那裏你可以指定分割什麼字,並從結果

+0

['Split']沒有重載(https://msdn.microsoft.com/en-us/library/b873y76a(v = vs.110) .aspx)它採用零參數 – Jamiec

+0

@Jamiec謝謝。我插入了缺失的null。 –

+0

謝謝!這解決了我的部分問題。一個仍然存在。 Anagram檢查不應該出現在列表之後。我希望用戶寫一個他們剛剛寫在列表中的單詞,然後程序應該檢查我們寫的最後一個單詞是否在我們剛剛寫的列表中有一個Anagram。以下? :) \t \t 現在我得到這樣的:寫單詞的列表:ALG滯後加侖HEJ笑謝謝!鍵入其中一個單詞來檢查anagram:Anagrams:älggäl因此,所有jsut彈出而不是我們用來比較的一個詞 – Hippimaster

1

這是你如何讀取用戶輸入刪除空白項:

static void Main(string[] args) 
{ 
    Console.WriteLine("Write a list of Words"); 
    string input = Console.ReadLine(); 
    List<string> words = input.Split(' ').ToList(); 
    List<string> result = new List<string>(); 
    bool match = false; 

這應該引起:

enter image description here

+0

謝謝!這解決了我的部分問題。一個仍然存在。 Anagram檢查不應該出現在列表之後。我希望用戶寫一個他們剛剛寫在列表中的單詞,然後程序應該檢查我們寫的最後一個單詞是否在我們剛剛寫的列表中有一個Anagram。以下? :) – Hippimaster

+0

現在我得到這樣的:寫單詞的列表: ALG滯後加侖HEJ笑 謝謝!鍵入一個關鍵詞來檢查字謎: 字謎:ALG加侖 因此,所有的僅僅指剛彈出,而不是我們來比較只有一個字了 – Hippimaster

0

我建議有一個dictionar y(或查找)而不是列表並用相同的密鑰將所有字母組合在一起。鍵字內排序字母

amr: {mar, arm, ram} 
    egl: {Elg, gel} 

的imlementation(所以我們在「‘RAM’」和值爲設定的初始字排序爲「r」,「A」,「M」後具有"amr"

private static string MakeKey(string value) { 
    return string.Concat(value 
     .Select(c => char.ToUpper(c)) // let's be case insensitive 
     .OrderBy(c => c)); 
    } 

    private static void AddWord(Dictionary<string, HashSet<string>> words, string word) { 
    string key = MakeKey(word); 

    HashSet<string> anagrams; 

    if (words.TryGetValue(key, out anagrams)) 
     anagrams.Add(word); 
    else 
     words.Add(key, new HashSet<string>() {word});    
    } 

    static void Main(string[] args) 
    Dictionary<string, HashSet<string>> words = new Dictionary<string, HashSet<string>>(); 

    // Let user input all the words separating them either by spaces or by commas etc. 
    var initialWords = Console 
     .ReadLine() 
     .Split(new char[] { ' ', ',', ';', '\t' }, StringSplitOptions.RemoveEmptyEntries); 

    foreach (var word in initialWords) 
     AddWord(words, word); 

詞典是在大的字排列的情況下更有效O(N)O(N**2)(如果要分析整個瑞典的詞彙是什麼?)。 爲了獲得anagrams,我們應該從字典s.t中過濾出對。含有至少2個字在Value

var report = words 
    .Where(pair => pair.Value.Count > 1) // at least 2 words share the same key 
    .Select(pair => string.Join(", ", pair 
     .Value 
     .OrderBy(item => item))) // let us be nice and ordering anagrams 
    .OrderBy(item => item); // let us be nice and ordering anagrams 

    Console.Write(string.Join(Environment.NewLine, report)); 

結果是

arm, ram 
    Elg, gel 
    era, rea 
    för, frö 
0

感謝迄今答案!我認爲我對這個問題的解釋有點弱。用戶輸入現在是固定的,但最後一個問題仍然存在。 用戶編寫他們的輸入後,他們得到另一個問題「鍵入列表中的一個詞來尋找anagrams?」但我的問題是,我的程序運行所有字謎,而不是我們在第二個問題中選擇的字。 :/