Last active
June 28, 2019 09:27
-
-
Save tayyebi/af474bc0c0820d7ed1bdbb6a64f0d23a to your computer and use it in GitHub Desktop.
@digikala Rand7() challenge
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
// Author: Mohammad R. Tayyebi (@tayyebi) | |
// Date: June 28 2019 | |
// A simple solution to @Digikala challenge: | |
// > You are given a function Rand6() which | |
// > will generate a random integer (with flat distribution) | |
// > from 1 to 6. | |
// > Using Rand6(), write a function Rand7() which will | |
// > generate a random number from 1 to 7 with FLAT DISTRIBUTION. | |
#include <iostream> | |
#include <cstdlib> | |
#include <ctime> | |
using namespace std; | |
// Fund max function | |
#define max(a, b) (((a) > (b)) ? (a) : (b)) | |
// Declare rand6() | |
int rand6(); | |
// Declare rand7() | |
int rand7(int (&votes)[7], int &global_max); | |
int main() | |
{ | |
// Generate true random | |
srand(static_cast<unsigned int>(clock())); | |
// Init votes | |
int votes [7] = {0}; | |
// Init the output global_max | |
int global_max = 0; | |
// Print out random between 1 ~ 7 | |
cout << rand7(votes, global_max); | |
// Exit the program | |
return 0; | |
} | |
// Not our job | |
int rand6() | |
{ | |
// Return random number between 1 ~ 6 | |
return rand() % 6 + 1 ; | |
} | |
// Solution | |
int rand7(int (&votes)[7], int &global_max) | |
{ | |
// Election | |
int local_max_count = -1; | |
for (int i = 0; i < 7 ; i ++) | |
if (votes[i] == global_max) | |
{ | |
local_max_count ++; | |
// call the rand6() | |
votes[i] += rand6(); | |
} | |
// Find the array maximum | |
for (int i = 0; i < 7 ; i ++) | |
global_max = max (global_max, votes[i]); | |
// If there is a single global maximum return the index | |
if (local_max_count == 0) | |
for (int i = 0; i < 7 ; i ++) | |
if (votes[i] == global_max) | |
return i + 1; | |
// Recursivly run the func until global max | |
rand7(votes, global_max); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python: