在数据处理和算法设计中,经常需要比较两组数据的相似性。本文通过一个实际案例——多组数字对比与替换系统,详细介绍如何从需求分析到代码实现,完成一个功能完备的数字对比工具。我们将分别用 Java 和 Python 实现,并深入探讨对比逻辑的优化方式。
输入:
A组:
A1: 340516154771
A2: 348185279640
A3: 548731001647
A4: 348003001649
B组: 045288193789输出:
| 组号 | 主相同 | 副相同 |
| A1 | 3 | 2 |
| A2 | 2 | 3 |
| A3 | 0 | 2 |
| A4 | 4 | 0 |替换操作:
输入替换组号(如2): 4
替换后的A4: 0 4 5 2 8 8 1 9 3 7 8 9定义:相同位置上的数字相同。
实现逻辑:
int mainMatch = 0;
for (int i = 0; i < length; i++) {
if (a.charAt(i) == b.charAt(i)) {
mainMatch++;
}
}定义:数字相同但位置不同(需排除主相同已匹配的数字)。
实现逻辑(Java):
int[] aCount = new int[10]; // 统计A中未匹配的数字频率
int[] bCount = new int[10]; // 统计B中未匹配的数字频率
for (int i = 0; i < length; i++) {
if (a.charAt(i) != b.charAt(i)) {
aCount[a.charAt(i) - '0']++;
bCount[b.charAt(i) - '0']++;
}
}
int subMatch = 0;
for (int i = 0; i < 10; i++) {
subMatch += Math.min(aCount[i], bCount[i]);
}实现逻辑(Java):
public void replaceInA(int index) {
if (index < 1 || index > groupA.length) {
System.out.println("无效的组号");
return;
}
groupA[index-1] = groupB;
System.out.printf("替换后的A%d: %s\n", index, formatNumber(groupB));
}import java.util.Scanner;
public class NumberComparator {
private String[] groupA;
private String groupB;
public NumberComparator(String[] aNumbers, String bNumber) {
this.groupA = aNumbers;
this.groupB = bNumber;
}
// 对比所有A组与B组
public void compareAll() {
System.out.println("[对比结果]");
System.out.println("| 组号 | 主相同 | 副相同 |");
for (int i = 0; i < groupA.length; i++) {
if (groupA[i] == null || groupA[i].isEmpty()) continue;
int[] result = compareNumbers(groupA[i], groupB);
System.out.printf("| A%d | %d | %d |\n", i+1, result[0], result[1]);
}
}
// 对比两个数字字符串
private int[] compareNumbers(String a, String b) {
int mainMatch = 0; // 主相同
int subMatch = 0; // 副相同
int length = Math.min(a.length(), b.length());
// 统计主相同
for (int i = 0; i < length; i++) {
if (a.charAt(i) == b.charAt(i)) {
mainMatch++;
}
}
// 统计副相同
int[] aCount = new int[10];
int[] bCount = new int[10];
for (int i = 0; i < length; i++) {
if (a.charAt(i) != b.charAt(i)) {
aCount[a.charAt(i) - '0']++;
bCount[b.charAt(i) - '0']++;
}
}
for (int i = 0; i < 10; i++) {
subMatch += Math.min(aCount[i], bCount[i]);
}
return new int[]{mainMatch, subMatch};
}
// 替换A组中的某个数字
public void replaceInA(int index) {
if (index < 1 || index > groupA.length) {
System.out.println("无效的组号");
return;
}
groupA[index-1] = groupB;
System.out.printf("替换后的A%d: %s\n", index, formatNumber(groupB));
}
// 格式化数字输出
private String formatNumber(String num) {
return num.replace("", " ").trim();
}
public static void main(String[] args) {
// 初始化数据
String[] aNumbers = {
"340516154771",
"348185279640",
"548731001647",
"348003001649"
};
String bNumber = "045288193789";
NumberComparator comparator = new NumberComparator(aNumbers, bNumber);
// 显示初始数据
System.out.println("A组数量: " + aNumbers.length);
for (int i = 0; i < aNumbers.length; i++) {
System.out.printf("A%d: %s\n", i+1, aNumbers[i]);
}
System.out.println("B组: " + bNumber);
// 对比所有组
comparator.compareAll();
// 用户输入替换
Scanner scanner = new Scanner(System.in);
System.out.print("\n输入替换组号(如2): ");
int replaceIndex = scanner.nextInt();
// 执行替换
comparator.replaceInA(replaceIndex);
scanner.close();
}
}class NumberComparator:
def __init__(self, a_numbers, b_number):
self.group_a = a_numbers
self.group_b = b_number
def compare_all(self):
print("[对比结果]")
print("| 组号 | 主相同 | 副相同 |")
for i, a_num in enumerate(self.group_a, 1):
if not a_num:
continue
main_match, sub_match = self.compare_numbers(a_num, self.group_b)
print(f"| A{i} | {main_match} | {sub_match} |")
@staticmethod
def compare_numbers(a, b):
length = min(len(a), len(b))
main_match = sum(1 for i in range(length) if a[i] == b[i])
a_counts = [0] * 10
b_counts = [0] * 10
for i in range(length):
if a[i] != b[i]:
a_counts[int(a[i])] += 1
b_counts[int(b[i])] += 1
sub_match = sum(min(a_d, b_d) for a_d, b_d in zip(a_counts, b_counts))
return main_match, sub_match
def replace_in_a(self, index):
if 1 <= index <= len(self.group_a):
self.group_a[index-1] = self.group_b
formatted = ' '.join(self.group_b)
print(f"替换后的A{index}: {formatted}")
else:
print("无效的组号")
# 示例使用
if __name__ == "__main__":
a_numbers = [
"340516154771",
"348185279640",
"548731001647",
"348003001649"
]
b_number = "045288193789"
comparator = NumberComparator(a_numbers, b_number)
print(f"A组数量: {len(a_numbers)}")
for i, num in enumerate(a_numbers, 1):
print(f"A{i}: {num}")
print(f"B组: {b_number}")
comparator.compare_all()
replace_index = int(input("\n输入替换组号(如2): "))
comparator.replace_in_a(replace_index)通过本文,读者可以掌握数字对比算法的设计与实现,并了解Java和Python在字符串处理上的差异。完整代码已提供,可直接运行测试!