Skip to content

Instantly share code, notes, and snippets.

@xxxzhi
Created November 25, 2013 15:28
Show Gist options
  • Save xxxzhi/7643017 to your computer and use it in GitHub Desktop.
Save xxxzhi/7643017 to your computer and use it in GitHub Desktop.
single traversal random algorithm
/*
* SingleTraveralRandom.h
*
* Created on: 2013年11月25日
* Author: houzhi
*/
#ifndef SINGLETRAVERALRANDOM_H_
#define SINGLETRAVERALRANDOM_H_
#include<time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
class SingleTraveralRandom {
public:
SingleTraveralRandom(int select_nums);
int SingleTraversal();
void Init();
private:
int Random(int max);
size_t cur_index;
//选择多少
size_t select_nums;
};
SingleTraveralRandom::SingleTraveralRandom(int select_nums){
this-> select_nums = select_nums;
cur_index = 0;
}
inline int SingleTraveralRandom::Random(int max){
srand((unsigned )time(NULL));
int res = rand() % max;
return res;
}
/**
* 初始化
*/
inline void SingleTraveralRandom::Init(){
cur_index = 0;
}
int SingleTraveralRandom::SingleTraversal(){
cur_index ++;
if(cur_index <= select_nums ){
return cur_index-1;
}else{
int random = Random(cur_index);
if(random <=select_nums){
return random-1;
}else{
return -1;
}
}
}
#endif /* SINGLETRAVERALRANDOM_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment