【问题标题】:Compare lexicographically two char arrays按字典顺序比较两个 char 数组
【发布时间】:2015-03-31 17:28:15
【问题描述】:

你能帮忙吗?

我需要按字典顺序比较两个数组:如果其中一个比另一个短,则按字典顺序排列。如果它们的长度相同,则必须逐个元素地比较它们。如果一个元素在字母表中位于另一个元素之前,则此数组按字典顺序排在第一位。

这是我的代码:

using System;

internal class CompareTwoCharArraysLexicographically
{
    private static void Main()
    {
       char[] firstArray = {'a', 'b', 'c', 'z'};
       int firstArrayLength = firstArray.Length;
       char[] secondArray = {'a', 'b', 'c', 'd'};
       int secondArrayLength = secondArray.Length;
       int length = Math.Min(firstArray.Length, secondArray.Length);

       if (firstArray.Length > secondArray.Length)
       {
          Console.WriteLine("Second array is earlier.");
       }

       else if (firstArray.Length == secondArray.Length)
       {
          for (int i = 0; i < length; i++)
          {
              if (firstArray[i] > secondArray[i])
              {
                  Console.WriteLine("2 array is earlier.");
                  break;
              }
              else if (secondArray[i] > firstArray[i])
              {
                  Console.WriteLine("1 array is earlier."); 
                  break;
              }
              else
              {
                  Console.WriteLine("Two arrays are equal.");
              }
          }
       }
       else
       {
          Console.WriteLine("First array is earlier.");
       }
    }
}

如何避免三次重复消息“两个数组相等。”?

【问题讨论】:

标签: c# arrays char compare


【解决方案1】:

另一种结构化的方法:

class LexicographicCharArrayComparer : Comparer<char[]>
{
    public override int Compare(char[] x, char[] y)
    {
        if (x == null || y == null)
            return Default.Compare(x, y);

        int lengthComp = x.Length.CompareTo(y.Length);
        if (lengthComp != 0)
            return lengthComp;

        return StringComparer.Ordinal.Compare(new string(x), new string(y));
    }
}

用法:

        char[] firstArray = { 'a', 'b', 'c', 'z', };
        char[] secondArray = { 'a', 'b', 'c', 'd', };

        var comparer = new LexicographicCharArrayComparer();
        var result = comparer.Compare(firstArray, secondArray);
        if (result < 0)
            Console.WriteLine("1st array is earlier");
        else if (result == 0)
            Console.WriteLine("The two arrays are equal");
        else
            Console.WriteLine("2nd array is earlier");

当然,您自己的方法可以修复。将中间块更正为:

   else if (firstArray.Length == secondArray.Length)
   {
      bool resolved = false;
      for (int i = 0; i < length; i++)
      {
          if (firstArray[i] > secondArray[i])
          {
              Console.WriteLine("2 array is earlier.");
              resolved = true;
              break;
          }
          if (secondArray[i] > firstArray[i])
          {
              Console.WriteLine("1 array is earlier."); 
              resolved = true;
              break;
          }
      }
      if (!resolved)
      {
          Console.WriteLine("Two arrays are equal.");
      }
   }

