1 #include<cstdio>
2
3 bool duplicate(int numbers[], int length, int* duplication)
4 {
5 if (numbers == nullptr || length <= 0)
6 return false;
7 for (int i = 0; i < length; ++i)
8 {
9 if (numbers[i] < 0 || numbers[i] > length - 1)
10 return false;
11
12 }
13 for (int i = 0; i < length; ++i)
14 {
15 while (numbers[i] != i)
16 {
17 if (numbers[i] == numbers[numbers[i]])
18 {
19 *duplication = numbers[i]; //
20 return true;
21 }
22
23 int temp = numbers[i];
24 numbers[i] = numbers[temp];
25 numbers[temp] = temp;
26
27
28 }
29 return false;
30 }
31 }
32 // test codes
33 bool contains(int array[], int length, int number)
34 {
35 for (int i = 0; i < length; ++i)
36 {
37 if (array[i] == number)
38 return true;
39 }
40 return false;
41 }
42 void test(char* testName, int numbers[], int lengthNumbers, int expected[], \
43 int expectedExpected, bool validArgument)
44 {
45 printf("%s begins: ", testName);
46 int duplication;
47 bool validInput = duplicate(numbers, lengthNumbers, &duplication);
48
49 if (validArgument == validInput)
50 {
51 if (validArgument)
52 {
53 if (contains(expected, expectedExpected, duplication))
54 printf("Passed.\n");
55 else
56 printf("Failed.\n");
57 }
58 else
59 printf("Passed.\n");
60 }
61 else
62 printf("Failed.\n");
63 }
64
65 void test1()
66 {
67 int numbers[] = { 2,1,3,1,4 };
68 int duplications[] = { 1 };
69 test("Test1", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), true);
70 }
71 void test3()
72 {
73 int numbers[] = { 2,4,2,1,4 };
74 int duplications[] = { 2,4 };
75 test("Test1", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), true);
76 }
77
78 // 无效的输入
79 void test6()
80 {
81 int* numbers = nullptr;
82 int duplications[] = { -1 }; // not in use in the test function
83 test("Test6", numbers, 0, duplications, sizeof(duplications) / sizeof(int), false);
84 }
85
86 // 没有重复的数字
87 void test4()
88 {
89 int numbers[] = { 2, 1, 3, 0, 4 };
90 int duplications[] = { -1 }; // not in use in the test function
91 test("Test4", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), false);
92 }
93
94 // 没有重复的数字
95 void test5()
96 {
97 int numbers[] = { 2, 1, 3, 5, 4 };
98 int duplications[] = { -1 }; // not in use in the test function
99 test("Test5", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), false);
100 }
101 // 重复的数字是数组中最大的数字
102 void test2()
103 {
104 int numbers[] = { 2, 4, 3, 1, 4 };
105 int duplications[] = { 4 };
106 test("Test2", numbers, sizeof(numbers) / sizeof(int), duplications, sizeof(duplications) / sizeof(int), true);
107 }
108 void main()
109 {
110 test1();
111 test2();
112 test3();
113 test4();
114 test5();
115 test6();
116 }