vendredi 31 mars 2017

How to create thread-safe random number generator in C using rand_r()?

I was asked to not use rand() because they were not "thread safe" and to also use a different seed value each time. I found examples on GitHub using a seed value like this:

unsigned int seed = time(NULL);

That only has a precision by seconds. Since the program runs in under 1 second, I end up getting the same random number every instance.

How would I fix this algorithm so that it only uses rand_r() or any other "thread safe" methods to generate 10 random numbers?

int main()
{
    for(int i = 0; i < 10; i++){
        int random;
        unsigned int seed = time(NULL);
            random = 1 + (rand_r(&seed)% 10);
        printf("%d\n",random);
    }
 return 0;
}




C# Random() instance in web farm

I'm running an application on multiple web servers that communicate with a distributed in-memory caching cluster, where I generate exclusive lock IDs on the application server -- the problem is that in high concurrency of parallel execution it is possible that more than one execution across all servers would generate the same pseudo random lock value.

The idea would be to initiate a single instance of the Random class per application pool using an incrementing seed within the distributed caching cluster, and to re-seed the randomizer after each helper method to generate a thread safe random number has reached a specific number of invocations.

Interested to see what thoughts you would have on this.




How to randomly rank each item from a text box

I have text boxes where the user gets to fill them up with names. What I'm trying to do is code in javascript that will Randomly rank these names from 1 to 5.

My friend told me to use "let orderList=....... +resultOrder.string()" but I couldn't get it to work properly.

<form>

    <input type="text"  id="LoverName1" name="name">

    <input type="text" id="LoverName2" name="Name2">

    <input  type="text" id="LoverName3" name="Name3">

    <input type="text" id="LoverName4" name="Name4">

    <input type="text" id="LoverName5" name="Name5">
</form>




I need to randomly list 5 names that the User chooses

I have text boxes where the user gets to fill them up with names. What I need is a code is javascript that will Randomly rank these names from 1 to 5. Thanks!

<form>

    <input type="text"  id="LoverName1" name="name">

    <input type="text" id="LoverName2" name="Name2">

    <input  type="text" id="LoverName3" name="Name3">

    <input type="text" id="LoverName4" name="Name4">

    <input type="text" id="LoverName5" name="Name5">
</form>




What is the Probability distribution of product of two cosine function?

I have two random variable X and Y which are uniformly distributed in the interval [-pi, pi]. I want to know what will be the probability distribution of cos(X)cos(Y)?




Java Random - set seed to get expected results

Is there a way, to calculate a seed for a java.util.Random instance, to force a specific (start-) behaviour?

For example: I want to calculate one or more (maybe 'all' ?) seeds, so that the first three numbers it generates are x, y, z. Is there a reasonable way to do this?




How to randomly select letters in Java?

I am learning java, and my assignment now is to simulate a chess notation. I have done random int codes, but not sure how to make a random letter code, and the thing is I only need to choose randomly letters from A to H, I have seen random all 26 letter generators, but could not work my way to understand how to generate only A to H. My other concern is will I be able to store char and ints in a matrix [k][8] or do I have to initialise it in a special way? The idea is to create the a class and later try and randomly generate chess notation. At this stage the notations does not have to make sense.

Here is what i used for int random

import java.util.Random;

