#include <iostream>
#include <cstdlib>
#include<ctime>
using namespace std;
 
void Swap(int &a, int &b){// 有可能swap同一变量,不能用异或版本
    int t = a;
    a = b;
    b = t;
}
void RandomShuffle(int a[], int n){  //洗牌程序
    for(int i=0; i<n; ++i){
        int j = rand() % (n-i) + i;// 产生i到n-1间的随机数
        Swap(a[i], a[j]);
    }
}
int main(){
    srand((unsigned)time(0));  //用时间来作为种子
    int n = 9;
    int a[] = {
        1, 2, 3, 4, 5, 6, 7, 8, 9
    };
    RandomShuffle(a, n);
    for(int i=0; i<n; ++i)
        cout<<a[i]<<endl;
    return 0;
}

 

相关文章:

  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
  • 2021-10-28
  • 2022-02-12
  • 2021-05-28
猜你喜欢
  • 2021-11-05
  • 2021-10-24
  • 2021-10-16
  • 2021-11-17
  • 2022-12-23
  • 2021-11-07
相关资源
相似解决方案