題目:n人圍成一個圈,順序排列。
從第一個人開始報數,從一報到三,凡是報到三的人退出圈子,
問最後留下的是原來第幾号的那位。
問題來源:> C語言論壇提問帖 <
獻醜了!
// 20190421_circle_report_3_last_one_.c
/* 題目:n人圍成一個圈,順序排列。
* 從第一個人開始報數,從一報到三,凡是報到三的人退出圈子,
* 問最後留下的是原來第幾号的那位。
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
// 去除值為0的元素,重整數組長度
int del_zero(int *p, int *source, int new_n, int *temp);
int main(int argc, char const *argv[])
{
int n;
printf("Enter a num > 0 ==> people quantity: ");
if (scanf("%d", &n) != 1) {
printf("Enter error!\n");
exit(1);
}
if (n < 1) {
printf("Number is too small. Bye!\n");
exit(1);
}
int *p, *source;
source = (int *)malloc(n * sizeof(int));
if (source == NULL) {
printf("source malloc error!\n");
exit(1);
}
for (p = source; p < source + n; p++) {
*p = p - source + 1;
}
int new_n = n;
int *temp = (int *)malloc(n * sizeof(int));
if (temp == NULL) {
printf("temp malloc error!\n");
exit(1);
}
int num = 1;
while (1) {
for (p = source; p < source + new_n; num++) {
if (new_n >= 3) {
if (num % 3 == 0) {
*p = 0;
num = 0;
new_n = del_zero(p, source, new_n, temp);
// 重整數組後,後面的元素向前移動了一位,
// 是以下一次要從這次的位置開始數1
p = p - 1;
}
} else if (new_n == 2) {
*p = 0;
new_n = del_zero(p, source, new_n, temp);
break;
} else {
break;
}
// 如果周遊到了最後一位元素,則下一次從頭開始
if (p == source + new_n - 1) {
p = source;
} else {
p++;
}
}
if (new_n == 1) {
free(temp);
temp = NULL;
break;
}
}
printf("The last number is %d\n", *source);
free(source);
source = NULL;
return 0;
}
// 去除值為0的元素,重整數組長度
int del_zero(int *p, int *source, int new_n, int *temp)
{
int i;
for (i = 0, p = source; p < source + new_n; p++) {
if (*p != 0)
temp[i++] = *p;
}
new_n = i;
int j;
for (j = 0, p = source; j < new_n; j++) {
*p = temp[j];
p++;
}
return new_n;
}
簡單測試
Linux環境下,clang編譯,測試運作結果:
(1)
Enter a num > 0 ==> people quantity: 0
Number is too small. Bye!
(2)
Enter a num > 0 ==> people quantity: 1
The last number is 1
(3)
Enter a num > 0 ==> people quantity: 2
The last number is 2
(4)
Enter a num > 0 ==> people quantity: 3
The last number is 2
(5)
Enter a num > 0 ==> people quantity: 4
The last number is 1
(6)
Enter a num > 0 ==> people quantity: 5
The last number is 4
(7)
Enter a num > 0 ==> people quantity: 6
The last number is 1
(8)
Enter a num > 0 ==> people quantity: 7
The last number is 4
(9)
Enter a num > 0 ==> people quantity: 11
The last number is 7
(10)
Enter a num > 0 ==> people quantity: 16
The last number is 8