NC319. 用rand5()实现rand7()
描述
示例1
输入:
1
输出:
[2]
示例2
输入:
2
输出:
[1,5]
示例3
输入:
3
输出:
[1,3,7]
C 解法, 执行用时: 12ms, 内存消耗: 920KB, 提交时间: 2022-03-09
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * srand((unsigned int)time(NULL)); already set * rand5() is defined *@return a random integer in the range 1 to 7 * * * C语言声明定义全局变量请加上static,防止重复定义 */ int rand5() { return rand()%5+1; } int rand7() { // write code here int ret = 5 * rand5() + rand5() - 5; if(ret > 21) return rand7(); return ret % 7 + 1; }
C++ 解法, 执行用时: 13ms, 内存消耗: 908KB, 提交时间: 2022-05-03
#include <random> std::random_device rd; // Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<> distrib(1, 5); class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * rand5() is defined * @return a random integer in the range 1 to 7 */ int rand5() { return distrib(gen); } int rand7() { // write code here int x = (rand5() - 1) * 5 + rand5() - 1; while (x > 20) { x = (rand5() - 1) * 5 + rand5() - 1; } return x % 7 + 1; } };
C++ 解法, 执行用时: 14ms, 内存消耗: 928KB, 提交时间: 2022-03-07
#include <random> std::random_device rd; // Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<> distrib(1, 5); class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * rand5() is defined * @return a random integer in the range 1 to 7 */ int rand5(){ return distrib(gen); } int rand7() { // write code here int x=22; while(x>21){ x=(rand5()-1)*5+rand5(); } return x%7+1; } };
C++ 解法, 执行用时: 14ms, 内存消耗: 1028KB, 提交时间: 2022-04-07
#include <random> std::random_device rd; // Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<> distrib(1, 5); class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * rand5() is defined * @return a random integer in the range 1 to 7 */ int rand5(){ return distrib(gen); } int rand7() { // write code here int x = (rand5() - 1)* 5 + rand5() - 1; while(x > 20) { x = (rand5() - 1) * 5 + rand5() - 1; } return x % 7 + 1; } };
C++ 解法, 执行用时: 14ms, 内存消耗: 1036KB, 提交时间: 2022-06-23
#include <random> std::random_device rd; // Will be used to obtain a seed for the random number engine std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd() std::uniform_int_distribution<> distrib(1, 5); class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * rand5() is defined * @return a random integer in the range 1 to 7 */ int rand5(){ return distrib(gen); } int rand7() { // write code here int ret = rand5()+(rand5() -1)*5; while (ret>21) { ret = rand5()+rand5()*5; } return ret%7 + 1; } };