C語言本身沒有提供shuffle陣列的函式,以下就提供一個打亂陣列的自訂函式。

原始碼
	#include<stdio.h>
	#include<stdlib.h>
	#include<time.h>

	void shuffle(int *array, size_t n){
		//亂數前置
		srand(time(NULL));
		if (n > 1){
			size_t i;
			for (i = 0; i<n; i++){
				size_t j = rand()/(RAND_MAX/(n));
				int t = array[j];
				array[j] = array[i];
				array[i] = t;
			}
		}
	}
	
使用範例
	int main(void){
		//亂數前置
		srand(time(NULL));
		//宣告陣列
		int a[] = {90, 91, 92, 93, 94, 95, 96, 97, 98, 99};
		int m = (int) sizeof(a)/sizeof(a[0]);
		//亂數
		shuffle(a, m);
		//印出
		int i;
		for(i=0; i<m; i++){
			printf("%d = %d\n", i, a[i]);
		}
		return 0;
	}
	
執行結果
	0 = 96
	1 = 95
	2 = 91
	3 = 98
	4 = 93
	5 = 99
	6 = 90
	7 = 92
	8 = 94
	9 = 97
	

酷米 © All Rights Reserved.

loading
Loading...