我在使用以下算法时遇到逻辑问题:
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/