Created
November 25, 2013 15:28
-
-
Save xxxzhi/7643017 to your computer and use it in GitHub Desktop.
single traversal random algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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