约瑟夫环问题(c语言实现)
设有n个围坐一圈,现在从某一个人开始报数,数到m的人出列,接着从出列的下一个人(顺时针方向)开始重新报数,数到m的人出列,如此下去,直到所有的人都出列为止。试设计确定他们的出列次序序列的程序
数据要求:人数n;报数指m
数据输出:依次输出出列人员的编号
[解决办法]
这是之前做的一个例子,用的数组,仅作参考
#include <stdio.h>void get_last_element();int getNextElement(int curPosition, int CNT);int main(){ get_last_element(); return 0;}void get_last_element(){ const int ARR_SIZE = 10; int test_arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int i; int del_counter = 0; int tmp_counter = 0; int curPosition = -1; while (1) { if (test_arr[curPosition = getNextElement(curPosition, ARR_SIZE)] != -1) { // Count up the no deleted element. tmp_counter++; } // delete the element if (tmp_counter == 3) { test_arr[curPosition] = -1; printf("the deleted element index is :%d\n", curPosition); // Count up the deleted element. del_counter++; // Reset the counter tmp_counter = 0; } // The left element is 1 if (del_counter == ARR_SIZE - 1) { break; } } for (i = 0; i < ARR_SIZE; i++) { if (test_arr[i] > -1) { // Output the result. printf("The last element is:%d\n and the index is:%d\n", test_arr[i], i); break; } } getchar();}int getNextElement(int curPosition, int CNT){ return (++curPosition % CNT);}