-2

I have a very simple and silly test that is to compare two strings and check if it is an anagram.

I found this question, bt besides being old, it has no correct answer.

This using LINQ.

This not solve my question.

I managed to solve it using LINQ and also using a foreach, but the next challenge is to do it using sorting (without using LINQ). An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. We can generalize this in string processing by saying that an anagram of a string is another string with exactly the same quantity of each character in it, in any order.

How can I sort without using LINQ?

private static bool CheckAnagramWithLinq(string texto1, string texto2)
{
   return texto1.ToList().Intersect(texto2.ToList()).ToList().Count == texto1.Length;
}
private static bool CheckAnagramaWithoutLinq(string texto1, string texto2)
{
      var charArray = texto1.ToCharArray();

      foreach (var caracter in charArray)
      {
          if (texto2.Contains(caracter) && texto1.Count(x => x == caracter) == texto2.Count(x => x == caracter))
      continue;

      return false;
   }

   return true;
}
Diego Lobo
  • 156
  • 7
  • Here's a hint: a property of anagrams is that, since they contain the same letters in different orders, sorting the letters of two anagrams alphabetically (and removing whitespace) will produce two identical lists. – Abion47 Feb 03 '23 at 17:48
  • [Sorting Algorithms in C#](https://code-maze.com/sorting-algorithms-csharp/) – Dimitris Maragkos Feb 03 '23 at 17:49
  • @DimitrisMaragkos In your opinion, which one is the most suitable for this specific case? – Diego Lobo Feb 03 '23 at 17:55
  • There's also a bug in your LINQ attempt. If `b` is longer than `a` but contains the same unique letters, the function will return true. (For example, try `CheckAnagramWithLinq("abcdef", "ffedcba");`) – Abion47 Feb 03 '23 at 17:56
  • Thank's @Abion47, I will work on it. – Diego Lobo Feb 03 '23 at 17:58
  • 1
    @DimitrisMaragkos The assignment was to check anagrams without using LINQ. It says nothing about not using `List.Sort`. (As opposed to `List.OrderBy`, which *is* LINQ.) – Abion47 Feb 03 '23 at 17:58
  • There are plenty of ways to sort lists/arrays, but unfortunately most are RTFM (which is not allowed on SO either as comments or answers). As result reasonable duplicates are all a bit more complicated - since you asked "no LINQ" you may mean "no library methods for my CS101 assignment" - there is bubble-sort duplicate that you can just copy-paste code from to your assignment. – Alexei Levenkov Feb 03 '23 at 18:37
  • 1
    Assuming you can use Generics, it's [fairly simple](https://replit.com/join/hmmsoaenqj-idlemind)... – Idle_Mind Feb 03 '23 at 18:42

1 Answers1

0

Works for me:

private static bool CheckAnagram(string text1, string text2)
{
    var aa = string.Concat(text1.OrderBy(c => c));
    var bb = string.Concat(text2.OrderBy(c => c));

    return aa == bb;
}