static Random rnd = new Random();
static int rnd(int A, int B) { 
    return A+rnd.nextInt(B-A+1);

Also how can i make random selection from specified letters that will represent the chess figures?

I don't need exact codes a push to the right direction will be more then enough




jeudi 30 mars 2017

Cannot convert object of type 'list' to a numeric value

I am making a pyomo model, where i want to use random numbers for my two dimensional parameters. I put a small python script for random numbers that looks exactly what i wanted to see for my two dimensional parameter. I am getting a TypeError: Cannot convert object of type 'list'(value =[[....]] to a numeric value. in my objective function. Below is my objective function and random numbers script.

model.obj = Objective(expr=sum(model.C[v,l] * model.T[v,l] for v in model.V for l in model.L) + \
            sum(model.OC[o,l] * model.D[o,l] for o in model.O for l in model.L), sense=minimize)

import random
C = [[] for i in range(7)]
for i in range(7):
     for j in range(5):
        C[i]+= [random.randint(100,500)]
model.C = Param(model.V, model.L, initialize=C)

Please let me know if someone can help fixing this.




Random Pivot(QuickSort) not sorting correctly

This is a quick sort algorithm with a random pivot. It is not sorting the array correctly and I cannot figure out why. Would anyone be able to point out any mistakes I made? I don't know if I screwed up in a place or if there is something just wrong somewhere. Thanks in advance.

import java.util.*;

public class QuickRand
{
    public static <T extends Comparable<? super T>> void quickSort(T[] array, int n)
    {
        quickSort(array, 0, n-1);
    }

    public static <T extends Comparable<? super T>> void quickSort(T[] array, int first, int last)
    {
        if (first < last)
        {
            // create the partition: Smaller | Pivot | Larger
            int pivotIndex = partition(array, first, last);

            // sort subarrays Smaller and Larger
            quickSort(array, first, pivotIndex - 1);
            quickSort(array, pivotIndex + 1, last);
        }
    }

    private static <T extends Comparable<? super T>> int partition(T[] a, int first, int last)
    {
        Random r = new Random();
        int pivotIndex = first + r.nextInt(last - first + 1); //random pivot
        T pivot = a[pivotIndex];

        // determine subarrays Smaller = a[first..endSmaller]
        //                 and Larger  = a[endSmaller+1..last-1]
        // such that elements in Smaller are <= pivot and 
        // elements in Larger are >= pivot; initially, these subarrays are empty

        int indexFromLeft = first; 
        int indexFromRight = last; 

        boolean done = false;
        while (!done)
        {
            // starting at beginning of array, leave elements that are < pivot; 
            // locate first element that is >= pivot
            while (a[indexFromLeft].compareTo(pivot) < 0)
                indexFromLeft++;

            // starting at end of array, leave elements that are > pivot; 
            // locate first element that is <= pivot

            while (a[indexFromRight].compareTo(pivot) > 0 && indexFromRight > first)
                indexFromRight--;

            // Assertion: a[indexFromLeft] >= pivot and 
            //            a[indexFromRight] <= pivot.
            if (indexFromLeft < indexFromRight)
            {
                swap(a, indexFromLeft, indexFromRight);
                indexFromLeft++;
                indexFromRight--;
            }
            else 
                done = true;
        } // end while

        // place pivot between Smaller and Larger subarrays
        swap(a, pivotIndex, indexFromLeft);
        pivotIndex = indexFromLeft;

        return pivotIndex; 
    }  // end partition

    private static void swap(Object [] a, int i, int j)
    {
        Object temp = a[i];
        a[i] = a[j];
        a[j] = temp; 
    } // end swap
}




Generate a random number in MS WORD VBA

In MS EXCEL VBA I have for many years used

lowerbound=some figure
upperbound=some other figure
m=Int((upperbound-lowerbound+1)*Rnd +lowerbound)

I put this in a WORD macro and it did not work; it gave the same number for m every time I ran it.

Can anyone assist please




Generate Random Number Between 0 and 12 In For Loop (C#)

I'm currently having an issue with randomly generating fake data stored across several arrays. The loop works fine, and all the data is being pulled correctly, however the data is the same for every iteration of the loop which is driving me insane; it doesn't matter if I loop 100 times or 1,000,000 times, it will all be the same.

Random r = new Random(123456);
for (int i = 0; i < 100; i++) {
     temp.Name = names[r.Next(0, 4)];
     temp.Status = status[r.Next(0, 12)];
}

All variables are local to the method, and are created before the loop begins. At the end of each iteration the temp variable is stored within a list of it's type for later access. Everything else works just fine and I'm thinking that maybe it's just the small ranges that are causing the issue. I originally initialized 'r' with an empty constructor to simply use system time as the seed but even that was to no avail.

The random values do change, but only once at page load; for example, if I refresh the page or if I restart the debugging process the values change to a set of different values, however the values are still the same throughout the 100 'temp' objects in the list; should I be re-initializing the 'temp' variable with each iteration of the loop as well?




"Uncaught SyntaxError: missing ) after argument list" math.random and math.floor

With this code I'm getting a "Uncaught SyntaxError: missing ) after argument list"

    var rndm = console.log(Math.random() * 10; Math.floor(rndm))

I am trying to recreate something my friend made a while ago to do a giveaway. I need a random number between 1 and 4 but I was just testing out Math.random and Math.floor first and was planning on figuring out the rest.




C#: I need to input a value, and extract information of an object

I'm programming in Unity, using the language C#.

I need to be able to input a random value, search through a list of objects in a class, and find the one with an ID that matches the random value. To make things more complicated, I also have to extract all information I can on that item. I have the random input, which is the following line of code:

firstCard = Random.Range (1, 18);

Then I have the cards:

public class Card {
public int CardID;
public string element;
public int value;
public string color;

public Card (int cardids, string elementals, int values, string coloring) {
    this.CardID = cardids;
    this.element = elementals;
    this.value = values;
    this.color = coloring;
    }
}

public class CardList : MonoBehaviour {
    public Card a = new Card(1,"Fire",3,"Blue");
    //Other cards appear here.
}

So if the random number returns 1, I want it to retun "Fire", 3, and "Blue" because the CardID matches the random number. These two groups of code are in two different files, if that changes anything.




Send a random number output every x seconds in to COM1 in Batch

I'm trying to send a random number to my program that listens to a virtual COM port for testing reasons. I though a quick .batch would do it since I'm too lazy to do

echo 54646 > COM1

Every time.

What I developed (using stackoverflow example) is:

:loop
%RANDOM%
echo %RANDOM% > COM1
sleep 1
goto loop

However, it doesn't run as wanted and outputs:

C:\Users\user\Desktop>goto loop

C:\Users\user\Desktop>13599
'13599' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\user\Desktop>echo 20524  1>COM1

C:\Users\user\Desktop>sleep 10
'sleep' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\user\Desktop>goto loop

C:\Users\user\Desktop>11259
'11259' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\user\Desktop>echo 2973  1>COM1
^CTerminate batch job (Y/N)?

Questions:

  • What's wrong with my code?

  • Why is the script running the command as echo 20524 1>COM1? Where does the '1'> come from?




Taking a sample of a CSV?

I have a program converting a CSV to a valid JSON file.

I would like to change it to take a random subset of my CSV file (as its 50k lines) and make a JSON from this. Here is my code so far -

import csv
import json

csvfile = open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv', 'r')
jsonfile = open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w')

with open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w') as f:
    json.dump(rows, f)

What's the most efficient way to do this?

Thanks.




c++ - having trouble in random numbers

This program generates random numbers and lets the user guess it. I'm using Geany as IDE and it highlights this as an error: Error message: error: 'rand' was not declared in this scope

the_number = rand() % 101 + 1;

Code (not working):

#include <iostream>
using namespace std;
int main()

{
using namespace std;

int the_number;
int guess;
int tries=8;

the_number = rand() % 101 + 1;

cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;

for (tries = 8; tries++;)
{
    if (guess == 8)
    {
        cout << "You guessed it!";
        cout << "And it only took you: "<< tries;
    }
    else if (guess < the_number)
    {
        cout << "Higher";
        tries++;
    }


    else if (guess > the_number)
    {
        cout << "Lower";
        tries++;
    }

    else
         cout << "That's not even in range!";
    return 0;
   }
}




How create spring with random port?

Spring-boot has random port generation as described here. But this example about web configuration. Is there a way to generate random port number, check that it is avalible, and reserve it for bean creation? E.g. something like that:

@Bean
public void myBean (@Value("${somePort}") String port) {
    return new MyBean(port);
}

Please note, that spring has random properties like ${random.int} but this does not garante that port is free to use.




Tensorflow: running same computational graph with different random samples efficiently

In Tensorflow, the computational graph can be made to depend on random variables. In scenarios where the random variable represents a single sample from a distribution, it can be of interest to compute the quantity with N separate samples to e.g. make a sample estimate with less variance.

Is there a way to run the same graph with different random samples, reusing as many of the intermediate calculations as possible?

Possible solutions:

  • create the graph and the random variable inside a loop. Con: makes redundant copies of quantities that don't depend on the random variable.
  • Extend the random variable with a batch dimension. Con: a bit cumbersome. Seems like something TF should be able to do automatically.
  • Maybe the graph editor (in .contrib) can be used to make copies with different noise, but I'm unsure whether this is any better than the looping.
  • Ideally, there should just be an op that reevaluates the random variable or marks the dependency as unfulfilled, forcing it to sample a new quantity. But this might very well not be possible.

Example of the looping strategy:

import tensorflow as tf
x = tf.Variable(1.)
g = []
f = lambda x: tf.identity(x) #op not depending on noise 
for i in range(10):
    a = tf.random_normal(()) # random variable
    y = tf.pow(f(x)+a*x, 2) # quantity to be repeated for diff samples
    g += [y]

#here, the mean is the quantity of interest
m = tf.reduce_mean(g)

#the variance demonstrates that the samples are different
v = tf.reduce_mean(tf.map_fn(lambda x: tf.square(x-m), tf.stack(g)))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(g))
    print('variance: {}'.format(sess.run(v)))

if f(x) is an expensive function, I can only assume that the loop would make a lot of redundant calculation.




PHP Array Select Random Value on Refresh

I have Submit button on Page. Once I click each time it should give random different result.

I have below array code

$qty = 10;
$array = array(4 => 2, 6 => 5, 7 => 10, 8 => 1, 10 => 5);
$array = arsort($array);
echo "<pre>";
print_r($array);
//array_rand($array);
exit;

Array pair is Customer & It's Quantity. I need to compare $qty with array's highest value. If it matches then take that value out & print out final result.

It is not necessary to assign 100% qty to each customer. But in the end 10 qty should assign overall.

So output can be

1st Click on Submit Button

Array
(
    [7] => 10
)

2nd Click on Submit Button

Array
(
    [7] => 2
    [6] => 2
    [10] => 2
    [4] => 2
    [8] => 2
)

3rd Click on Submit Button

Array
(
    [7] => 5
    [6] => 2
    [10] => 3
)




I want my random to be less random [duplicate]

Let's say i have a list. I want to iterate over that list and add 2 random strings from it to an empty list. However, because this is a random choice, there is a possibility that the same string will be picked twice (As it is crucial not to pop or delete from that list the selected item). something like this:

import random

emptylist = []
somelist = ["a","b","c","d","e",]

for item in somelist:
    emptylist.append(random.choice(somelist))
    emptylist.append(random.choice(somelist))

How do i make sure that it won't pick, for example, "a" twice? I know it is possible in many ways but im looking for the most efficient one.




Choose random data from an Array in Swift

I would like to create a new Array of 3 random values pulled from this list to be used in two other view controllers. Not sure how to assign the Array so those values are accessible.

class WorkoutDataSource {
var allWorkouts:[Workout]

init() {
    allWorkouts = []
    let bh1 = Workout(title: "Figure 8s - Clockwise", workoutText: "Clockwise around each leg.", color:  UIColor.flatNavyBlueColorDark())
    allWorkouts.append(bh1)
    let bh2 = Workout(title: "Figure 8s - Counter Clockwise", workoutText: "Counter Clockwise around each leg.", color:  UIColor.flatNavyBlue())
    allWorkouts.append(bh2)
    let bh3 = Workout(title: "Dribble Left Handed", workoutText: "Low and Powerfull.", color:  UIColor.flatTealColorDark())
    allWorkouts.append(bh3)
    let bh4 = Workout(title: "Dribble Right Handed", workoutText: "Low and powerfull", color:  UIColor.flatTeal())
    allWorkouts.append(bh4)
    let bh5 = Workout(title: "Around Both Feet", workoutText: "With feet together, circles around ankles-waist-head, work up & down, the full length of body.", color:  UIColor.flatSkyBlueColorDark())
    allWorkouts.append(bh5)
    let bh6 = Workout(title: "Spider Dribble", workoutText: "feet apart, 1 dribble with each hand in front, then 1 dribble with each hand in back. ", color:  UIColor.flatSkyBlue())
    allWorkouts.append(bh6)
    let bh7 = Workout(title: "Helicopter", workoutText: "1 hand in front, 1 hand in back – move your hands from front to back while catching the ball between your legs.", color:  UIColor.flatGreenColorDark())
    allWorkouts.append(bh7)
    let bh8 = Workout(title: "Scissors - Legs Not Moving", workoutText: "One leg forward and one leg back. Dribble between your legs low and fast.", color:  UIColor.flatGreen())
    allWorkouts.append(bh8)
    let bh9 = Workout(title: "Behind the Back", workoutText: ".",color:  UIColor.flatGray())
    allWorkouts.append(bh9)
    let bh10 = Workout(title: "Fingertip Squeeze", workoutText: ".",color:  UIColor.flatPink())
    allWorkouts.append(bh10)
}


func getWorkOuts() -> [Workout]{

return allWorkouts
}

}

Thank you




mercredi 29 mars 2017

C#: Most efficient way to generate lots of "good" random ranged integers

I have a program wherein I need to generate a huge quantity of random integers, all within a specific range.

I've written a little benchmark tool that will test various ways to generate random integers and populate an array of ints with the results. The methods I've benchmarked are as follows:

  1. Simple Random.Next() without ranging, populating array using a for loop*
  2. Random.Next(x,y), with ranging, populating array using a for loop
  3. Random.next(x,y), with ranging, populating array using LINQ
  4. RNGCryptoServiceProvider, directly populating a byte[] array, no conversion to ints, no ranging*
  5. RNGCryptoServiceProvider, converting all values to int, without range constraints, using a for loop*
  6. RNGCryptoServiceProvider, generating 4x the desired random numbers as bytes, converting each value to a double between 0 and 1, then using multiplication/addition to range the value while converting to int. All in a for loop.
  7. RNGCryptoServiceProvider, same as #6 but using LINQ
  8. RNGCryptoServiceProvider, same as #6, but only generating n+3 bytes and using 8-bit offsets rather than 32-bit offsets to generate the floats
  9. RNGCryptoServiceProvider, bytes converted to ints and ranged using the modulus operator, in a for loop
  10. RNGCryptoServiceProvider, same as #9 but with 4x the bytes generated, each int converted from 32-bits rather than just 8 bits, also ranged with modulus
  11. RNGCryptoServiceProvider, same as #10 but rejecting values that might create an uneven distribution.
    • I do this by figuring out the largest multiple within the integer space. So for example, if working with 8-bit values, and we desire numbers from 1 to 10, we know that there are 10 possible values. We take 255 (maximum value of a byte) % 10 to get 5, and subtract 5 from 255 to get 250. Now, any random number we get that is >= 250 is rejected and a new number is generated in its place.

I haven't thought of any other strategies so far.

There are problems with most of these strategies:

  • Any strategy ending with a * does not enforce the range for the ints and thus the results are unacceptable.
  • The LINQ methods are always slower than their respective for loop methods. (This is a given.)
  • Random.Next() is not necessarily "cryptographically" secure or "good enough" randomness.
  • Method 8 uses overlapping offsets (e.g. each double is composed of three of the bits from the previous double, thereby affecting randomness) In this method, the double for value 0 is extracted from bytes 0-3 of the random pool; the double for value 1 is taken from bytes 1-4, and so on.
  • The methods using the modulus operator other than method 11 will not necessarily produce an even distribution. For example, if you need values betweeen 1 and 10 and you are working with 8-bit byte valuies, the numbers 1 through 6 will occur slightly more likely than 7 through 10, because the numbers 250-255 would map to 1-6 after modulus and ranging. These values would be 4% more likely to occur in any given value.

Here are the results of a benchmark run, running on a Xeon E5-2620v1, which has AES instruction support:

Generate 50,000,000 random numbers in the range 1 to 10...
 *1: 1.10 sec 45,335,560 num/sec [Random.Next, unranged ints, for loop]
 +2: 1.90 sec 26,266,911 num/sec [Random.Next, ranged ints, for loop]
 +3: 3.23 sec 15,476,958 num/sec [Random.Next, ranged ints, LINQ]
 *4: 0.11 sec 475,817,979 num/sec [RCSP.GetBytes, direct to byte array]
 *5: 0.44 sec 114,849,593 num/sec [RCSP.GetBytes, unranged ints, for loop]
  6: 3.11 sec 16,090,076 num/sec [RCSP.GetBytes, 32-bit offsets, ranged ints, for loop]
  7: 4.09 sec 12,215,084 num/sec [RCSP.GetBytes, 32-bit offsets, ranged ints, LINQ]
 +8: 2.59 sec 19,289,457 num/sec [RCSP.GetBytes, 8-bit offsets, ranged ints, for loop]
 +9: 0.42 sec 118,669,825 num/sec [RCSP.GetBytes, ranged ints via modulus, for loop]
+10: 0.99 sec 50,311,904 num/sec [RCSP.GetBytes, ranged ints from 32-bits via modulus, for loop]
 11: 1.10 sec 45,335,515 num/sec [RCSP.GetBytes, ranged ints from 32-bits via modulus with check, for loop]

*unacceptable result
+undesirable result

Method 11 turns out to be the fastest method and appears to give me what I want.

So my questions are:

  1. Is there any more efficient way to generate a large quantity of random, ranged integers in C#?
  2. Is my method of rejecting numbers on the tail end of the valid range valid for keeping the numbers evenly distributed?

Here's the code for method 11:

    int rnCount = 50000000;
    DateTime startTime;
    TimeSpan endTime;
    RNGCryptoServiceProvider rcsp = new RNGCryptoServiceProvider();

    int min = 1;
    int max = 10;

    int randomNumbers = new int[rnCount];

    // method 11: with RNGCryptoServiceProvider, ranged ints, 32 bits per int, ranged with modulus and checked
    byte[] randomBytes = new byte[rnCount * 4];
    rcsp.GetBytes(randomBytes);
    startTime = DateTime.Now;
    // The maximum value we should allow, i.e. the maximum multiple of the desired range delta
    uint maxValue = uint.MaxValue - (uint.MaxValue % (max-min));

    for (int i = 0; i < randomNumbers.Length; i++)
    {
        uint thisNumber = BitConverter.ToUInt32(randomBytes, i * 4);
        while (thisNumber >= maxValue)
        {
            byte[] newNumber = new byte[4];
            rcsp.GetBytes(newNumber);
            thisNumber = BitConverter.ToUInt32(newNumber, 0);
        }
        randomNumbers[i] = (int)(thisNumber % max) + min;
    }
    timeTaken = DateTime.Now - startTime;
    Console.WriteLine("+11: {0:F2} sec {1:N0} num/sec [RCSP.GetBytes, ranged ints from 32-bits via modulus with check, for loop]", timeTaken.TotalSeconds, rnCount / timeTaken.TotalSeconds);




Simulating finding a randomly chosen number by asking binary questions

As a question in an assignment, I have been asked to write an Octave function that simulates 1000 experiments of finding a Random Variable X with alphabet {0, 1, 2, 3} and pmf:

Px(0) = 1/8

Px(1) = 1/4

Px(2) = 1/2

Px(3) = 1/8

by asking a sequence of binary, "yes" or "no" questions.

I have determined that the optimal sequence of binary questions asked to find the value of X is to simply ask "Is X = p?" where p are the possible values, in order of decreasing probabilty.

So the optimal sequence would be:

  1. Is X = 2?

    If not:

  2. Is X = 1?

    If not:

  3. Is X = 0?

    If not then X = 3

This is the function I have written:

function x = guessing_experiment(probabilities, n)
  % generates n simulations of finding a random number in an alphabet by asking binary questions,
  % where 'probabilities' is a list of the probabilities per number in the order the questions will be asked

  num_Qs = zeros(1,n);                            % allocate array of size n for number of questions asked per experiment
  [num_col, alphabet_size] = size(probabilities); % get size of alphabet

  for i = 1:n                                     % generate n experiments
    Qs = 0;                                       % number of questions asked in this experiment
    for j = 1:alphabet_size - 1                   % iterate through questions
      question = rand;                            % generate random number in range [0, 1]
      Qs++;                                       % incremenet number of questions asked
      if (question <= probabilities(j))           % if question produces a "yes" answer
        break;
      endif
    endfor
    num_Qs(i) = Qs;                               % store number of questions asked for this experiment
  endfor

  x = mean(num_Qs);                               % calculate mean number of questions asked over the n experiments 

 end

Which is called as guessing_experiment([1/2, 1/4, 1/8, 1/8], 1000) where the array is the probability of each question producing a "yes" answer, in order of how they are to be asked, and n is the number of experiments.

Asking these questions should produce an average number of questions of 1.75, but my program is always producing an average of ~1.87. Where is my script in error?




Plotting realisations of random Gaussian fields using RandomFields package

For some reason when I try to using the plot() function to visualise the output of the RFsimulate() function in the RandomFields package, the output is always an empty plot.

I am just using the example code included in the help file:

## first let us look at the list of implemented models
RFgetModelNames(type="positive definite", domain="single variable",
                iso="isotropic") 

## our choice is the exponential model;
## the model includes nugget effect and the mean:
model <- RMexp(var=5, scale=10) + # with variance 4 and scale 10
  RMnugget(var=1) + # nugget
  RMtrend(mean=0.5) # and mean

## define the locations:
from <- 0
to <- 20
x.seq <- seq(from, to, length=200) 
y.seq <- seq(from, to, length=200)

simu <- RFsimulate(model=model, x=x.seq, y=y.seq)
str(simu)

Which gives:

Formal class 'RFspatialGridDataFrame' [package ""] with 5 slots
  ..@ .RFparams  :List of 5
  .. ..$ n         : num 1
  .. ..$ vdim      : int 1
  .. ..$ T         : num(0) 
  .. ..$ coordunits: NULL
  .. ..$ varunits  : NULL
  ..@ data       :'data.frame': 441 obs. of  1 variable:
  .. ..$ variable1: num [1:441] 4.511 2.653 3.951 0.771 2.718 ...
  ..@ grid       :Formal class 'GridTopology' [package "sp"] with 3 slots
  .. .. ..@ cellcentre.offset: Named num [1:2] 0 0
  .. .. .. ..- attr(*, "names")= chr [1:2] "coords.x1" "coords.x2"
  .. .. ..@ cellsize         : Named num [1:2] 1 1
  .. .. .. ..- attr(*, "names")= chr [1:2] "coords.x1" "coords.x2"
  .. .. ..@ cells.dim        : int [1:2] 21 21
  ..@ bbox       : num [1:2, 1:2] -0.5 -0.5 20.5 20.5
  .. ..- attr(*, "dimnames")=List of 2
  .. .. ..$ : chr [1:2] "coords.x1" "coords.x2"
  .. .. ..$ : chr [1:2] "min" "max"
  ..@ proj4string:Formal class 'CRS' [package "sp"] with 1 slot
  .. .. ..@ projargs: chr NA

... so data has been simulated, but when I call

plot(simu)

I end up with something like this:

e.g. Empty plot

Can anyone tell what going on here?!




RANDOM_NUMBER: how to fix the random number sequence

I coded a Monte Carlo method that makes many calls to RANDOM_NUMBER. I would like it to use either a fixed random number sequence, which in the end is supposed to have the algorithm to always give the same answer, OR a different sequence at each run.

In order to achieve this, before any call to RANDOM_NUMBER, I do this, just once:

IF (ISRDNSD) THEN
  CALL init_random_seed()
ELSE
  CALL RANDOM_SEED(SIZE=G)
  allocate(SEED(1:G))
  SEED = SEEDINIT
  CALL RANDOM_SEED(PUT=SEED)
END IF

The ELSE being the "fixed random sequence" code. Since SEEDINIT is a constant PARAMETER, I expected the Markov Chain to be the same at each run; but it is not the case; i.e., the random number sequence appears to be different each time.

Any clue?




what is the fastest way to randomly select some numbers in a range that contains a given set of numbers?

Here is the function I want

random_select(contain_list, ttl_num, sample_num)

There're ttl_num integers from 0 to ttl_num-1 to select from, I want to return a list of sample_num integers, where numbers provided in contain_list have to be in the list, and other numbers are selected randomly.

I have to do this query very often, every time with a different contain_list, but ttl_num, sample_num and the length of contain_list are the same for all the queries.

Currently what I'm doing is, first generate a set of ttl_num integers, subtract contain_list from the set, randomly select some numbers with no replacement from the rest, then concatenate it with the contain_list to get the result.

I believe this is not the fastest way, any better thoughts?

It's okay to use global variables if needed.




mardi 28 mars 2017

Does .NET connection pooling affect RAND calls?

The T-SQL RAND function is documented to continue the sequence from the original seed value for the same database connection.

For example, if you open a new window in SSMS and run select rand(7),rand(),rand() and then in a separate query (but the same window and therefore the same connection) run select rand(),rand(),rand(), take note of all six values. Repeat the two calls in the same order to see that the exact same values are generated, proving that the original seed value of 7 determines the latter 3 random results, even though they're run as a separate statement, because they're run on the same connection.

I was wondering if this could impact seemingly separate calls in the .NET framework because of connection pooling. For example, if 3 mobile device users all made a server call in quick succession to pick a random number, and .NET used the same connection for all three, and the users were able to identify the whole sequence from those 3 numbers (being familiar with the implementation of rand), then could they predict additional numbers that may subsquently be generated for other users in different regions because of how RAND is tied to the connection? Or, does .NET reset the connection between calls in some way that actually resets the RAND seed when one is not specified.

(I don't use RAND, I use crypt_gen_random, so this is a purely academic question).




How can I simply generate a random integer number between specific intervals?

I want to simply generate a random number for instance between 1 and 10 with Fortran. But I cannot achieve this. For example, When I wrote a do loop for a variable which desired to be random, It wasn't be generated as random for every loop.




Can we conclude a set might not be random by checking its subset?

Set A includes 1000 numbers. I checked that half of the numbers in this set is even.

I extracted subset B from set A as follow: any number in set A which starts with 1 is also in set B. (All numbers in B start with 1).

I checked that more than half of the numbers in set B is even.

Half of the numbers in A are even so should we expect the same for B? But more than half of B is even. So can conclude that set A is not random?

If 60% of B are even, can we still conclude A is not generated random?

How if 70% of B are odd?




INSERT INTO table_1 SELECT FROM table_2 WHERE condition ORDER BY random value from table 3 (not table_2)

I have 3 tables:

Table_1 is flux_zilnic: Table_2 is tableta: tableta And table_3 is birouri: birouri

I have the PHP code:

function search_in_birouri()
    {
        $connection = db_connect();
        $query = mysqli_query($connection, "SELECT * FROM birouri WHERE disponibilitate = 'LIBER' AND locatie_actuala = 'Orhideea' AND pauza = '' AND closed_program = '' AND feedback = '' ORDER BY id ASC") or die(mysqli_error($connection));
        $row = mysqli_fetch_assoc($query);

        $username = $row['username'];
        $nr_birou = $row['nr_birou'];
        $disponibilitate = $row['disponibilitate'];
        $locatie_actuala = $row['locatie_actuala'];
        $pauza = $row['pauza'];
        $closed_program = $row['closed_program'];
        $feedback = $row['feedback'];
        $inregistrare_clienti = $row['inregistrare_clienti'];

        return array('username' => $username, 'nr_birou' => $nr_birou, 'disponibilitate' => $disponibilitate, 'locatie_actuala' => $locatie_actuala, 'pauza' => $pauza, 'closed_program' => $closed_program, 'feedback' => $feedback, 'inregistrare_clienti' => $inregistrare_clienti);
        unset($connection);
    }

function search_in_tableta()
    {
        $connection = db_connect();
        $query = mysqli_query($connection, "SELECT * FROM tableta WHERE locatie = 'Orhideea' ORDER BY `tableta`.`id` ASC") or die(mysqli_error($connection));
        $row = mysqli_fetch_assoc($query);

        $clientID = $row['clientID'];
        $nume_client = $row['nume_client'];
        $data_inregistrare = $row['data_inregistrare'];
        $ora_inregistrare = $row['ora_inregistrare'];
        $locatie = $row['locatie'];
        $status = $row['status'];

        return array('clientID' => $clientID, 'nume_client' => $nume_client, 'data_inregistrare' => $data_inregistrare, 'ora_inregistrare' => $ora_inregistrare, 'locatie' => $locatie, 'status' => $status);
        unset($connection);
    }

function start_working()
    {
        $username = cauta_in_birouri();
        $nr_birou = cauta_in_birouri();
        $disponibilitate = cauta_in_birouri();
        $paused = cauta_in_birouri();
        $closed_program = cauta_in_birouri();
        $feedback = cauta_in_birouri();
        $inregistrare_clienti = cauta_in_birouri();
        $clientID = cauta_urmatorul_client();
        $nume_client = cauta_urmatorul_client();
        $connection = db_connect();
        $data_curenta = date_create('');
        $ora_alocare = date_format($data_curenta, 'H:i');
        $username = $username['username'];
        $nr_birou = $nr_birou['nr_birou'];
        $clientID = $clientID['clientID'];
        $nume_client = $nume_client['nume_client'];
        $disponibilitate = $disponibilitate['disponibilitate'];
        $paused = $paused['pauza'];
        $closed_program = $closed_program['closed_program'];
        $feedback = $feedback['feedback'];
        $inregistrare_clienti = $inregistrare_clienti['inregistrare_clienti'];
        //
        if($nume_client == NULL)
        {
            //Salveaza in log
            $linie_text = "NU DETECTEZ NICIUN CLIENT ÎNREGISTRAT ÎN ORHIDEEA";
            $new_line = "==> ";
            $handle = fopen('loguri/actiuni_comandate.txt','a+');
            fwrite($handle, $new_line . $linie_text . " (" . $ora_alocare . ")" . "<br>" . "\r\n");
            fclose($handle);
        } else if($nume_client != NULL && $disponibilitate == 'LIBER' && $paused == NULL && $closed_program == NULL && $feedback == NULL && $inregistrare_clienti == NULL)
        {
            $query = mysqli_query($connection,"
                INSERT INTO `flux_zilnic` (motiv,nume_client,clientID,data_inregistrare,ora_inregistrare,status_alocare,ora_alocare,status_preluare,ora_preluare,status_rezolvare,ora_rezolvare,operator,birou,fisa_service,locatie_actuala,fise_cu_probleme,observatii,status)
                SELECT  '',nume_client,clientID,data_inregistrare,ora_inregistrare,'ALOCAT','$ora_alocare','','','','','$username','$nr_birou','',locatie,'','',status
                FROM `tableta` WHERE locatie = 'Orhideea' ORDER BY id ASC LIMIT 1") or die("NU AM ALOCAT URMĂTORUL CLIENT DEOARECE: <br>" . mysqli_error($connection));

            $queryTwo = mysqli_query($connection,"UPDATE `birouri` SET `disponibilitate` = 'OCUPAT' WHERE username = '$username'") or die("ÎN ORHIDEEA NU AM SCHIMBAT BIROUL ÎN STATUS OCUPAT, DEOARECE: <br>" . mysqli_error($connection));

            $queryThree = mysqli_query($connection,"DELETE FROM `tableta` WHERE locatie = 'Orhideea' ORDER BY id ASC LIMIT 1") or die("ÎN ORHIDEEA NU AM ȘTERS CLIENTUL DE PE TABLETĂ DIN CAUZA UNEI ERORI: <br>" . mysqli_error($connection));

            if($query && $queryTwo && $queryThree) 
            {
                //Salveaza in log
                $linie_text = "AM ALOCAT CLIENTUL " . $nume_client . " CĂTRE " . $username . " ÎN ORHIDEEA";
                $new_line = "==> ";
                $handle = fopen('loguri/actiuni_comandate.txt','a+');
                fwrite($handle, $new_line . $linie_text . " (" . $ora_alocare . ")" . "<br>" . "\r\n");
                fclose($handle);
            }
        } else
        {
            //Salveaza in log
            $linie_text = "NU ESTE DISPONIBIL NICIUN BIROU ÎN ORHIDEEA. NU POT SĂ ALOC CLIENTUL " . $nume_client;
            $new_line = "==> ";
            $handle = fopen('loguri/actiuni_comandate.txt','a+');
            fwrite($handle, $new_line . $linie_text . " (" . $ora_alocare . ")" . "<br>" . "\r\n");
            fclose($handle);
        }
        unset($connection);
    }

According to $query from start_working() I am taking values from table 2 and table 3 and put them together in table 1.

As you can see in search_in_birouri(), this function returns me values from table 3 ORDER BY id ASC.

This means that next thing will happen: 1. Function start_working() - $query will copy all values from table_2 and only nr_birou and username from table_3 and put them together in table_1. 2. Function start_working() - $queryTwo will update table_3 ... 3. Function start_working() - $queryThree will delete one row from table_2

Everything work just fine and no problems.

Except I want to select a random $nr_birou (and the username which belongs to it) from table_3 and put it in table_1 combined with values from table_2.

How can I do that? How to copy values from table_2 with random nr_birou and username from table_3 into table_1?

I really, really tried to explain the best I could.




Pseudo Random Number Generator using LFSR in VHDL

I'm having a bit of trouble creating a prng using the lfsr method. Here is my code:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity pseudorng is
Port ( clock : in STD_LOGIC;
       reset : in STD_LOGIC;
       Q : out STD_LOGIC_VECTOR (7 downto 0);
       check: out STD_LOGIC);

       constant seed: STD_LOGIC_VECTOR(7 downto 0) := "00000001";
end pseudorng;

architecture Behavioral of pseudorng is

signal temp: STD_LOGIC;
signal Qt: STD_LOGIC_VECTOR(7 downto 0);

begin

PROCESS(clock)
BEGIN

IF rising_edge(clock) THEN
IF (reset='1') THEN Qt <= "00000000";
ELSE Qt <= seed; 
END IF;
temp <= Qt(4) XOR Qt(3) XOR Qt(2) XOR Qt(0);
--Qt <= temp & Qt(7 downto 1);

END IF;
END PROCESS;

check <= temp;
Q <= Qt;

end Behavioral;

Here is the simulation I have ran: prng sim

Firstly, the check output is just there so I can monitor the output of the temp signal. Secondly, the line that is commented out is what is causing the problem.

As can be seen from the simulation, on the first rising edge of the clock, the Qt signal reads the seed. However, and this is my question, for some reason the temp signal only XORs the bits of the Qt signal on the second rising edge of the clock. It remains undefined on the first clock pulse. Why is that? If it operated on the first rising edge right after the Qt signal reads the seed, then I could uncomment the line that shifts the bits and it would solve my problem. Any help would be much appreciated!

Here is the test bench if anyone cares:

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity tb_pseudorng is
end tb_pseudorng;

architecture bench of tb_pseudorng is

COMPONENT pseudorng
      Port ( clock : in STD_LOGIC;
      reset : in STD_LOGIC;
      Q : out STD_LOGIC_VECTOR (7 downto 0);
      check: out STD_LOGIC);
END COMPONENT;

signal clock1: STD_LOGIC;
signal reset1: STD_LOGIC;
signal Q1: STD_LOGIC_VECTOR(7 downto 0);
signal check1: STD_LOGIC;

begin

mapping: pseudorng PORT MAP(
clock => clock1,
reset => reset1,
Q => Q1,
check => check1);

clock: PROCESS
BEGIN
clock1<='0'; wait for 50ns;
clock1<='1'; wait for 50ns;
END PROCESS;

reset: PROCESS
BEGIN
reset1<='0'; wait for 900ns;
END PROCESS; 

end bench;




Creating Key/Value JSON object with random integers and Flask

I recently was asked for homework to expand upon a Flask application so that a route is created which will roll two dice and return the outcome as a JSON object. I thought I had completed the program correctly but was disappointed to find out that what my code is producing is not a JSON object? Would anyone know how I would take the code below and return the dice roll as a key/value pair? At this point in time when I visit the rolldice route the output is Jsonified as the sum of the two dice rolls. I'm not sure how I can turn this into a key/value pair. Any help is appreciated, thanks again.

Here is my code:

from flask import Flask
from flask import jsonify
app = Flask(__name__)

import json
import random

@app.route('/')
def hello_world():
    return 'Hello World!'

# Create a route and function for rolling dice.
@app.route('/rolldice')
def dieobject():
    # Define rollcount
    rollcount = []
    # Define the number of times we will roll two dice.
    for i in range(0, 1):
        # Define rolling two dice.
        two_dieobject = random.randint(1, 6) + random.randint(1, 6)
        # Take output of our dice roll and pass it to rollcount.
        rollcount.append(two_dieobject)
    # Return the value of rollcount as JSON Data.
    # Data will be presented as one integer which is the sum of two dice rolls.
    return jsonify(rollcount)

if __name__ == '__main__':
    app.debug = True
    app.run()




probability modifiers for Math.random()

I'd like to know what the best or most accepted method of creating probabilities is. I've done some research and found some interesting questions and answers on the Math.random() topic such as:

How random is JavaScript's Math.random?

and

Generating random whole numbers in JavaScript in a specific range?

I'm looking for a simple way to modify the probability that a value will be true or not using Math.random()

For example, I know that Math.floor(Math.random() * 2) is a useful method for generating a 1 nearly 50% of the time:

-Math.random() generates a random number between 0 (inclusive) and 1 (exclusive)

-If the number generated is < 0.5, this number multiplied by 2 will still be less than 1, so this number .floor() returns a 0

-If the number generated is > 0.5, this number multiplied by 2 will be greater than 1, so this number .floor() returns a 1

I wanted to skew the probability of getting a 1 using a "modifier" and this is as close as I have to come to getting the desired probability...

Every time you run the code snippet the console prints the percentage of hits. As you can see they are almost accurate, but not quite. I came up with the exponent modifying function by trial and error. Is there any way I can make this more accurate?

var youHit = Math.floor(Math.random() * 2);
var totalTries = 0;
var hits = 0;

var pointNine = 0.9; // you want 90% of tries to hit
var pointEight = 0.8;// you want 80% of tries to hit 
var pointSeven = 0.7;// you want 70% of tries to hit
  
function probCheck(modifier) {
  var exponent = 1 + (1 - modifier) + (1 - modifier)*10;
  for (var x = 0; x < 100; x++) {
     youHit = Math.floor((Math.pow(modifier, exponent)) + (Math.random() * 2));
     totalTries += 1;
     if (youHit) {
        hits += 1;
     } 
  }
  console.log("final probability check: " + hits / totalTries);
};

 probCheck(pointNine);
 probCheck(pointEight);
 probCheck(pointSeven);
<script src="http://ift.tt/1oMJErh"></script>



How to generate a random 8 digit string and verify that it was not generated already in feasible amount of time?

I need to generate a random string 8 digit long and next time when I generate the random number make sure it was not already generated. If we simply think I have to store every confirmation number generated and every time I try to generate a new one, verify that it was not already generated by looking at the stored values. But if the already generated numbers are a lot, it can take significant time to validate that. What is the best way to approach this problem?




Can I generate a random float on the whole space ?

I am trying to generate a random number that range from Number.MIN_VALUE to Number.MAX_VALUE, but the following algorithm fails due to buffer overflows (I guess ) :

var randFloat = Math.floor(Math.random() * (Number.MAX_VALUE - Number.MIN_VALUE)) + Number.MIN_VALUE

Is there any way to do it ?




java program compiling but not executing

\the above is not executing can anyone tell the reason.
import java.util.Random; class Randomnum { public static void main(String args[]) { int a; Random d=new Random(); for(int i=1;i<=10;i++) { a=d.nextInt(3); System.out.println("rabdom numbers--->"+a); } } }




Rest-Assured. Random "Cannot invoke method getAt() on null object" Error when running multiple test suites in Maven

I have a couple of test suites using Rest-Assured, JUnitParams, and JUnit4, this suites share a @Test method that has this portion of code, the code randomly gets an item from the JSON response that has a "children_uuids" value in them:

            // Test case
            response = serviceCaller.call();

            Boolean success = response.then().extract().path("Success");
            assertTrue(success);

            // get random content data
            Integer contentAmmount = response.body().path("Contents.Contents.size()");
            Random randomGenerator = new Random();
            int randomInt = randomGenerator.nextInt(contentAmmount);
            while (response.body().path(
                    String.join("", "Contents.Contents[", Integer.toString(randomInt), "].children_uuids"))
                    .toString().isEmpty()) {
                randomInt = randomGenerator.nextInt(contentAmmount);
            }

            contentTitle = response.then().extract()
                    .path(String.join("", "Contents.Contents[", Integer.toString(randomInt), "].title"));
            contentUuid = response.then().extract()
                    .path(String.join("", "Contents.Contents[", Integer.toString(randomInt), "].uuid"));
            contentChildrenUuid = response.body().path(
                    String.join("", "Contents.Contents[", Integer.toString(randomInt), "].children_uuids.item[0]"));
            System.out.println(contentTitle + "#" + contentChildrenUuid);

The problem is, that if i run only one test suite with the command:

mvn test -Dtest=TestSuite01#testCase01

The test runs fine, but if i run all the suites with the command:

mvn test -Dtest=TestSuite*#testCase01

I get the following error randomly in some suites:

java.lang.IllegalArgumentException: Cannot invoke method getAt() on null object
Results :

Tests in error: 
  TestSuite01>ApiServiceCommon.testCase01:1023 » IllegalArgument

Thanks in advance!




Runs test for a pre-specified length of runs

I want to conduct runs test on my data observations but for a specified length say for runs of length 5 and test for its significance. The R functions runs.test in both randtests and lawstat packages give critical values and no. of runs but I specifically want to test for the statistically significant appearances of runs of (say) size 5 in my data. Is there any package/function in R that does that?




Mersenne Twister in python

In an attempt to better understand the Mersenne Twister (MT) I decided to convert it into python. Here you can run the code and see the commented C source code at the bottom.

The code runs but I'm not getting the expected output. Based on the C output here The first numbers I should be getting are 1067595299 955945823 477289528 4107218783 4228976476 but I'm getting 2594155707 3648022958 667752806 3967333545 3535325493.


Side note:

I found another implementation on SO saying they got the same output as C here but when I run it in python2 or python3 (xrange->range and no L in hexadecimal) the output also doesn't match Cs expected, it gives 0.817330 0.999061 0.510354 0.131533 0.035416 instead of the expected 0.76275443 0.99000644 0.98670464 0.10143112 0.27933125. ... If you're wondering changing my code to give a result in [0,1) interval gives 0.6039989429991692 0.8493715333752334 0.15547331562265754 0.9237168228719383 0.823132110061124 which is also different from both of these results.


Why does this python code not give the same output as the C code? Did I incorrectly implement something?

Code:

class RandomGenerators:
  # period parameters
  N = 624
  M = 394
  MATRIX_A = 0x9908b0df    # constant vector a
  UPPER_MASK = 0x80000000  # most significant w-r bits
  LOWER_MASK = 0x7fffffff  # least significant r bits

  def __init__(self):
    self.mt = [None]
    self.mti = self.N + 1

  '''
  initialize by an array with array-length
  init_key is the array for initializing keys
  key_length is its length
  slight change for C++, 2004/2/26
  '''
  def init_by_array(self, init_key, key_length):
    #int i, j, k;
    self.init_genrand(19650218)
    i,j = 1,0
    k = self.N if self.N > key_length else key_length
    #k = (self.N > key_length ? self.N : key_length)
    #for (; k; k--) {
    while k > 0:
      self.mt[i] = (self.mt[i] ^ ((self.mt[i-1] ^ (self.mt[i-1] >> 30)) * 1664525)) + init_key[j] + j # non linear 
      self.mt[i] &= 0xffffffff # for WORDSIZE > 32 machines 
      i+=1
      j+=1
      if i >= self.N:
        self.mt[0] = self.mt[self.N-1]
        i = 1
      if j >= key_length:
        j = 0
      k-=1

    k = self.N-1
    #for (k=N-1; k; k--) {
    while k > 0:
      self.mt[i] = (self.mt[i] ^ ((self.mt[i-1] ^ (self.mt[i-1] >> 30)) * 1566083941)) - i # non linear 
      self.mt[i] &= 0xffffffff # for WORDSIZE > 32 machines 
      i += 1
      if i >= self.N:
        self.mt[0] = self.mt[self.N-1]
        i=1
      k-=1

    self.mt[0] = 0x80000000 # MSB is 1; assuring non-zero initial array

  # initializes mt[N] with a seed
  def init_genrand(self,s):
    self.mt[0] = s & 0xffffffff
    self.mti = 1
    while self.mti < self.N:
      self.mt.append(1812433253 * (self.mt[self.mti-1] ^ (self.mt[self.mti - 1] >> 30)) + self.mti)
      self.mt[self.mti] &= 0xffffffff
      self.mti += 1

  # generates a random number on [0,0xffffffff]-interval
  def genrand_int32(self):
    y = 0
    mag01=[0x0, self.MATRIX_A]
    if self.mti >= self.N: # generate N words at one time
      kk = 0
      if self.mti == self.N + 1: # if init_genrand() has not been called,
        self.init_genrand(5489) # a default initial seed is used

      while kk < self.N - self.M:
        y = (self.mt[kk] & self.UPPER_MASK) | (self.mt[kk+1] & self.LOWER_MASK)
        self.mt[kk] = self.mt[kk+self.M] ^ (y >> 1) ^ mag01[y & 0x1]
        kk += 1

      while kk < self.N - 1:
        y = (self.mt[kk] & self.UPPER_MASK) | (self.mt[kk+1] & self.LOWER_MASK)
        self.mt[kk] = self.mt[kk+(self.M-self.N)] ^ (y >> 1) ^ mag01[y & 0x1]
        kk += 1

      y = (self.mt[self.N-1] & self.UPPER_MASK) | (self.mt[0] & self.LOWER_MASK)
      self.mt[self.N-1] = self.mt[self.M-1] ^ (y >> 1) ^ mag01[y & 0x1]

      self.mti = 0

    y = self.mt[self.mti]
    self.mti += 1

    # Tempering 
    y ^= (y >> 11)
    y ^= (y << 7) & 0x9d2c5680
    y ^= (y << 15) & 0xefc60000
    y ^= (y >> 18)

    return y

  # generates a random number on [0,0x7fffffff]-interval 
  def genrand_int31(self):
    #return (long)(genrand_int32() >> 1)
    return (self.genrand_int32() >> 1)

  # generates a random number on [0,1]-real-interval 
  def genrand_real1(self):
    return self.genrand_int32() * (1.0 / 4294967295.0)
    # divided by 2^32-1 

  # generates a random number on [0,1)-real-interval 
  def genrand_real2(self):
    return self.genrand_int32() * (1.0 / 4294967296.0)
    # divided by 2^32 

  # generates a random number on (0,1)-real-interval 
  def genrand_real3(self):
    return ((self.genrand_int32()) + 0.5) * (1.0 / 4294967296.0)
    # divided by 2^32 

  # generates a random number on [0,1) with 53-bit resolution
  def genrand_res53(self):
    a, b = self.genrand_int32()>>5, self.genrand_int32()>>6 
    return(a * 67108864.0 + b) * (1.0 / 9007199254740992.0)

r = RandomGenerators()
init = [0x123, 0x234, 0x345, 0x456]
length = 4
r.init_by_array(init, length)
for i in range(10):
  print('mt: '+str(r.genrand_int32()))




Creating random integers with Flask and presenting them as a JSON object

I'm having some trouble and I'm lost on what to do with this. I need to create a Flask route which will simulate rolling two dice, then once the dice roll has been completed the output is a JSON object. I've been chipping away at this all morning and I'm hitting a brick wall. If anyone can offer me some help and/or suggestions I'd really appreciate it.

This is my code so far:

from flask import Flask
app = Flask(__name__)

import json
import random

@app.route('/')
def hello_world():
    return 'Hello World!'

# Create a route for rolling dice.
@app.route('/rolldice')
def dieobject(n):

    # Define roll count
    rollcount = []
    for i in range(n):

        # Define two dice rolls
        two_dieobject = random.randint(1, 6) + random.randint(1, 6)

        # Take output of pairdice and pass it to rollcount
    rollcount.append(two_dieobject)

    # Set rollcount as Json Data
    jsonData = '{rollcount}'
    jsonToPython = json.loads(jsonData)

    # Return Json data as the dice roll
    return 'jsontoPython'

if __name__ == '__main__':
    app.debug = True
    app.run()

Right now I'm getting a TypeError message stating that dieobject() takes 1 argument, 0 given. However beyond that error I'm not sure I know where I'm going with this code. Again if anyone can offer me some advice I'd really appreciate it, thanks!




How to randomize an array whitout duplicating an integer

For example if we have this:

<?php
$b = array(100);
for ($i = 1; $i <= 100; $i++) {
    $b[$i]=$i;
}
?>

How do we randomize all the numbers without duplicating them?




How do I create string of random length using different calls to random in PL/SQL Oracle Developer?

I am writing a chunk of PL/Code to test a database for a homework assignment. The criteria for what I am working on: b. Email must be less than 20 characters long, and must be a valid format, e.g. having a ‘@’ sign and a ‘.’ sign at the right position.

So I will have a string/varchar that is less than 20. I know that with the Top Level Domain as 3 spaces, the dot, and the at symbol taking up 5 spaces of that length, which leaves 14 spaces. So I thought I could randomly generate a string in the range of 1-14 to fill in the remaining spaces, and make the whole thing less than 20. How would I do this?

Email := dmbs_random.string('U', trunc(dbms_random.value(1,14))||'@'||dmbs_random.string('U', trunc(dbms_random.value(1,14))||'.'||dbms_random.string('U',3)<20;

I know the above is incorrect, but it is just psuedo code of what I am attempting.




lundi 27 mars 2017

Assigning random tuples to a dictionary

Please I need help with this, Thank you.

for i in conflictList:
    d[i] = random.sample(set(domainList),2)

This assigns only a single tuple to the key But i want to assign more than a single tuple, tried this but didnt work

for i in conflictList:
    while len(d[i]) < tup:
        d[i] = random.sample(set(domainList),2)

'tup' represents the number of tuples the user wants do if the user wants 3 tuples, it gives something like this:
(x1,x2): (0,1), (1,2), (1,0)




How to expand the range of a random integer from 1-10 to 1-200

Given a function that produces random integers uniformly in range 1 to 10, how to write a function that produces random integers uniformly in range 1 to 200?




mySQL - Select records based on value in order, then random records in one query

I'm looking to have one mySQL query where I can select all records set to a particular value, then selecting a number of other records from the records left, in a random order.

To explain, here's an example: (MyTable database table)

ID        Name        SomeValue
1         Fred        0
2         Jake        0
3         Jone        1
4         Bill        0
5         Greg        0
6         Thom        2
7         Jane        3
8         Erin        0

So first, I'd want to select all records where SomeValue is more than 0. The appropriate mySQL query for this would be:

SELECT * FROM MyTable WHERE SomeValue > 0 ORDER BY SomeValue DESC

This would return:

7         Jane        3
6         Thom        2
3         Jone        1

Next (in the same query), how would it be possible to select 3 other records at random, from the ones remaining?

So that the end result of records returned looks something like this:

7         Jane        3
6         Thom        2
3         Jone        1
5         Greg        0    // Randomly picked
1         Fred        0    // Randomly picked
8         Erin        0    // Randomly picked




Extract substrings with certain length randomly from a file with Bash

I have multiple text files, and from each file I need to extract random contiguous substrings with a certain length.

For example, I need to extract Five random substrings that consist of 3 contiguous characters each, or 4 random substrings that consist of 20 characters each.

In practice, let's assume this is the content of one of the files

Welcome to stackoverflow the best technical resource ever

so if I want Five random substrings that consist of 3 characters each, I expect an output that looks like this for example:

elc sta tec res rce

Your help would be much appreciated.




Elegant way to control Random Seed if necessary

I have an application that more or less spits out randomly generated data. The short is, we have collections of data (first names, last names, etc.) and we get a random index of each collection and return the data. Right now, there's lots of calls that look like this...

Random rando = new Random()
int index = rando.Next(collection.Count());

Which is fine, and works as intended but what I am interested in introducing is a way to reproduce data sets if the need arises. This can be done by capturing/controlling the seed used to create the Random object. My idea is as follows:

A static class that's essentially a wrapper around a Random object. It looks like this;

public static class SeedGovernor
{
    private static Random random = null;
    private static int masterSeed; 

    public static void SetSeed()
    {
        if (random != null) random = null;
        Random master = new Random();
        masterSeed = master.Next();
        random = new Random(masterSeed);
    }

    public static void SetSeed(int sd)
    {
        if (random != null) random = null;
        masterSeed = sd;
        random = new Random(masterSeed);
    }

    public static int GetMasterSeed()
    {
        return masterSeed;
    }

    public static int GetRandomInt()
    {
        return random.Next();
    }

    public static int GetRandomInt(int max)
    {
        return random.Next(max);
    }

    public static int GetRandomInt(int min, int max)
    {
        return random.Next(min, max);
    }

    public static double GetRandomDouble()
    {
        return random.NextDouble();
    }
}

At run time, we can either define the seed we want to use using SetSeed(int sd) or let it be randomly chosen (but still capturing the seed for future use) using SetSeed(). Then, we simply make calls to the static methods we need.

int index = SeedGovernor.GetRandomInt(collection.Count);

Is there a better, more elegant approach to this? Is there anything wrong with this implementation that I should be concerned with? The testing I've done so far appears to be working as I intended.




C++ algorithm for generating random numbers for atomic systems [on hold]

I'm trying to model an atomic system under the assumption that atoms are just points without any volume. The only criterion is that all atoms must be at least a distance 'r' away from each other and the positions of the atoms should be randomly distributed (generated using a uniform random number generator). Is there an algorithm for this problem using C++?




Optimal seed for Mersenne Twister in C++ 11

My use case is : i need random numbers , but just for graphics (not for cryptography). I need to be able to get the same image (result) for 2 renderings /runs. For example using time() as seed would not create the same result for the next run. So i need a -constant- seed. The documentation for the mersenne twister says that it does not like 0 as seed, it also dislikes certain bit combinations. For such cases it is said to take up to 800000 calls until it delivers good random numbers again. For speed reasons i dont want to spend the overhead of 800000 calls. Ideally i would need some nice and trusted value(s) that i can use as seed directly.




How to test sequence of bits with dieharder?

I'm thinking to perform the Dieharder tests for some number sequences. For now, my code is generating just ones and zeroes. In general, it will generate numbers between a and b. How shall I format the input text for dieharder in order to test my sequence of ones and zeroes? Can I write like this

type: d
count: 100
numbit: 1
1
0
1
1
...

?




randomly create a 4 digit square number on python

Im having a hard time getting anywhere with this question. I need to create a random 4 digit number, ABCD where ABCD is a square by using no arguments.




Amplitude spectrum change after altering phases of Fourier coefficients

I'm trying to generate some random 1d sequences (r) by changing the phases of the Fourier coefficients of a given array (y). I assume the amplitude spectrum of these two sequences (y and r) won't change after doing this, and they indeed don't if I use numpy.fft.fft(), like this:

import numpy as np
import numpy.fft as fft

n=512
x=np.linspace(0,10*np.pi,n)
y=np.sin(x)+2*np.sin(2*x)+2*np.sin(5*x)

#-------------Get Fourier coefficients-------------
cf1=fft.fft(y)
amp1=np.abs(cf1)
theta1=np.angle(cf1)

#-Randomly alter phase keeping amplitude unchanged-
theta2=np.random.normal(0,1.,size=theta1.shape)+theta1
cf2=amp1*np.cos(theta2)+1j*amp1*np.sin(theta2)

#-----------------------IFFT-----------------------
y2=fft.ifft(cf2)

#------------Compare amplitude spectrum------------
cf3=fft.fft(y2)
amp2=np.abs(cf3)

import matplotlib.pyplot as plt
figure=plt.figure()
ax=figure.add_subplot(111)
ax.plot(amp1-amp2,'k-')

plt.show(block=False)

The resultant plot is a random sequence at the order of 1e-13. So effectively unchanged.

But I'm interested in generating random real data rather than complex. Using numpy.fft.rfft() and numpy.fft.ifft() instead, the amplitudes agree at all frequencies but the last one (amp1[-1] and amp2[-1]), and the difference is at the order of 0.1. According to the docs this correspondes to the Nyquist frequency, and the difference doesn't go away if the data size is an odd number. I don't understand what is causing the difference or how should I generate a real valued array with identical amplitude spectrum.

Thanks in advance.




IE11 + Edge 12-13-14 : random JavaScript parsing errors, caused by very long object?

I'm getting reports of JavaScript errors in production (from TrackJS.com) from IE & Edge browsers like:

  • Expected identifier, string or number
  • Unterminated string constant
  • Expected ':', '}' or ';'
  • illegal character

And when I check the error file / line, it's sometimes in "mathiasbynens/he" library (look on GitHub), like here : example 1

And sometimes it's in other parts of the code (like in YUI library). I've got lots of these and they seem completely random (targeting what seems to be valid code) : example 2

The only idea I have would be that IE shits on himself when loading the very long JSON defined in he.js. Have you ever had any issue of this kind ?

Thanks a lot for your help. gnutix




Dice roll with a 50% chance of rolling 6

So I made this method of rolling a dice 100 times with a 50% chance of rolling 6. Basic idea is that there are 50% odd numbers and 50% even numbers between 1 and 6, so if an even number is rolled, system prints 6 else it prints a random number between 1 and 5. Do you think this is correct?

public static void printDiceRolls(Random randGenerator) {
    for (int i=0;i<30;i++) {
        int temp;        
        temp=randGenerator.nextInt(6)+1;
        if (temp%2==0) {
            temp=6;
        }
        else
            temp=randGenerator.nextInt(5)+1;
        System.out.print(" "+temp+" ");
    }
}




dimanche 26 mars 2017

How random is crypto#randomBytes?

How random is crypto.randomBytes(20).toString('hex')?

Easy as that, all I need to know.




Generating random numbers in a file in C++

How do I generate 1019 integer keys in a file that are generated as random numbers from the range [1, 9999] in C++?




Improving the time complexity of this java program

I have to solve the following problem: From an array a of n elements, select k elements such that the sum of the k elements selected is equal to the minimum multiple of f possible for this array and output that minimum possible multiple of f.

Sample test case:
array a = {1,2,3,4,5}
k = 3
f = 5
output:
minimum possible multiple of f = 10

I tried implementing it with my code and it passes 80% of the test cases but fails for the remaining cases because of exceeding the time limit. Please help me solve the time complexity issues of my code:

Selection.java

import java.util.*;

public class Selection
{
  public Selection()
  {
  }
  private static Random rand = new Random();
  public static int minMultiple (int[] input1, int input2, int input3)
  {
    Arrays.sort(input1);
    List<Integer> uniqueSet = new ArrayList<>();
    List<Integer> listOfMultiples = new ArrayList<>();
    int  maxSubSets = (int)Math.pow (2,input1.length);
    for (int i=0; i<maxSubSets; i++)
    {
      // Method to find the minimum possible multiple of user input value for the array 
      uniqueSet = multiple (input1, input2, input3);
      int sum =0;
      for (int j=0; j < uniqueSet.size(); j++)
      {
        sum = sum + uniqueSet.get(j);
      }

      if (sum % input2 == 0)
      {
        listOfMultiples.add (sum);
      }
    }
    if (listOfMultiples.isEmpty())
    {
      return -1;
    }
    Collections.sort (listOfMultiples);
    return listOfMultiples.get(0);
  }
  // Method to return the list of selected random values
  private static List<Integer> multiple (int [] input1, int input2, int input3)
  {
    int  size = input1.length,value =0, index=0;
    List <Integer> list = new ArrayList<>();
    List <Integer> listOfValues = new ArrayList<>();
    while (list.size()<input3)
    {
      // Generating non-repeating random numbers from the array
      index = rand.nextInt(size);
      value = input1[index];
      if (!(list.contains(index)))
      {
        list.add(index);
        listOfValues.add(value);
      }
    }      

    return listOfValues; 
  }
  // Run method
  public final void run (String []args)
  {
    // Entering the number of boxes
    Scanner input = new Scanner (System.in);
    System.out.println ("Enter the size of the array:");
    int arraySize = input.nextInt();

    // Entering the number of balls in each box
    int [] elements = new int [arraySize];
    System.out.println ("Enter the elements of the array:");
    for (int i=0; i<arraySize;i++)
    {
      elements[i] = input.nextInt();
    }
    System.out.println ("Enter the number whose multiple you want");
    int factor = input.nextInt();
    System.out.println ("Enter the no. of elements you want to select.");
    int selection = input.nextInt();
    int result = minMultiple(elements, factor, selection);
    System.out.println ("The minimum possible multiple = "+ result) ;
  }
}

Result.java

public class Result 
{

  private Result() 
  { 

  }

     public static void main (String []args) throws Exception
   {
        Selection value = new  Selection();
        value.run(args);   
   }

}




How does this script generate a random image?

I found this script by accident: http://ift.tt/2ojRbBK

But I have zero idea how it works. There is nothings in the code. If I try to save the page I only get the image save pop up. Can someone give me a hint, because this is absolutely fantastic!




how to make random my article in another article js

I have

    <div id = "primary">
     <div id= "river" class="story-river" role = "main">
      <article id="post-1"></article>
      <article id="post-2"></article>
      <article id="post-3"></article>
      <article id="post-4"></article>
      <article id="post-5"></article>
     </div>
    </div>

I need create function, it should random add my article to my js code to another article. i try that code, but it doesnt work

itemLength = $('#river article').length; //quantity of .items
randomPlace = Math.floor((Math.random()*articleLength)); 

randomArticle = $('<article />',{
    'class':'randomArticle',
    text: randomPlace
}); 

$('#river article').eq(randomPlace).after(randomDiv); 

can someone tell me what wrong?




Scipy Multivariate Normal: How to draw deterministic samples?

I am using Scipy.stats.multivariate_normal to draw samples from a multivariate normal distribution. Like this:

from scipy.stats import multivariate_normal
# Assume we have means and covs
mn = multivariate_normal(mean = means, cov = covs)
# Generate some samples
samples = mn.rvs()

The samples are different at every run. How do I get always the same sample? I was expecting something like:

mn = multivariate_normal(mean = means, cov = covs, seed = aNumber)

or

samples = mn.rsv(seed = aNumber)




samedi 25 mars 2017

How to populate list in SML with random numbers

fun list(n) = 
let 
    val list = []
    val nextInt = Random.randRange (1,100)
    val r = Random.rand (1,1)
    val x1 = nextInt r
in 
if n = 0 then (return list)
else (
    list @ x1
    list(n-1));

 list(50);

I'm wanting to make a recursive function that will populate a list with a given amount of numbers. Those numbers should all be in a random range. However, I'm not very familiar with SMLNJ. I'm getting the error stdIn:15.1 Error: syntax error found at EOF So clearly I have a syntax error somewhere, but I don't see a syntax error (I'm sure its obvious to anyone with experience but to my new eyes I can't find it).




how to print all numbers in a range randomly in C? For example if I give a maximum number as 5, the program has to print 1, 2, 0, 4, 5, 3

how to print all numbers in a range randomly in C? For example if I give a maximum number as 5, the program has to print 1, 2, 0, 4, 5, 3. Where lowest value of range is always 0.




C# random number and greater than operator

I'm trying to generate a random number and give the user 5 tries to guess the right number. I want to compare their guess and tell them if they're too high or too low. VS wont execute and I don't understand why I'm getting errors.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NumberGuessingGame
{
class Program
{
    static void Main(string[] args)

    {
        bool keepGoing = true;
        while (keepGoing)
        {
            Random rnd = new Random();
            int randomnumber = rnd.Next(1, 100);

            //PC tells user to pick a number, display guessed number


            Console.Write("Guess any integer between 1 and 100: ");
            int userentry = Console.ReadLine();


            {

                if (int.Parse(userentry > rnd.Next))
                { Console.WriteLine($"You entered {userentry}. That's too 
high. Try again.");
                    keepGoing = true;

                }

                if (int.Parse(userentry < randomnumber))
                {
                    Console.WriteLine($"You entered {userentry}. That's too 
low. Try again.");
                    keepGoing = true;
                }

                if (int.Parse(userentry = randomnumber))
                {
                    Console.WriteLine($"You entered {userentry}. That's 
right. Good job.");
                    keepGoing = false;
                }

                else (keepgoing) > 5);

                {
                    Console.WriteLine($"You've already tried 5 times. You 
lose.");
                    keepGoing = false;
                }

                else
                {
                Console.WriteLine("That is not a valid number.");
            }


        }
    }
}

}




Android - Random order videos in Youtube playlist

I want to show playlist videos randomly in my android app. But YouTube API 3 doesn't supported. Then I try to do it on my server.

Step 1: Get all videos in playlist and store it in database. Step 2: Generate json file which has same Youtube json Step 3: Get that json from android.

But nothing show up at all.

Any ideas?




Importance of a Random Variable using Entropy or other method

I have a two-dimensional random vector $\mathbf{x} = [x_1, x_2]^T$ with a known joint probability density function (pdf). The pdf is non-Gaussian and the two entries of the random vector are statistically dependent. I need to show that for example $x_1$ is more important than $x_2$, in terms of the amount of information that it carries. Is there a classical solution for this problem? Can I show that for example n% of the total information carried by $\mathbf{x}$ is in $x_1$ and 100-n% is carried by $x_2$?

I assume that the standard way of measuring the amount of information is by calculating the Entropy. Any clues?




Generate unique randoms when we cannot store previous generated randoms

We have an array (of strings for example). The size of this array is not fixed. Now, our machine, selects an element of this array every 3 minutes and shows us. The problem is we don't have a memory to store the elements we have picked before, and every 3 minutes when we select from this array we would like the elements to first cover up the whole array and then they are free to repeat, but they should not repeat before every element has been picked up once. We don't have memory to store the elements picked but we can get the MinutesInDay variable (how many minutes have passed in the day). I believe something could be done using this variable. I am confused and been coding since 6 hours and just now came across this hurdle, please help.




Generation of float`s in certain range

I have a random number generators that generates random integers. However, I need floats in the range (0<=x<=1 or open 0

Would appreciate any help.




Simulate packet loss in UDP in python

I am supposed to simulate a packet loss rate of 10^-2 in a Stop-and-wait protocol, that is 0.01, which means that 1 out of 100 packets transmitted get lost. Suppose I'm sending 1000 packets, how to drop exactly 1 random packet out of the 100 packets sent throughout the transmission ?




vendredi 24 mars 2017

Why this loop stops before it finishes?

I have some problems with this small program for rolling two dices.

Why the program stops before it finishes the loop and instead it asks a loop times "do you want to play again?"

Thank you for your help!

#Program which simulates the rolling of two dice

import random

def rolling_dices(repetitions):
    a = repetitions
    b = 1
while b <= a:
    i = (random.randrange(1,7))
    y = (random.randrange(1,7))
    b +=1
    print(i, y, "\t =>", int(i+y))

    answer = input("do you want to play again? (Y/N)")
    if answer.lower() == "y":
        continue
    else:
        break


rolling_dices(5)




How do I generate a random integer between 1and a variable, or two variables in python? [duplicate]

This question already has an answer here:

I'm trying to generate a random integer between a specified minimum and maximum.

maxlength = input("Maximum length? \n >")
minlength = input("Minimum length? \n >")
import random
length = random.randint(minlength,maxlength) #this line does not work, says the arguments need to be integers
print (length)

Any ideas what I can do?




c++ rand() - possible side-effect of If-statement

I am new to c++ and require your help regarding the rand() command in the following function:

// select_action function
void Agent::select_action(){

    // generate random number between 1 and 100
    int random_number = rand() % 100;

    cout << random_number << endl;

    if(random_number < (100*epsilon)){
        // select random action
        select_random_action();
        // cout << "pick random action" << endl;
    } else{
        // select action according to policy
        select_policy_action();
        // cout << "pick policy action" << endl;
    }
}

The above function has to select different functions dependent on the value of random_number. random_number is generated with the rand() command; I declared srand(time(NULL)) at the start of the main function.

Problem: the value of random_number is not random. If I loop over the above function the value is often the same or sequences through 2-5 different values. If, however, I declare a variable "a" and assign it similarly as random_variable, "a" does generate random values. Heuristically I found out that the first condition in the if statement messes up the randomness of the variable.

Does anyone know how to solve this problem?

Thanks in advance!




How to randomly mix List content under the same indexes

I'm wondering, what is a proper way to mix List<string> list = new List<string>(); content inside the list randomly, without using of another list for random rewriting.

For example, if I got value by index this way:

list[0];
list[1];
list[2];
list[3];

and order output is:

line1
line2
line3
line4

after desired mixing, how is possible to get it under the same indexes, but over the randomly mixed values:

list[0];
list[1];
list[2];
list[3];

to get random order inside the list:

line2
line4
line1
line3




Undefined function or variable 'setdemorandstream'

I am working on a feed-forward neural network analysis using MATLAB. I am getting the following error:

Undefined function or variable 'setdemorandstream'.

Code is as follows:

setdemorandstream(391418381);

Any help in rectifying this error is appreciated.




Generating and storing random numbers in array in c

I have to make an array containing 25 random numbers using a function to define the random numbers but keep getting it to either display only one number at a time (instead of all of them cell by cell) or simply displaying incorrectly i.e. 0. Here is what I have so far.

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

    int get_value (int t);
    int main()
    {
    srand(time(NULL));

    int temp[25], n;
    for(n=0; n<25; n++)
       temp[t] = get_value(n);
       printf("value at cell %d is %d \n", n, temp[25]);
    return 0;
    }

    //function get_value()
    //needs to return rand # <-> 60 and 100 seed rand
    //use rand %40+60 to ensure value is <-> 60 and 100

   int get_value (int t)
   {
       return rand() %(40)+60;
    }




drand48() isn't working in my c program

for some reason neither of my drand48() are returning random numbers between 0-1 like they're supposed to... x was resulting in only the inputted number that is n, and y stayed 0

/// Challenge: Darts
/// circle of radius 0.5 inside a 2x2 square
/// throw darts (x) times and calculate random hits

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main() {
  double n, t, z, a;
  int x, y;

  printf("How many darts do you want to throw? ");
  scanf("%lf", &n);
  printf("Okay, let's throw %lf darts\n. . .\n", n);

  z = 0;
  a = 0;
  t = 0;

  while (t <= n) {
    x = drand48(); /// returns # 0-1
    x = x - 0.5; /// puts it on a graph with domain/range -0.5 - 0.5
    y = drand48();
    y = y - 0.5;

    if ((((x^2) + (y^2))^2) <= 0.25) {
      z = z + 1;
    }
    t = t + 1;
  }
  a = z / (t - 1);
  printf("%lf\n", a);
}

/// remember to compile with gcc darts.c -lm
/// remember to run with ./a.out




How to call upon the last line in a .txt file in batch and use it?

I have a code for a random number generator that looks like this:

@echo off
set cycle=0
:cycle
%random% 2>nul
%random% 2>nul
set /a cycle=%cycle%+1
if "%cycle%"=="2" goto core
goto cycle
:core
set /a num="(10 * %random%) / 32768 + 1"
echo %num% >>rng.log
echo %num%
echo.
rem Code break point, Add on from here.
pause

I have this to generate a random number and put it in a .txt file, but how would I call upon the last number in the file in another batch file:

:Start
@echo off
echo Are you a [b]oy or a [g]irl?
set INPUT=
set /P INPUT=Type input: %=%
If "%INPUT%"=="b" goto boy 
If "%INPUT%"=="g" goto girl
If "%INPUT%"=="B" goto boy
If "%INPUT%"=="G" goto girl
pause
:boy
echo You have chosen boy, are you sure you want to continue? [y/n]
set INPUT=
set /P INPUT=Type input: %=%
If "%INPUT%"=="y" goto classb 
If "%INPUT%"=="n" goto Start
If "%INPUT%"=="Y" goto classb
If "%INPUT%"=="N" goto Start
pause
:girl
echo You have chosen girl, are you sure you want to continue? [y/n]
set INPUT=
set /P INPUT=Type input: %=%
If "%INPUT%"=="y" goto classg 
If "%INPUT%"=="n" goto Start
If "%INPUT%"=="Y" goto classg
If "%INPUT%"=="N" goto Start
pause
:classb
echo What class would you like to be? [s]oldier, [m]ercenary, [w]izard
set INPUT=
set /P INPUT=Type input: %=%
If "%INPUT%"=="s" goto soldier 
If "%INPUT%"=="S" goto soldier
If "%INPUT%"=="m" goto merc
If "%INPUT%"=="M" goto merc
If "%INPUT%"=="w" goto wizard
If "%INPUT%"=="W" goto wizard
pause
:classg
echo What class would you like to be? [g]hetto, [f]abulous, [w]itch, [fe]minist
set INPUT=
set /P INPUT=Type input: %=%
If "%INPUT%"=="g" goto ghetto 
If "%INPUT%"=="G" goto ghetto
If "%INPUT%"=="f" goto fabulous
If "%INPUT%"=="F" goto fabulous
If "%INPUT%"=="w" goto witch
If "%INPUT%"=="W" goto witch
If "%INPUT%"=="fe" goto feminist
If "%INPUT%"=="Fe" goto feminist
If "%INPUT%"=="fE" goto feminist
If "%INPUT%"=="FE" goto feminist
pause
:soldier
echo You woke up in the middle of a battlefield, which way do you want to go? [u]p, [d]own, [l]eft, [r]ight
set INPUT=
set /P INPUT=Type input: %=%
If "%INPUT%"=="u" goto 01 
If "%INPUT%"=="U" goto 01
If "%INPUT%"=="d" goto 0-1
If "%INPUT%"=="D" goto 0-1
If "%INPUT%"=="l" goto -10 
If "%INPUT%"=="L" goto -10
If "%INPUT%"=="r" goto 10
If "%INPUT%"=="R" goto 10
:01
echo To your left you see a soldier laying on the ground with something stuck in his side, which way do you want to go? [u]p, [d]own, [l]eft, [r]ight
Invisible.vbs "rng.bat"
set INPUT=
set /P INPUT=Type input: %=%
If "%INPUT%"=="u" goto 02 
If "%INPUT%"=="U" goto 02
If "%INPUT%"=="d" goto 00
If "%INPUT%"=="D" goto 00
If "%INPUT%"=="l" goto -11 
If "%INPUT%"=="L" goto -11
If "%INPUT%"=="r" goto 11
If "%INPUT%"=="R" goto 11

I want to use the number to randomly generate a monster or no monster at all in every room besides the first one, as I am creating a text-based RPG, how would I make it so only a few numbers generate a certain thing?




Generate random number in range excluding some numbers

Is there a simple way in Python to generate a random number in a range excluding some subset of numbers in that range?

For example, I know that you can generate a random number between 0 and 9 with:

from random import randint
randint(0,9)

What if I have a list, e.g. exclude=[2,5,7], that I don't want to be returned?




How do i generate a random maze in java?

Ok, so i want t generate a random maze for my maze game. I have hardcoded the maze like this, and have several different versions that i would like to be able to have spawned at random.

public Maze() {
        this.mazeMap1 = new BlockType[][] {
                {H, H, H, H, H, H, H, H, H, H, H, H, H, H, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, H, E, E, H, E, E, H, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, H, E, E, H, E, E, H, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, H, E, E, H, E, E, H, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, H, E, E, H, E, E, H, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, E, E, E, E, E, E, E, E, E, E, E, E, E, H},
            {H, H, H, H, H, H, H, H, H, H, H, H, H, H, H}
            };
}

then i create a getter and return the maze

public BlockType[][] getMazeMap() {
return mazeMap2;
}

Then i have a class 'Board' where i make the maze

 private void makeBoard() {
        blocks = new Maze().getMazeMap();
    }

If i would have, say 10 different hardcoded mazes, how would i generate one at random?




How to get random data from Csv file in Jmeter

We are planning to pick Random data from csv file in Jmeter. But we know there is no option in Csv Data Config. So we are planning to implement the Bean-shell Pre processor.

Any other idea to get Random data from Csv Files?

For Example




Why I am getting 0 in value. I have debugged it and found I am getting 0 in value. Also when i am storing to database it also store 0

I am trying to generate random number using RNGCryptoServiceProvider, but some how I am getting o(Zero) in return

private string generatePassword()
{

    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
    {
        string value = string.Empty;
        byte[] randomnumber = new byte[10000];
        rng.GetBytes(randomnumber);
        value = randomnumber.Tostring();
        return value;
    }

}




jeudi 23 mars 2017

C# Random Number Generator with unique numbers

I have managed to make an app which randomly generates a selected amount of numbers and puts all of the numbers in a rich text box (A result I would get from 1-100 with 10 numbers is '67, 55, 28, 35, 7, 69, 47, 59, 69, 82'. However, I am wanting to add an option where you can select if you want the numbers to be unique (checkbox), because the numbers box is close to the max number box, the numbers tend to duplicate.

I am not too sure how to do this though, I have tried looking online but most of the answers are a bit too complicated for me.

The code I have so far (C# Windows Form App FYI):

            int minComplexNumber = Convert.ToInt32(minComplexTextBox.Text);
            int maxComplexNumber = Convert.ToInt32(maxComplexTextBox.Text);
            int intergersNumber = Convert.ToInt32(intergersTextBox.Text);
            int numbersLeft = intergersNumber;
            resultComplexTextBox.Text = "";

            if (UniqueCheckBox.Checked)
            {
                //Need something here
            }
            else
            {
                Random comrnd = new Random();
                while (numbersLeft > 1)
                {

                    int complexResult = comrnd.Next(minComplexNumber, maxComplexNumber);
                    resultComplexTextBox.Text += complexResult + ", ";
                    numbersLeft = numbersLeft - 1;
                }

                if (numbersLeft == 1)
                {
                    int complexResult = comrnd.Next(minComplexNumber, maxComplexNumber);
                    resultComplexTextBox.Text += complexResult;
                    numbersLeft = numbersLeft - 1;
                }
            }

Any advice on how to get unique numbers?




How do I use random.randint(1000, 9999) as a function in python

I need to come up with 4 digit pass codes for users of a database at my work and I would like to just press a button, get a random value between 1000 and 9999, and have the program save that number so that it is not output again. I am not going to go through 9000 numbers so the fact that generated values can't appear again isn't a big deal.

How do I make a program that takes a random number between 1000 and 9999 and stores the values it has generated so that they are not used again? As far as generating the random numbers goes, random.randint(x, y) works just fine, I just need to know how to get the display to print to the command prompt or a the file that I write the generated numbers to.




Array index out of bounds with random generator

I am working on my home work and have an issue I cannot sort. All of this I created and it compiles fine until I tried to test it in the main. It is giving me the error in "

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1712741702
    at Test.arrayGen(Test.java:45)
    at Test.main(Test.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
".  

Here are the methods I created, one for the generation of the arrays and the sort as well as a counter to track the number of changes. Any help is appreciated.

import java.util.*;

public class Test {

    public static int selectionSort(int[] data) {

        int min;
        int temp;
        int counter = 0;

        for (int index = 0; index < data.length-1; index++) {

            min = index;
  /* Find the minimum element from position index */
            for (int scan = index + 1; scan < data.length; scan++) {
                counter++;
                if (data[scan] < (data[min])) min = scan;
            }

         /* Swap the values */
                temp = data[min];
                data[min] = data[index];
                data[index] = temp;

        }
        return counter;
    }

    public static int[] arrayGen(int max) {
        int top = 100;
        int bottom = 0;
        int listInts;
        Random random = new Random();

        top = 100;

        int[] myList = new int[max];

        for (int i = 0; i < max; i++) {
            myList[i] = random.nextInt(top - bottom);
            listInts = random.nextInt();
            System.out.println(myList[ listInts]);

        }
        return myList;
    }


   public static void main(String[] args) {
        selectionSort(arrayGen(5));

    }

}




How to generate random choices for random.choice() function using dictionary

I am trying to create a function which generates a random password using random.choice function,but i also want the choices to be random,i am trying to use a dict for this purpose,but not getting the desired result.. My code is:

def makepassword():
    letter1=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    letter2=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    symbol1=["@","#","$","%","&","*","<",">"]
    symbol2=["@","#","$","%","&","*","<",">"]
    number1=["0","1","2","3","4","5","6","7","8","9"]
    dict1={0:"letter1",1:"letter2",2:"symbol1",3:"symbol2",4:"number1"}
    k=dict1.get(randint(0,4))
    l=dict1.get(randint(0,4))
    m=dict1.get(randint(0,4))
    print(k,l,m)
    password=(choice(k)+choice(l)+choice(m))
    print(password)

If i print and check the values of k,l,m am getting values such as letter1/letter2/symbol1/symbol2/number1 so trying to use those values in choice function.

where as when i directly use: password=(choice(letter1)+choice(symbol1)+choice(number1)) it works fine.

So how the above Choice function can be implemented using Dictionary.




In java: Troubling generating a random order from an ArrayList

total newbie here. I've written a program in java to help randomize the order of bands for a concert I'm organizing. I'm having trouble getting the code to work. The output I get terminates after printing three strings instead of four, often repeats strings (which I don't want) and terminates after the third string with the following error:

"java.lang.IllegalArgumentException: bound must be positive"

Can anyone help troubleshoot my code?

public class BandRandomizer
{
public static void main(String[] args) 
{
    ArrayList<String> bands = new ArrayList<>();
    bands.add("Band A");
    bands.add("Band B");
    bands.add("Band C");
    bands.add("Band D");

    Random gen = new Random();
    int index = 0;

    for (int i = 3; i >= 0; i--)
    {
        index = gen.nextInt(i);
        System.out.println(bands.get(index));
        bands.remove(i);    
    }



}

}




How to automatically set the random seed on current time?

Everytime one opens a R console, the random seed is set to the same value. On my computer (it might alike the same on your machine), if I run rnorm(1), I always get 0.1777571 at the first call.

I tried to automatically set the random seed using the computer current time by adding something like

set.seed(
   as.integer(
      as.numeric(
         gsub("[^0-9]","",paste(format(Sys.time(), "%Y %X %x")))
      )%%.Machine$integer.max
   )
)

in the file .Rprofile but it does not change anything. The first call to rnorm(1) always return 0.1777571.

How can I automatically set the random seed to the computer current time?