【讨论】:

    【解决方案2】:

    我认为您需要使用跟踪变量来了解数组是否相等。当前,您说的是每次同一索引中的两个项目相等时它们都相等。相反,请考虑以下代码:

    else if (firstArray.Length == secondArray.Length)
    {
        var largerArray = 0;
    
        // Compare each item in the array
        for (int i = 0; i < length; i++)
        {
            // As soon as two items are not equal, set the comparison value and break
            if (firstArray[i] > secondArray[i])
            {
                largerArray = 1;
                break;
            }
            else if (secondArray[i] > firstArray[i])
            {
                largerArray = 2
                break;
            }
        }
    
        // Check the largerArray value. If it was never changed, the arrays are equal
        // Otherwise, display a message based on the value of the largerArray.
        if (largerArray == 0)
        {
            Console.WriteLine("Two arrays are equal.");
        }
        else
        {
            Console.WriteLine("{0} array is earlier.", largerArray); 
        }
    }
    

    【讨论】:

    • 我猜你的&lt;&gt; 应该是!=。
    • @JeppeStigNielsen 是的,谢谢!更新...正在写意。 :(
    【解决方案3】:

    这是我的建议:

            Console.Write("Enter a positive number for length of the first array: ");
            int n = int.Parse(Console.ReadLine());
            Console.Write("Enter a positive number for length of the second array: ");
            int m = int.Parse(Console.ReadLine());
    
            // Declare and create the arrays
            char[] firstArray = new char[n];
            char[] secondArray = new char[m];
    
            Console.WriteLine("Enter values of the arrays: ");
            for (int i = 0; i <  firstArray.Length; i++)
            {
                firstArray[i] = char.Parse(Console.ReadLine());
            }
            Console.WriteLine();
    
            for (int i = 0; i < m; i++)
            {
                secondArray[i] = char.Parse(Console.ReadLine());
            }
            Console.WriteLine();
    
            // Print them on the console
            for (int i = 0; i < n; i++)
            {
                Console.Write(" " + firstArray[i]);
            }            
            Console.WriteLine();
    
            for (int i = 0; i < m; i++)
            {
                Console.Write(" " + secondArray[i]);
            }            
            Console.WriteLine();
    
            int minLength = Math.Min(firstArray.Length, secondArray.Length);
            bool equalValues = true;
    
            // Search which of the arrays is lexicographically earlier
                for (int i = 0; i < minLength; i++)
                {
                    if (firstArray[i] == secondArray[i])
                    {
                        continue;
                    }
                    else if (firstArray[i] < secondArray[i])
                    {
                        Console.WriteLine("The first array is earlier.");
                        break;
                    }
                    else if (firstArray[i] > secondArray[i])
                    {
                        Console.WriteLine("The second array is earlier.");
                        break;
                    }
                }
                for (int i = 0; i < minLength; i++)
                {
                    if (firstArray[i] != secondArray[i])
                    {
                        equalValues = false;
                    }
                }
                // This is to indicate the values of the two arrays till the element of index minLength-1 are equal
                for (int i = 0; i < minLength; i++)
                {
                    if (equalValues && n < m)
                    {
                        Console.WriteLine("The first array is earlier.");
                        break;
                    }   
                    else if (equalValues && n > m)
                    {
                        Console.WriteLine("The second array is earlier.");
                        break;
                    }
                    else if (equalValues && n == m)
                    {
                        Console.WriteLine("The two arrays aree equal.");
                        break;
                    }          
                }                          
    

    【讨论】:

      【解决方案4】:

      这里是一个相对简单的实现,使用数组字符的 ASCII 值的总和作为字典比较标准:

      /*  Method: compareLexicographically(a, b);
          Compare lexicographically the two arrays passed as parameters and print result.
          Comparison criteria:
          1. Arrays lengths.
          2. Accumulated ASCII values of the array characters. 
      */
      static void compareLexicographically(char[] a, char[] b)
      {
          if (a.Length == b.Length) // same lengths
          {
              int suma = 0;
              int sumb = 0;
              for (int i = 0; i < a.Length; i++)
              {
                  suma += a[i];
                  sumb += b[i];
              }
      
              if (suma == sumb)
              {
                  Console.WriteLine("Two arrays are lexicographically equal.\n");
              }
              else
              {
                  if (suma < sumb)
                  {
                     Console.WriteLine("First array lexicographically smaller than second.\n");
                  }
                  else
                  {
                      Console.WriteLine("First array lexicographically greater than second.\n");
                  }
              }
          }
          else  // different lengths
          {
              if (a.Length < b.Length)
              {
                  Console.WriteLine("First array lexicographically smaller than second.\n");
              }
              else
              {
                  Console.WriteLine("First array lexicographically greater than second.\n");
              }
          }
      }
      

      【讨论】:

        【解决方案5】:

        我认为这可以解决您的问题 :) 希望我也能帮助你,你帮我找到一个练习的答案

        using System;
        
        internal class CompareTwoCharArraysLexicographically
        {
            private static void Main()
            {
                char[] firstArray = { 'a', 'b', 'c', 'z' };
                int firstArrayLength = firstArray.Length;
                char[] secondArray = { 'a', 'b', 'c', 'd' };
                int secondArrayLength = secondArray.Length;
                int length = Math.Min(firstArray.Length, secondArray.Length);
                bool same = false;
        
                if (firstArray.Length > secondArray.Length)
                {
                    Console.WriteLine("Second array is earlier.");
                }
        
                else if (firstArray.Length == secondArray.Length)
                {
                    for (int i = 0; i < length; i++)
                    {
                        if (firstArray[i] != secondArray[i])
                        {
                            same = false;
        
        
                            if (firstArray[i] > secondArray[i])
                            {
                                Console.Clear();
                                Console.WriteLine("2 array is earlier.");
                                break;
                            }
                            if (secondArray[i] > firstArray[i])
                            {
                                Console.Clear();
                                Console.WriteLine("1 array is earlier.");
                                break;
                            }
        
                        }
        
        
        
                        else same = true;
        
        
                        if (same == true)
                        {
                            Console.Clear();
                            Console.WriteLine("Two arrays are equal."); 
        
                        }
        
                        else
                        {
                            Console.WriteLine("First array is earlier.");
                        }
                    }
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2023-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-16
          相关资源
          最近更新 更多