mardi 1 novembre 2016

Achieve same random number sequence on different OS with same seed

Is there any way to achieve same random int numbers sequence in different operating system with same seed? I have tried this code:

std::default_random_engine engine(seed);
std::uniform_int_distribution<int> dist(0, N-1);

If I ran this code on one machine multiple times with same seed, sequence of dist(engine) is the same, but on different operating system sequence is different.




java exponential random number generator

I am trying to generate exponentially distributed random numbers btw 0-100. But when I use the below function my variables is assigned value more than even 200 but they should be btw 0-100. Anybody has any idea?

here is my code;

Random rng3 = new Random(85);
ExponentialGenerator exponentialGenerator = new ExponentialGenerator(0.012, rng3 ); 

and the general usage is ;

public ExponentialGenerator(NumberGenerator<Double> rate,
                            Random rng)

Parameters:

rate - The rate (lamda) of the exponential distribution.

rng - The source of randomness used to generate the exponential values.




Insert Parameters on Random.org and take the result on Python [on hold]

How can I insert the Min and Max parameters on https://www.random.org/, generate the result and put it as a variable in the code, all this in Python?




Random number Powerpoint as slide change

I need a random number generator in Powerpoint to create a new value into a text box every time I open a new slide. In other words each slides will contain a text box, when the presentation start I need a random value to be placed automatically into the text box. I tried with VBA and OnSlideShowPageChange() but without success, can someone give me a hint ?




Generate a million unique random 12 digit numbers

I need to generate close to a million(100 batches of 10000 numbers) unique and random 12 digit codes for a scratch card application. This process will be repeated and will need an equal number of codes to be generated everytime.

Also the generated codes need to be entered in a db so that they can be verified later when a consumer enters this on my website. I am using PHP and Mysql to do this. These are the steps I am following

a) Get admin input on the number of batches and the codes per batch
b) Using for loop generate the code using mt_rand(100000000000,999999999999)
c) Check every time a number is generated to see if a duplicate exists in the db and if not add to results variable else regenerate.
d) Save generated number in db if unique
e) Repeat b,c, and d over required number of codes
f) Output codes to admin in a csv

Code used(removed most of the comments to make it less verbose and because I have already explained the steps earlier):

$totalLabels = $numBatch*$numLabelsPerBatch;
// file name for download
$fileName = $customerName."_scratchcodes_" . date('Ymdhs') . ".csv";
$flag = false;
$generatedCodeInfo = array();
// headers for download
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Type: application/vnd.ms-excel");
$codeObject = new Codes();
//get new batch number 
$batchNumber = $codeObject->getLastBatchNumber() + 1;
$random = array();
for ($i = 0; $i < $totalLabels; $i++) {
    do{
        $random[$i] = mt_rand(100000000000,999999999999); //need to optimize this to reduce collisions given the databse will be grow
    }while(isCodeNotUnique($random[$i],$db));
    $codeObject = new Codes();
    $codeObject->UID = $random[$i];
    $codeObject->customerName = $customerName;
    $codeObject->batchNumber = $batchNumber;
    $generatedCodeInfo[$i] = $codeObject->addCode();

    //change batch number for next batch
    if($i == ($numLabelsPerBatch-1)){$batchNumber++;}


    //$generatedCodeInfo[i] = array("UID" => 10001,"OID"=>$random[$i]);
    if(!$flag) {
        // display column names as first row
        echo implode("\t", array_keys($generatedCodeInfo[$i])) . "\n";
        $flag = true;
    }
    // filter data
    array_walk($generatedCodeInfo[$i], 'filterData');
    echo implode("\t", array_values($generatedCodeInfo[$i])) . "\n";


}


function filterData(&$str)
{
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}

function isCodeNotUnique($random){
    $codeObject = new Codes();
    $codeObject->UID = $random;
    if(!empty($codeObject->getCodeByUID())){
        return true;
    }
    return false;
}

Now this is taking really long to execute and I believe is not optimal.

1) How can I optimize so that the unique random numbers are generated quickly?
2) Will it be faster if the numbers were instead generated in mysql or other way rather than php and if so how do I do that?
3) When the db starts growing the duplicate check in step b will be really time consuming so how do I avoid that?
4) Is there a limit on the number of rows in mysql?




Randomly select element from array and assign it to list

I have a char array(A) and int array(B). I want to select elements randomly from array A and concatenate them with elements of array B from first element. Add the concatenated elements to a string list.

 List<string> AB_Concat = new List<string>();
        Random random = new Random();
        for(int i=0;i<26;i++)
       AB_Concat[i] = Convert.ToString(A[random.Next(i, A.Length)]) + Convert.ToString(B[i]);




        for (int i = 0; i < 26; i++)
            Console.Write(AB_Concat[i] + " ");




lundi 31 octobre 2016

Regex Python - Modify random generated string

I need to read from file, two strings, one 'static' string from file, and one random dynamically generated one, which is also written on a file.

Then, replace one character in the random generated string with another random one.

And repeat the process. Until I get the "static" string which is on a file, in this case "THIS IS A STRING".

I'm pretty lost trying to achieve this, this is what I have so far:

import string
import random
import os
import re

file = open('file.dat', 'r')
file=file.read().split(',')
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

if os.path.exists('newfile.txt'): os.remove('newfile.txt') else: file = open("newfile.txt", "w") file.write(id_generator()) file.close() if re.search(r"THIS IS A STRING", file): print("success!")

I'm trying to achieve this with re module, since it should read character by character, finding it's position in the random generated string.

Not just comparing but also finding the position of the matching characters (if any)

The file.dat file contains the THIS IS A STRING string, which I call the 'static' one, it doesn't changes, it should be matched by the random generated ones process .

The newfile.txt prints the random generated string.

So, in a nutshell, how can I read the string on file.dat character by character, and same goes for the random generated string on newfile.txt?

I hope I've explained myself.