您好,登錄后才能下訂單哦!
1、隨機化數組問題
就是對已有的數組進行亂序排列,使之隨機的,毫無規律;
(1)、代碼實現
#include<stdio.h> #include<time.h> #include<stdlib.h> void showArray(int *a, int count); void random_1(int *a, int count); void random_1(int *a, int count){ int i; int tmp; int index; srand(time(NULL)); for(i = count; i > 0; i--){ index = rand()%i; tmp = a[index]; a[index] = a[i-1]; a[i-1] = tmp; } } void showArray(int *a, int count){ int i; for(i = 0; i < count; i++){ printf("%d ", a[i]); } printf("\n"); } int main(void){ int a[] = {4, 6, 8, 2, 0, 7, 1,}; int count = sizeof(a)/sizeof(int); showArray(a, count); random_1(a, count); showArray(a, count); return 0; }
(2)、結果截圖
2、約瑟夫環問題
M個元素,第N個元素出圈,從第start開始數即可;
(1)、代碼實現
#include<stdio.h> #include<malloc.h> void yusf(char **str, int count, int doom, int start){ int *person; int i; int pre = start-2; int cur = start-1; int alive = count; int doomNumber = 0; if(start == 1){ pre = count-1; } person = (int *)malloc(sizeof(int) * count); for(i = 0; i < count; i++){ person[i] = (i+1)%count; //循環數組 } for(; alive > 0; cur = person[cur]){ if(++doomNumber >= doom){ printf("%s->出圈\n", str[cur]); alive--; doomNumber = 0; person[pre] = person[cur]; //出圈時的pre的保存 }else{ pre = cur; } } } int main(void){ char *str[] = {"李大", "馬二", "張三", "李四", "王五", "劉六", "吊七", "朱八", "楊九"}; int count = sizeof(str)/sizeof(char *); int doom; //惡運數字 int start; //從第幾個人開始 scanf("%d%d", &doom, &start); if(doom > count || doom <= 0 || start > count|| start <= 0){ return; } yusf(str, count, doom, start); //count個元素,doom個厄運數字,從第start開始; return 0; }
(2)、結果截圖
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。