samedi 1 juin 2019

How to generate 4 different random numbers in C++

I am making Bulls and Cows assignment from Bjarne Stroustrup's "Programming Principles and Practice Using C++" book (p. 130, exercise 13) and I want program to generate four different integers in the range 0 to 9 (e.g., 1234 but not 1122)

I made a vector to store numbers and a function which generates 4 numbers and adds them to vector, but numbers might be the same and I can't return numbers to main function

#include "../..//..//std_lib_facilities.h"

vector<int> gen4Nums(vector<int> secNum)
{
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range 

    secNum.clear();
    for (int i = 0; i < 4; i++)
    {
        secNum.push_back(distr(eng));
        cout << secNum[i];
    }
    return secNum;
}

int main()
{
        vector<int> secNum;
        gen4Nums(secNum);   
}

I expect to return 4 different random numbers to the main function




Uniform generation of permutation with repetition at most k times?

We have set {1, 2, 3, ...,n} of numbers. We want to generate permutation of length of m created of those numbers with repetition of each number at most $k$ times.

If we assume n=5, k=2, m=3, then we could receive: {3,3,1}, but not {3, 3, 3} as 3 in the second example happens to be three times in output, which is more than k.

Is there a way of uniform generation of such permutation in a fast way?

I tried two different solutions.

First:

1) generate random permutation with repetition, there is n^m different permutations.

2) check if this is a correct permutation (if it does not contain more than k times the same number

3) if yes, then return, else go to 1)

Python snippet:

import numba
import numpy as np


@numba.jit(nopython=True)
def gen_sequence1(n, k, m):
    result = np.random.randint(0, n, (1, m))[0]
    while not is_correct(result, k):
        result = np.random.randint(0, n, (1, m))[0]
    return result


@numba.jit(nopython=True)
def most_frequent(iter):
    return np.bincount(iter).max()


@numba.jit(nopython=True)
def is_correct(pruf, k):
    return most_frequent(pruf) <= k

Second method:

Generate random integer, add it to sequence only if it didn't show up before k times. Optimized version of these words is below presented (written in Python). Python snippet:

def gen_seq(n, d, m):
    choices = list(range(n))
    degrees = [0] * n
    result = []
    k = n - 1
    for i in range(m):
        rand = np.random.randint(0, k)
        result.append(choices[rand])
        degrees[choices[rand]] += 1
        if degrees[choices[rand]] == d:
            choices[rand], choices[k] = choices[k], choices[rand]
            k -= 1
    return result

Problem is that the first method is very slow for n=30, m=28, d=1 it needs 10^9 times to generate sequence, which is pretty obvious.

The second one is not generating uniform permutations (some have bigger probabilities than others).

Do you have any ideas how one could generate such sequence fast and uniformly?




Pseudo random number generator using the Blum Blum Shub algorithm

We're required to implement Blum Blum Shub Algorithm in a pseudo random number generator. I tried searching for implementations in c# to get an idea but was unsuccessful. Some methods we're required to implement are not clear enough (or maybe I'm not getting exactly what they're asking).

Any help would be greatly accepted!

First, I tried following the logic of the question. With little progress, I began searching on-line for better explanations and possibly finding implementations to better understanding. Finally, I attempted to fill in some of the requested methods with what I thought made sense.

static long seed = 6367859;
static long p = 3263849;
static long q = 1302498943;
static long m = p*q;

// Generates a random bit i.e. 0 or 1 using the Blum Blum Shub Algorithm and the Least Significant Bit
private byte generateRandomBit(){ }

// Method to generate a single positive 32 bit random number using the Blum Blum Shub Algorithm.
// The generateRandomBit() method is used to generate the random bits that make up the random number
// Not complete!!
public int GenerateNextRandomNumber()
{
    int nextRandomNumber = (int)((p * seed + q) % m);

    seed = nextRandomNumber;

    return nextRandomNumber;
}

// Generates a random number between min and max.
// The GenerateNextRandomNumber() method must be used to generate the initial random number which must then be manipulated (if necessary) to be between min and max
public int GenerateNextRandomNumber(int min, int max){ }

// Uses the GenerateNextRandomNumber Method to generate a sequence of Random Numbers between the minimum and the maximum value using the Blum Blum Shub Algorithm
public int[] GenerateRadmonSequence(int n, int min, int max)
{
    int[] sequence = new int[n];

    for (int i = 0; i < n; i++)
    {
        int randNum = Math.Abs(GenerateNextRandomNumber());

        randNum = min + randNum % (max + 1 +- min);
        sequence[i] = randNum;
    }

    return sequence;
}

The result should be to generate a sequence of numbers from min to max.




C# Am I doing "Bays & Durham Randomization by Shuffling" correctly?

I tried to improvise a random number generator by using the "Bays & Durham Randomization by Shuffling" algorithm. I followed a tutorial online and made this code:

 public int[] GenerateRandomSequence_Improved(int n, int min, int max)
 {
       int[] seq = new int[n];
       for(int i = 0; i < n; i++)
       {
           int rand = GenerateNextRandomNumber(min, max);

           rand = min + rand % (max + 1 - min);
           seq[i] = rand;
       }
       return seq;
 }

I wanna know if I did it correctly or not..

EDIT: This is the code for the GenerateNextRandomNumber method

public int GenerateNextRandomNumber(int min, int max)
{
       return cSharpRNG.Next(min,max);
}




How to generate a random sample of points from a 3-D ellipsoid using Python?

I am trying to sample around 1000 points from a 3-D ellipsoid, uniformly. Is there some way to code it such that we can get points starting from the equation of the ellipsoid?




Generate Array Randomly only Once a Day

I want to generate random array but once a day and should not be repeated next day or on same date next month. Here is my code...

function Rand1($min, $max, $quantity) {
srand(date("ymd"));
$first = array("A", "B", "C", "D", "E", "F", "G", "H");
shuffle($first);
return array_slice($first, 0, $quantity);
}
$three_array=Rand1(0,8,3);
$three_string=implode(" ",$three_array);
echo $three_string;

It generate D H F for the same day and next day and so on. If I remove this - srand(date("ymd")) then it shows randomly on each page load. But it string should not change for the 24 hours, like this:

If date is 01/06/2019 - D H F

If date is 02/06/2019 - A E B (Any other random order)

If date is 01/07/2019 - B D F (Any other random order)

How can I get this without database or cookie, it should be based on PHP.




random number generation in fortran

I have been trying to generate the random numbers in fortran, now I want to recall it and want to generate it in the range of (-1,1)

plus, it will be helpful to show put inside on random seed!