c# - 比较两个字母数字 "numbers",任意排序

标签 c# algorithm compare

我在使用以下算法时遇到逻辑问题:

Compare to alphanumeric numbers "letter by letter", in a way that the order of "letters" is, in ascending order:

0123456789A...Z

Example results:

  • V123 > A789 = true (because V > A)
  • AB123CD > 12DEF56 = true (because A > 1)
  • AB > DE = false (because A < D)
  • A1B2 > A123 = true (because B > 2)
  • X2Y3 > X1Y5 = false (because 3 < 5)
  • AB10 > AA23 = true (because B > A)
  • VA20C > VB10C = false (because A < B)

The order must be editable, so that you might change that A > Z some day, or 9 > B, etc.

我当前的算法适用于大多数测试用例,但示例中的那些仍然给我带来麻烦 - 算法将它们报告为不匹配,而实际上它们应该匹配。

private static string _customAlphanumericOrder = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static bool Matches(string left_, string right_)
{
    int maxLength = Math.Max(left_.Length, right_.Length);

    left_ = left_.PadRight(maxLength, '0').ToUpperInvariant();
    right_ = right_.PadRight(maxLength, '0').ToUpperInvariant();

    for (int index = 0; index < maxLength; index++) {
        int leftOrderPosition = _customAlphanumericOrder.IndexOf(left_[index]);
        int rightOrderPosition = _customAlphanumericOrder.IndexOf(right_[index]);

        if (leftOrderPosition > rightOrderPosition) {
            return true;
        }
    }

    return false;
}

我知道我的错误在于我过早地中止了算法,但我想不通如何才能将前一个字母的结果“转移”到下一个。

我怎样才能摆脱困境?

最佳答案

我想我会像这样更新算法(参见添加的 if):

private static string _customAlphanumericOrder = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static bool Matches(string left_, string right_)
{
    int maxLength = Math.Max(left_.Length, right_.Length);

    left_ = left_.PadRight(maxLength, '0').ToUpperInvariant();
    right_ = right_.PadRight(maxLength, '0').ToUpperInvariant();

    for (int index = 0; index < maxLength; index++)
    {
        int leftOrderPosition = _customAlphanumericOrder.IndexOf(left_[index]);
        int rightOrderPosition = _customAlphanumericOrder.IndexOf(right_[index]);

        if (leftOrderPosition > rightOrderPosition)
        {
            return true;
        }
        if (leftOrderPosition < rightOrderPosition)
        {
            return false;
        }
    }

    return false;
}

在我的示例中,如果左边大于右边,则算法返回 true;如果它们相等或左边小于右边,则算法返回 false。 但是,最好知道预期的行为到底是什么。算法何时应返回 true,何时应返回 false?

关于c# - 比较两个字母数字 "numbers",任意排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479191/

相关文章:

c# - 未导出成员函数时从 C# 调用 C++ native /非托管成员函数

c# - htmlagilitypack 提取电子邮件

arrays - 查找数组中开始/结束索引的所有可能排列

python - 如果值小于 Pandas 数据框系列中的先前值

c - 字符串比较

c# - 在 C# 中查看非托管 dll 上的导出表

c# - 如何通过正则表达式验证mvc中的CNIC号

algorithm - "~"符号对于算法的运行时间意味着什么?

c++ - SPOJ SUMFOUR.....TLE 在测试用例 9 上

C#比较基于名称的文件列表不返回完整路径