Skip to content

Instantly share code, notes, and snippets.

@tayyebi
Last active June 28, 2019 09:27
Show Gist options
  • Save tayyebi/af474bc0c0820d7ed1bdbb6a64f0d23a to your computer and use it in GitHub Desktop.
Save tayyebi/af474bc0c0820d7ed1bdbb6a64f0d23a to your computer and use it in GitHub Desktop.
@digikala Rand7() challenge
// 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);
}
@tayyebi
Copy link
Author

tayyebi commented Jun 28, 2019

Python:

from random import randint
import matplotlib.pyplot as plt

def rand6():
    return randint(1, 6)

def rand7(votes, global_max):
    local_max_count = -1
    for i in range(0,7):
        if votes[i] == global_max:
            local_max_count += 1
            votes[i] += rand6()
    for i in range(0,7):
        global_max = votes[i] if votes[i] > global_max else global_max
    if local_max_count == 0:
        for i in range(0, 7):
            if votes[i] == global_max:
                return i + 1
    return rand7(votes, global_max)

# main()
I = []
for i in range(1, 1000):
    votes = [0,0,0,0,0,0,0]
    global_max = 0
    I.append(rand7(votes, global_max))

plt.plot(I)
plt.ylabel('Randoms')
plt.show()

@tayyebi
Copy link
Author

tayyebi commented Jun 28, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment