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