隨機化數組和約瑟夫環

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)、結果截圖

wKiom1jUABDwG_omAABd9nOXOoQ672.png-wh_50


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)、結果截圖

wKiom1jUAbHAK8NNAABOK-vbv9Q866.png-wh_50



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章