mardi 30 juin 2015

android random class setseed

i'm new in android & java.

i used random class and setSeed for get different integer. but it's result same everything. why, and how i can solve it.

private void show_fortune(){
        int love = getRandompercent(); //same
        ((TextView)findViewById(R.id.loveper)).setText(love+"%");
        int money = getRandompercent(); //same
        ((TextView)findViewById(R.id.moneyper)).setText(money + "%");
        int job = getRandompercent(); //same
        ((TextView)findViewById(R.id.jobper)).setText(job + "%");
        int school = getRandompercent(); //same
        ((TextView)findViewById(R.id.schoolper)).setText(school+"%");

        TextView result = (TextView)findViewById(R.id.fortune_result);
        result.setText(fortune_result[fortune_arrayindex(love, money, job, school)]);

    }
    private int getRandompercent(){
        Random random = new Random();
        random.setSeed(System.currentTimeMillis());
        return Math.abs(random.nextInt()%100+1); //it's value is same everything.

    }
    private int fortune_arrayindex(int love, int money, int job, int school){
        int sum = (love+money+job+school)/4;
        if (sum>=70)
            return 0;
        else if (sum>=50)
            return 1;
        else if (sum>=30)
            return 2;
        else
            return 3;
    }




rand() function taking same values everytime [duplicate]

This question already has an answer here:

I have a program which includes rand() , whenever I run the program I found that rand() function is taking the same values. How can I change it so that I get the rand() to take different values? Thanks.




Setting up a Piecewise Distribution in C++

After hours of struggling with this issue, I cannot find any explanations for my error.

I want the computer to pick a random number (weighted) between 0 and 120 (inclusive). I have an array, interval[], which holds the numbers from 0 to 120 (inclusive). I have another array, weights[], which holds the probabilities for choosing the ith element in the array. I want to define a probability distribution function for these data. I am trying to write:

piecewise_constant_distribution<> dist(begin(interval), end(interval), begin(weights));

However, I get an error saying: "invalid probability vector for discrete_distribution". Can someone please help me with this?




R split data into 2 parts randomly

I am trying to split my data frame into 2 parts randomly. For example, I'd like to get a random 70% of the data into one data frame and the other 30% into other data frame. Is there a fast way to do this? The number of rows in the original data frame is over 800000. I've tried with a for loop, selecting a random number from the number of rows, and then binding that row to the first (70%) data frame using rbind() and deleting it from the original data frame to get the other (30%) data frame. But this is extremely slow. Is there a relatively fast way I could do this?




Create random binary sequences with last and first element equal to 1

I use rand(1,N)<=0.5in order to create binary sequences with 1s, and 0s.

N can take any value from 0 and above.

What I want to achieve is to have the same functionality as above but secure that always first and last elements will be 1.

For example

For N=0 --> empty array

For N=1 -->[ 1 ]

For N=2 -->[ 1 1 ]

For N=3 --> [1 0 1] or [1 1 1]

For N=4 --> [1 0 0 1] or [1 0 1 1] or [1 1 0 1] or [1 1 1 1]

and you see the logic?? Is there any automated way to achieve this?? For N=2 and above I guess [1 rand(1,N-2)<=0.5 1] works, but I want something that also works for N=0 and N=1;

Thanks




Is it possible to generate random floating point numbers including subnormals, with rand() of math.h?

I would like to generate floating point numbers that include subnormal floating point numbers. Can we use the routine rand() of math.h to achieve this? The programming language should be C99.




How to search numbers for a given set of repetitive numbers in random order the first time only?

How to search numbers for a given set of repetitive numbers in random order that occurs for the first time only. Say for rand() % 5 +1 which repeats n times till it finds all the numbers which occurs at the first time and the number of iteration it took to get all the numbers?




Data Structures - Randomized Queues

I am currently working on Princeton's Algorithms Part I. One of the assignments is to implement a randomized queue. This is a question regarding the implementation and tradeoffs of using different data structures.

Question:

A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random from items in the data structure. Create a generic data type RandomizedQueue that implements the following API:

public class RandomizedQueue<Item> implements Iterable<Item> {
    public RandomizedQueue() // construct an empty randomized queue
    public boolean isEmpty() // is the queue empty?
    public int size() // return the number of items on the queue
    public void enqueue(Item item) // add the item
    public Item dequeue() // remove and return a random item
    public Item sample() // return (but do not remove) a random item
    public Iterator<Item> iterator() // return an independent iterator over items in random order
    public static void main(String[] args)   // unit testing
}

The catch here is to implement the dequeue operation and the iterator since the dequeue removes and returns a random element and the iterator iterates over the queue in a random order.

1. Array Implementation:

The primary implementation I was considering is an array implementation. This will be identical to the implementation of an an array queue except the randomness.

Query 1.1: For the dequeue operation, I simply select a number randomly from the size of the array and return that item, and then move the last item in the array to the position of the returned item.

However, this approach changes the order of the queue. In this case it does not matter since I am dequeuing in random order. However, I was wondering if there was an time/memory efficient way to dequeue a random element from the array while preserving the order of the queue without having to create a new array and transfer all the data to it.

// Current code for dequeue - changes the order of the array after dequeue
private int[] queue; // array queue
private int N; // number of items in the queue

public Item dequeue() {
    if (isEmpty()) throw NoSuchElementException("Queue is empty");
    int randomIndex = StdRandom.uniform(N);
    Item temp = queue[randomIndex]        

    if (randomIndex == N - 1) {
        queue[randomIndex] = null; // to avoid loitering
    } else {
        queue[randomIndex] = queue[N - 1];
        queue[randomIndex] = null; 
    }

    // code to resize array

    N--;
    return temp;
}

Query 1.2: For the iterator to meet the requirement of returning elements randomly, I create a new array with all the indices of the queue, then shuffle the array with a Knuth shuffle operation and return the elements at those particular indices in the queue. However, this involves creating a new array equal to the length of the queue. Again, I am sure I am missing a more efficient method.

2. Inner Class Implementation

The second implementation involves an inner node class.

public class RandomizedQueue<Item> {
    private static class Node<Item> {
        Item item;
        Node<Item> next;
        Node<Item> previous;
    }
}

Query 2.1. In this case I understand how to perform the dequeue operation efficiently: Return a random node and change the references for the adjacent nodes.

However, I am confounded by how to return a iterator that returns the nodes in random order without having to create a whole new queue with nodes attached in random order.

Further, what are the benefits of using such a data structure over an array, other than readability and ease of implementation?

This post is kind of long. I appreciate that you guys have taken the time to read my question and help me out. Thanks!




Game programming implement chunks

i'm working on a simple game project with libgdx and i need some help to make a random infinite world. After googling for hours i knew that many games use the "chunk theory" to generate an infinite map and also implement tiles. There are many things i don't understand... for example:

What is a tile? and a chunk? How can i implement this "chunk theory" in a game? Is this the best way to generate an infinite random map?

can someone answer my questions to make some clarifications in my mind? Thanks in advance




Java - generating random clusters of numbers

I have an array of stuff, and I want to "randomly" select stuff from that array, but I'd like the probability for it to get clusters to be higher.

For example:

arr = [1, 3, 4, 6, 7, 9, 10]
x = Math.random() * arr.length;
return arr[x]

If x came out to be 3, then the function would return 6. How do I increase the likelihood that the next number x will be is 2 or 4 (and then 1 and 5 and so on, with the probability curving the further away it gets from the current x). Is this doable?




How can I find and edit a line in a text file using batch?

I have a text file with multiple of lines. Each line contains a known word and an unknown number. I want to make a batch file which searches for a specific line (with a known word) and replaces the random number with a number with is entered by the user. I already used FART but I don't know the part with the unknown number.




Random .asp file generated within the web server?

I have a static html website and few pages that use php like forms. On the front end, the website looks fine, however when I try to login through ftp and noticed there are around 189600 files that end with .asp extension being generated within the server.

The file names are all like these:

   aada-oakley-047495.asp
   Aadcaj-puma-22256.asp
   AAeEc-furniture-s1-94186
   .......

Is this a sign of the website being hacked? Should I deleted all these files or leave it as it is?




lundi 29 juin 2015

Does calling random.normal on an array of values add noise?

I saw this pattern in someone's code:

import numpy as np
# Create array
xx = np.linspace(0.0, 100.0, num=100)
# Add Noise
xx = np.random.normal(xx)

and it seems to add some noise to each value of the array, but I can't find any documentation for this. What's happening? What determines the properties (i.e. scaling) of the noise? Is the given value being treated as the mean (i.e. the loc parameter) of each sampling from the normal distribution?

I'd also be very curious to know why this behavior doesn't seem to be covered in the documentation.




Random name picker based on points

I'm kinda noob in this stuff and that's why i always use ready-to-use scripts, etc ... I have searched around the network for such a script, but i didn't find any so i decided to ask here.

What I need is a script (javascript/php) that i can insert into my html page which should do the following.

I want to have one textbox1 where i type some name and textbox2 where i type some points then an add/remove button and a list to show the names that has been added and their points. Then a button again that will pick some of the names based on their points. So what i want to do is to make it that the name who has more points to have the better chance to get picked up. Thanks in advcance!




How to generate independent identically distributed (iid) random variables in python

I am developing a simulation infrastructure with some random events (for instance, sources that generate output with a certain probability). So far I've been doing it using the random.random() function. Ex:

class source:
    def output(self, x):
        if(random.random()<=x):
            return foo
a = []
for i in xrange(10)
    a.append(source())

for i in xrange(1000):
    for j in xrange(len(a)):
        a[j].output()

From what I understand, all of the sources in my list "a" will get random numbers from the same pseudo-random LFSR source, so a[0] will get a sample, then a[1] will get the next one, then a[2], etc. If random.ramdom() generated a truly random sequence, I believe this would still generate 10 iid subsets of values, however, since I am assuming that python uses an LFSR, or a similar scheme, where each subsequent sample depends on the previous sample, taking several subsets of these samples may or may not be independent and identically distributed.

I have two questions:

  1. What kind of distributions do I actually get using my pseudocode or something similar to that
  2. How do I get several iid random variables in python?

I looked at other stack overflow posts, like this one for example: Generate multiple independent random streams in python but they don't answer my question.




array[i] = java.lang.IndexOutOfBoundsException : Invalid array range 10 to 10

My problem is that I keep getting the error in the title during debugging.

array[i] = java.lang.IndexOutOfBoundsException : Invalid array range 10 to 10

The following is the for loop. I entered values people = 10, payer = 4, rest = 6.

int[] array = new int[people];
Random rand = new Random();
int rest = people-payer;

for(int i=0; i<people; i++) {
    if(payer<=0) { /*Payers are already decided*/
        array[i] = 0;
        continue;
    }
    if(rest<=0) {
        array[i] = 1;
        continue;
    }
    else {
        int randomNumber = rand.nextInt(2);
        array[i] = randomNumber;
        if (randomNumber == 1)
            payer--;
        if (randomNumber == 0)
            rest--;
    }
}

I think the error is saying that I'm trying to access an index 10 of my array which doesn't exist. I don't know where I am accessing array[10]. Or maybe the problem is somewhere else??

Thank you for your time :)




Selecting label and then export into a new label

I have a little problem here. So I do not mean my English ;-)

I have 3 generate numbers here in 3 different label.

Number 1:

-(IBAction)rechneAdd:(id)sender {
float erg = ([label1.text floatValue]) + ([label2.text floatValue]);
label3.text = [[NSString alloc] initWithFormat:@"% g", erg];
NSLog(@"Ergebnis 1 = % g", erg);
}

Number 2:

-(IBAction) rechneErgebnis:(id)sender {
float erg = ([label3.text floatValue]) + ([label4.text floatValue]);
label5.text = [[NSString alloc] initWithFormat:@"% g", erg];
NSLog(@"Ergebnis 2 = % g", erg);
}

Random number 3:

- (IBAction)Zufallszahl4:(id)sender {
Zufallszahl4 = random() % 2 ? 1 : -1;
label6.text = [NSString stringWithFormat:@"%i", Zufallszahl4];
NSLog (@"Zufallszahl 4 = %i", Zufallszahl4);
}

Now, if the random number 3, the result "1" returns, then the result is output the Number 1 in the new "Label1". If the random number 3, the result "-1" returns, then the result is output the Number 2 in "Label1".

Unfortunately do not continue... I hope you know what I mean Do you have a useful idea about this? Thank you very much, Christian




linear distribution in c++ using rand()

I am writing a function that generates n random points (x, y) such that xmin < x < xmax and ymin < y < ymax. This is easy to do with uniform distribution using rand().

int points[n][2];
for (int i = 0; i < n; i++) {
    points[i][0] = rand() % (xmax - xmin) + xmin;
    points[i][1] = rand() % (ymax - ymin) + ymin;
}

However, I would like to control the distribution so that the probability of each point having a given x or y value is px = (px2 * (x - xmin) + px1 * (xmax - x)) / (xmax - xmin) or py = (py2 * (y - ymin) + py1 * (ymax - y)) / (xmax - xmin), respectively. In other words, a linear distribution across the rectangle in each dimension.

I can fake this by partitioning the rectangle into sufficiently small discrete rectangles and using the algorithm above for each one, with n proportional to the average probability across that smaller rectangle. However, I would prefer to apply a continuous distribution across the entire rectangle. Can this be done, either using rand() or with another approach?




Attaching an image to a randomly generated number between 1-10?

I'm fairly new to HTML and I'm able to successfully generate the random numbers, but I want to attach an image to a specific number E.G a card game (11 =jack =12=queen ..etc)

This is what I have

function numbers() {
    var x = Math.floor((Math.random() * 10) + 1);
    var img = document.createElement("img");
    if(x ==1||2||3||4||5||6||7) {
        img.src = "ace.jpg";
    }
    document.getElementById("num").innerHTML = "Rule " + x;
}




How do I write a bash script to pass random files from all sublevels of a directory into an executable one by one?

I'm trying to feed random files from my iTunes Library into mpv, to shuffle my music without iTunes. Initially I tried to pass all the files into mpv using '**' and use mpv's '--shuffle' option, but mpv cannot take that many arguments. Instead, I want to generate the list of files in my own script and pass random elements from it into mpv.

Here is my code:

RANDOM=$$$(date +%s)

FILES=(~/Music/iTunes/iTunes\ Media/Music/**/**/*)

while [ 1 ]
do
    # Get random song
    nextsong=${FILES[$RANDOM % ${#FILES[@]} ]}

    # Play song
    mpv $nextsong --audio-display=no
done

When I run this, something is wrong with the list of files, mpv tries to play incomplete bits of filepaths.




Javascript Random Generator to create custom URL variables

OK - I am trying to generate a custom URL with appended variables that are randomly generated.

Example: http://ift.tt/1NqhQ6R< location_id >&user=< user_name >&pass=< password >

I'm fine with all of the variable data being numeric, and have been trying to use this to generate the random numbers:

<p>Click the button to join.</p>

<button onclick="genID5()">Join</button>

<p id="generateID1"></p><p id="generateID2"></p><p id="generateID3"></p>

<script>
function genIDA() {
    var x = Math.floor((Math.random() * 1000000000000) + 101);
    document.getElementById("generateID1").innerHTML = x;
        console.log(x);
}

function genIDB() {
    var y = Math.floor((Math.random() * 1000000000000) + 101);
    document.getElementById("generateID2").innerHTML = y;
        console.log(y);
}

function genIDC() {
    var z = Math.floor((Math.random() * 1000000000000) + 101);
    document.getElementById("generateID3").innerHTML = z;
        console.log(z);
}

function genID5() {
    genIDA();
    genIDB();
    genIDC();

}


</script>

I am getting some nice big random numbers, and then I am trying to use this to append the URL:

function genURL() { 
        document.action = window.location.href = "http://ift.tt/1NqhQ6R + X + &user= y + &pass= + z; 
            return true; 
}

The URL function mostly works as far as pushing it to the Window object, and going to that URL - but getting the var values to insert is giving me a problem... I am not sure if it is because they are not nested, but I am getting undefined errors. Ultimately I dont need/want the user to see the numbers, and if the page loaded and executed to the script and the loaded the destination, that would be OK as well. I wanted to see the output difference between the HTML and the Console, and having the button to execute it helped me see the steps...

Any help would be appreciated! Thanks in advance!




random picture script for new app

I am creating an app through AppMaker and I want a random picture to appear when someone clicks the icon. I found a script online (I am a newby to scripts and don't understand much of it. So I will need assistance). I entered the script in (where they accept html on a screen) and it doesn't seem to run when I test it. I created several test pictures and uploaded them to my online site and then ran this script. I have asked for tech support from the company and they have escalated the issue to higher tech support. Its been about a week and no one is getting back to me. Any help would be appreciated.

The script is as follows:

`<script type="text/javascript">
var total_images = 2;
var random_number = Math.floor((Math.random(2)*total_images));
var random_img = new Array(3);
random_img[0] = '<ahref="http://ift.tt/1KkyqoE"><img src="
images/Tarot1.jpg"></a>';;
random_img[1] = '<a href="http://ift.tt/1FKsO0D"><img src="
images/Tarot2.jpg"></a>';;
document.write(random_img[random_number]);
</script>`

Thank you so much for your assistance and patience with me as again, I am new to this.




Probability function

How can I create a function of probability, choosing between two strings with a probability range between 1/3, 1/2, 1/1, 2/1, 3/1

My value comes from a slider in a range between -2 and 2

this is my code:

$out = array('str1','str2');
$out = $out[array_rand($out)];

I want something like this:

$val = 0; //-2=1/3, -1=1/2, 0=1/1, 1=2/1, 2=3/1 

function random_str($val){
  ...
  retunt $myRandomValue;
}




random database connection (php)

Trying to make random database connection, but always getting errors. I Didn't know how to work with public static variable in class.

class DB {


    $dbs = array("data_base1","data_base2","data_base3"); 
    $dbs = $dbs[rand(0, count($dbs)-1)];

    // initial connection
    public static $dbName='$dbs';
    public static $user='$dbs';
    public static $password = 'pass123';
    public static $host = 'localhost';




Changing value of bool at random time within limits

What I am trying to write is a piece of code that will change the value of a bool from true to false and visa versa at a random time between say 1 and 3 seconds. I've tried many methods using random. etc and attempting to set a timer that resets but it just doesn't click. I'm using c# which I'm quite new to so I'm not sure if this is a simple trick or something more complex. Any forums or videos are much appreciated anyhow.




Saving a generated stream into an ArrayList

What I'm supposed to do is create an ArrayList of random numbers via stream.generate. Code below is my attempt of trying to save it into an ArrayList, but it's of type "object". I figured I have to somehow map it into int first, but I don't know how. Code right now doesnt work.

public ArrayList<Integer> createRandomList(ArrayList<Integer> list, int amount) {
     ArrayList<Integer> a = Arrays.asList(Stream.generate(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        Random rnd = new Random();
                        return rnd.nextInt(100000);
                    }
                }).limit(amount).mapToInt.toArray());
}




Why do you need Arbitraries in scalacheck?

I wonder why Arbitrary is needed because automated property testing requires property definition, like

val prop = forAll(v: T => check that property holds for v)

and value v generator. The user guide says that you can create custom generators for custom types (a generator for trees is exemplified). Yet, it does not explain why do you need arbitraries on top of that.

Secondly, it is curious how does arbitrary[Int] convert argument type into generator. I feel that these are related questions.




dimanche 28 juin 2015

JS: How to create a random picker that won't pick the same item twice?

I'm making a random hero picker for a game, and this tool will randomly pick heroes for the player. I want to add a feature where it picks the heroes for the whole team of 3, but I don't know how to make it so that the same hero won't be pick more than once. Here is a sample of my code for picking a random hero for a player. Thank you in advance!!!!

<script language="JavaScript">

function pickhero(){
var imagenumber = 16 ;
var randomnumber = Math.random() ;
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array
images[1] = "http://ift.tt/1TZeYSO"
images[2] = "http://ift.tt/1Ns7PW7"
images[3] = "http://ift.tt/1TZeYSQ"
images[4] = "http://ift.tt/1Ns7PW9"
images[5] = "http://ift.tt/1Ns7Ol0"
images[6] = "http://ift.tt/1TZeYSW"
images[7] = "http://ift.tt/1Ns7Qcp"
images[8] = "http://ift.tt/1TZeYT0"
images[9] = "http://ift.tt/1Ns7Qcr"
images[10] = "http://ift.tt/1TZeZ9g"
images[11] = "http://ift.tt/1Ns7Qct"
images[12] = "http://ift.tt/1TZeZ9i"
images[13] = "http://ift.tt/1Ns7Ol2"
images[14] = "http://ift.tt/1TZeXOP"
images[15] = "http://ift.tt/1TZeZ9k"
images[16] = "http://ift.tt/1Ns7Ol4"
var image = images[rand1]
document.team1hero1.src = image
}
</script>




This code has really long loading times, how to reduce loading? (Batch)

Okay, my code is a simple batch number generator 1-10, I need a way to make the code not take 1 minute per set of code. I use this code multiple times in my script, causing outrageous loading times of up to 5 minutes.

  :ans
set /a ran=%random%
if /i %ran% GTR 10 goto :ans
if /i %ran% LSS 1 goto :ans

this code has the random feature repeated until a number 1-10 appears. This takes a really long time because there are over 31.990 other ways it could go. Please tell me how to fix this issue, with a different set of code or a edited version of the code. Thank you.




(C++) Random numbers are equal, but program says they aren't

I am a beginner, and I created a slot machine simulator. The wheel is spun and x, y, and z are set to random numbers. I have an if statement that checks to see if x == y == z. When the program runs, and the numbers are in fact equal, it runs my code that says they are not equal. Why does this happen?

For example, the cout statement will say 1 -- 1 -- 1, then it goes to my if statement for when they are not equal, and I get the "you lose" code.

I should add, this does not happen every time. Sometimes it properly executes the if statement for when they are equal. It is very odd.

    srand(time(0));

    int x = (rand() % 2) + 1;
    int y = (rand() % 2) + 1;
    int z = (rand() % 2) + 1;

    std::cout << "The spin results are... " << x << " -- " << y << " -- " << z << std::endl << std::endl;

    if( x == y == z)
    {
    std::cout << "You win!\n\n";
    playerCoins = playerCoins + (coinsBet * 2);
    }
    else 
    {   
        std::cout << "You lose!\n\n";
    }




How to generate short, reasonably non-sequential keys in Scala (unique web links)

I'm sure someone has created a great, terse, and effective Scala function for generating short non-sequential keys suitable for use in web links. I'd like the keys to be hard to guess sequentially... I don't want someone just "browsing" through the links – but, hitting on one randomly is not a big deal.

There are a few related posts (this one and this other one), but they don't really address the problem (and they are in the wrong languages). The idea is to make seemingly random, reasonably short URL keys. Something like Vimeo or Youtube short links would be fine, but not too short (http://watever.com/abc is too easy to guess/browse) and not too long (http://ift.tt/1eSYP1x is just too long). A happy medium would be most desirable: http://ift.tt/1eSYOL2.

They keys will ultimately be stored in a relational database, so I have the option of checking for uniqueness, and retrying until I "get lucky."

Any ideas? Or hopefully a slick little algorithm?




unit test to check uniqueness of million generated strings

I would like to write a unit test to

1) go through a list of 1 million unique random generated strings.

2) Ensure that each numer is 100% unique and there are no duplicates.

What is the best way to check and compare that there are no duplicates.




Seeding rand() by itself

If a program generates a few numbers using rand(), stores the last rand() result, and on repeated runs use srand(stored_seed), would this provide some shorter, but still usable random number sequence?




Distribution of the mean (MatLab)

X1,X2,…,Xn are n i.i.d. random variables with the distribution F(X). Let Y=min(X1,X2,…,Xn). What is the code to calculate F(Y) using MatLab (preferably working for an arbitrary distribution)?

Thanks in Advance!




Using randoms and super

How would I call a Random from java.util.Random into a supertype constructor?

For example

Random rand = new Random();
int randomValue = rand.nextInt(10) + 5;

public Something() 
{
    super(randomValue);
    //Over Things
}

When I try this the compiler says I "cannot reference randomValue before supertype constructor has been called".




How to generate a set of random numbers in both Lua and C# that are the same?

I need to generate a set of random numbers from a seed in Lua and then generate the same set of random numbers in c# from the same seed, What would be the best way to go about this?




Mysql "where rand()" perfomance

I'm trying to pick random articles from my database, where high rating articles have a higher chance of getting picked

SELECT * FROM articles WHERE RAND()>0.1  ORDER BY rating  DESC LIMIT 3

My question is: Will it random the whole table, or just until it finds 3 articles that random a number higher then 0.1




Getting number of random timestamps throughout a day in Java

What would be a good way to go about this? I wish to show a message 5 times at random times throughout a day. I currently use the following method to generate timestamps:

List<Long> timestamps = new ArrayList<Long>();

long currentTimestamp = (long) (System.currentTimeMillis() / 1000L);
long endTimestamp = addHoursToTimestamp(8, currentTimestamp);

int n_timestamps = 5;
for (int i = 0; i < n_timestamps; i++) {
    Long randomTime = currentTimestamp + Math.abs(new Random().nextLong()) % (endTimestamp-currentTimestamp);
    timestamps.add(randomTime);
}

Sometimes this works good and I get nicely spread out timestamps. Of course as you can imagine, sometimes the timestamps are really close to one another, like in this example where there are 3 timestamps at the 11th hour (in a timespan of 11:00-19:00):

1435483835  Sun Jun 28 11:30:35 CEST 2015
1435501808  Sun Jun 28 16:30:08 CEST 2015
1435484646  Sun Jun 28 11:44:06 CEST 2015
1435495886  Sun Jun 28 14:51:26 CEST 2015
1435483799  Sun Jun 28 11:29:59 CEST 2015

This is not ideal, since I want the timestamps to be spread out a bit. To fix this I created a function that loops over all timestamps already added to the array, and check if the generated timestamp is at least an hour later or earlier than each of those.

However, I don't know if this is the preferred way to go about it. Seems pretty heavy in computation.




samedi 27 juin 2015

Is `arc4random` family of functions thread safe?

The title says all. I care especially about iOS and OS X.

If not, what are the possible replacements with cryptographic quality of randomness?




How to generate random strings in Label using def?

def mhello():    
    import  string    
    var = (random.choice("hey", "hi" "hello")    
    Label2 = Label(text=var, fg='Red').place(x=130,y=200)

This isn't working, how would I make it so that the label's text randomly generates one of the options?




randomly change image of buttons and decelerate changing

i have 2 buttons.

they are called _rightButtonPressed and _leftButtonPressed. They have an background image named "blackBackground". When they are clicked, the background image is changed to "whiteBackground".

Ok. Now i want to make a third button, that changes the background image at first _rightButtonPressed to "white", then "black", then _leftButtonPressed to "white", then "black" and so on. This change have to decelerate to the end. At least, it should be randomly stops at a button with "white" background image and click the button. I hope its comprehensible.

I have no idea, how i can do this...




generate random string so no two threads collide

Here is the code for my random string generator

private static string GetUniqueKey()
{
    int maxSize  = 15 ;
    char[] chars = new char[62];
    string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    chars = a.ToCharArray();
    int size  = maxSize ;
    byte[] data = new byte[1];
    RNGCryptoServiceProvider  crypto = new RNGCryptoServiceProvider();
    crypto.GetNonZeroBytes(data) ;
    size =  maxSize ;
    data = new byte[size];
    crypto.GetNonZeroBytes(data);
    StringBuilder result = new StringBuilder(size) ;
    foreach(byte b in data )
    {
        result.Append(chars[b % (chars.Length - 1)]);
    }
    return result.ToString();

}

How do I write a unit test that would test for 100% guarantee that no 2 threads will generate the same random number

I don't want to lock thread because it creates performance night mare under extreme load tests.

This logic will be used in load balanced 8 app servers.

I can't use GUID because this random string should be humanly readable like a credit card number.

Do I have to constantly read database to ensure that this is a unique number before I store in DB?




generate random string in load balanced app servers

Here is the code for my random string generator

private static string GetUniqueKey()
{
    int maxSize  = 15 ;
    char[] chars = new char[62];
    string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    chars = a.ToCharArray();
    int size  = maxSize ;
    byte[] data = new byte[1];
    RNGCryptoServiceProvider  crypto = new RNGCryptoServiceProvider();
    crypto.GetNonZeroBytes(data) ;
    size =  maxSize ;
    data = new byte[size];
    crypto.GetNonZeroBytes(data);
    StringBuilder result = new StringBuilder(size) ;
    foreach(byte b in data )
    {
        result.Append(chars[b % (chars.Length - 1)]);
    }
    return result.ToString();

}

How do I write a unit test that would test for the following:

  1. checks the database and keeps generating random number until it does not exist in the database and updates the database
  2. 100% guarantee that no 2 threads will generate the same random number
  3. will work on different app servers in load balancer situation.

I don't want to lock thread because it creates performance night mare under extreme load tests.




How to Replace Values Exceeding Threshold with Random Number Sampled from a Given Dataset?

I have a 3-dimensional vector called 'simulatedReturnsEVT3'. In that vector, I would like to replace all values that are higher than 'MaxAcceptableVal' or lower than 'MinAcceptableVal'. Such values that are beyond either of these two thresholds should be replaced by a random number that is drawn from the 3-dimensional vector 'data2'. For drawing that random number, I use the matlab function 'datasample'.

I have written the below code, which replaces the values that are beyond either of the thresholds with a random number sampled from 'data2'. However, it seems (when plotting the data in a histogram) that the replacement happens with the same value along dimension 'j'. This is not what I want to do. For every threshold exceedance, I want a new random number to be drawn for replacement from 'data2'.

nIndices = 19
nTrials  = 10000

% data2                has dimensions 782 x 19 x 10000
% simulatedReturnsEVT3 has dimensions 312 x 19 x 10000
% MaxAcceptableVal     has dimensions   1 x 19
% MinAcceptableVal     has dimensions   1 x 19

% Cut off Outliers
for i=1:nIndices
    for j=1:nTrials
        sliceEVT = simulatedReturnsEVT3(:,i,j);
        sliceEVT(sliceEVT < MinAcceptableVal(i))=datasample (data2(:,i,j), 1,1,'Replace',false);
        sliceEVT(sliceEVT > MaxAcceptableVal(i))=datasample (data2(:,i,j), 1,1,'Replace',false);
        simulatedReturnsEVT3(:,i,j) = sliceEVT;
    end
end

The same problem can be illustrated on a smaller scale by creating the following matrices.

% Set Maximum Acceptable Levels for Positive and Negative Returns
MaxAcceptableVal = [0.5   0.3]
MinAcceptableVal = [-0.5 -0.3]

simulatedReturnsEVT3 = [0.6 0.3; 0.3 0.3; 0.3 0.3; 0.3 0.4]
simulatedReturnsEVT3 = repmat(simulatedReturnsEVT3,[1 1 2])
data2                = [0.25 0.15; 0.25 0.15; 0.2 0.1]    
data2                = repmat(data2,[1 1 2])               

% Cut off Outliers
for i=1:2 
    for j=1:2 
        sliceEVT = simulatedReturnsEVT3(:,i,j);
        sliceEVT(sliceEVT < MinAcceptableVal(i))=datasample (data2(:,i,j), 1,1,'Replace',false);
        sliceEVT(sliceEVT > MaxAcceptableVal(i))=datasample (data2(:,i,j), 1,1,'Replace',false);
        simulatedReturnsEVT3(:,i,j) = sliceEVT;
    end
end

Can anybody help?




How to use randomly generated number in switch statement?

i am making a simple program that displays the behaviour of the person from the sentences that i write in switch statement cases. I want to randomly generate a number between 1 and 10 and use it in "switch(this place)". So far, i have written the following code and stuck here..

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int rand_range(int low, int high)
{
  return rand()%(high-low) + low;
}
int main()
{
    srand(time(NULL));
    cout<<"Hi!, this program tells you about your behaviour"<<endl;
    cout<<"press enter to continue";
    cin.get();

    switch(    )
    {
    case 1:
        {
            cout<<"you are rude !";
        }
    case 2:
        {
            cout<<"you are smart";
        }
    case 3:
        {
            cout<<"you try to prove yourself special all the time";
        }
    case 4:
        {
            cout<<"you are good in sarcasm";
        }
    case 5:
        {
            cout<<"you look dumb, but deep inside you are intelligent";
        }
    case 6:
        {
            cout<<"you are always ready for a debate with someone";
        }
    case 7:
        {
            cout<<"you are very lazy";
        }
    case 8:
        {
            cout<<"you are dumber than what you look";
        }
    case 9:
        {
            cout<<"you always try to help others";
        }
    case 10:
        {
            cout<<"you have good decision making capabilities";
        }
    default:
        {
            cout<<"something wrong";
        }
    }
}




Using rand()/(RAND_MAX +1)

i have problem with this use of rand(): rand() / (RAND_MAX + 1.0)

I know the "simple" use for rand() (like rand() %100 + 1) but i don't understand what it does.




How view 2 random text

I'm having a problem from this is make would tap my button view local b and local a but that not overlap code:

function randomText(event)

display.remove(mmDis)

local a = {"Cristiano ronaldo jest najlepszy!","messi jest dobry!","lewandowski jest ok","diego lopez to 
bramkarz realu"}

local b = {"blue","red","pink","orange"}

com = (a[math.random(1,#a)])


local mmDis = display.newText(tostring(com), 
    display.contentWidth*0.57, disp`enter code here`lay.contentHeight*0.7,               
    display.contentWidth*0.9, display.contentHeight*0.8, "Impact", 30)
    mmDis.y=20
    mmDis.x=175
    mmDis:setFillColor(0, 0, 0, 1)  
end 

play:addEventListener ("tap", randomText )




vendredi 26 juin 2015

In Powershell, How to generate a random variable (exponential) with a specified mean?

I am trying to write a basic simulation (a queue), which relies on generating random expovariates. While Powershell offers a Get-Random function, you can specify a min and a max, but it doesn't have anywhere near Python's random.expovariate(lambd) function.

Supposedly this is the model I should be following: log(1-$u)/(−λ)

The excellent Python documentation has this to say about it:

"Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.". In another description, "expovariate() produces an exponential distribution useful for simulating arrival or interval time values for in homogeneous Poisson processes such as the rate of radioactive decay or requests coming into a web server.

The Pareto, or power law, distribution matches many observable phenomena and was popularized by Chris Anderon’s book, The Long Tail. The paretovariate() function is useful for simulating allocation of resources to individuals (wealth to people, demand for musicians, attention to blogs, etc.)."

I have tried writing this in Powershell, but my distributions are way off. If I put in a mean of 3 I am getting the results that closely follow the results I should get from a mean of 1. My code is closely modeled on John D. Cook's SimpleRNG C# library.

function GetUniform #GetUint
{
    Return Get-Random -Minimum -0.00 -Maximum 1
}



# Get exponential random sample with specified mean
function GetExponential_SpecMean{
param([double]$mean)

    if ($mean -le 0.0)
    {
                Write-Host "Mean must be positive. Received $mean."

            }
    $a = GetExponential
    $R = $mean * $a
    Return $R
}


# Get exponential random sample with mean 1
function GetExponential
{
    $x = GetUniform
    Return -[math]::log10(1-$x) # -Math.Log( GetUniform() );
}

cls
$mean5 = 1
$rangeBottom = 3.0
$rangeTop = 4.0

$j = 0
$k = 0
$l = 0

    for($i=1; $i -le 1000; $i++){
        $a = GetExponential_SpecMean $mean5

        if($a -le 1.0){Write-Host $a;$j++}
        if($a -gt 1.0){Write-Host $a;$k++}
        if(($a -gt $rangeBottom) -and ($a -le $rangeTop)){#Write-Host $a;
        $l++}

        Write-Host "                      -> $i "
        }

Write-Host "One or less: $j"
Write-Host "Greater than one: $k"
Write-Host "Total in range between bottom $rangeBottom  and top $rangeTop : $l"

For a sample of 1000 and a Mean ($mean5) of 1, I should get (I believe) 500 results that are 1.0 or less and 500 that are greater than 1.0 (1:1 ratio), however I am getting a ratio of about 9:1 with a mean of 1 and a ratio of about 53:47 using a mean of 3.

There is some discussion in this Stack Overflow question with some good background, but it is not specific to Powershell: Pseudorandom Number Generator - Exponential Distribution




Generating a random number in Befunge

I want to generate a random number in Befunge, from 0 to n, where n is an arbitrary number. How would I go about doing this?
I thought of trying this (this example has 2 chained chunks of code to show how it works):

v  v
?#>?#>
1  1
+  +
> ^> ^

and repeating as needed, but I would need n copies of that chunk of code. Is there a better way I can generate a random number like rand(0, 10) in other languages?




Inconsistent results for f(g(x)) together or split up

During a recent investigation into setting random seeds within functions, I came across an odd situation. Consider functions f and g, each of which sets the random seed and then performs a simple randomized operation:

g <- function(size) { set.seed(1) ; runif(size) }
f <- function(x) { set.seed(2) ; x*runif(length(x)) }

Because each function sets the random seed, I would expect each function to always have the same return value given the same input. This would mean f(g(2)) should return the same thing as x <- g(2) ; f(x). To my surprise this is not the case:

f(g(2))
# [1] 0.1520975 0.3379658

x <- g(2)
f(x)
# [1] 0.04908784 0.26137017

What is going on here?




Other ways to get a random number in Lua

I'm looking for an alternative way to get a random number in Lua that is between a minimum and a maximum number without using math.random(). Is there any way? It doesn't have to be a simple method. Thanks for any help.




Trying to make array element appear only once

So i'm trying to do this : when you click the image the text in the center changes to a random element from the array but i want every element that appears once to not appear again... I tried doing it like this but it didn't work please help me here!!

package com.example.bibiwars.skills;


import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import java.util.Random;


public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


            ImageView img = (ImageView) findViewById(R.id.logo);
            img.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //ToastMessage to test the click ::::::
            Toast.makeText(MainActivity.this, "Clicked!!",Toast.LENGTH_SHORT).show();


            TextView text = (TextView) findViewById(R.id.text);
            String[] Array = {"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"};
            int rnd = new Random().nextInt(Array.length);
            while (Array[rnd].equals("0"))
               {rnd = new Random().nextInt(Array.length);}
            text.setText(Array[rnd]);
            Array[rnd] = "0";
        }

    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}



}




Random based upon percentage

Given a set a yet unknown values in an array/table, where each value contains a number, how would I make it so that the values with higher numbers have a larger chance of being picked?

I did this in Lua and I came up with an extremely inefficient method that didn't even work some reason:

Example:

"module.InsertTokens(5,'a')
--The function above would insert the value "a" five times into an array
module.RemoveId('a') --this is supposed to remove all values of a
print(#module.Tokens)"

2 --should be 0 --why does it return 2?? D:

function module.InsertTokens(amount, id)
    for i = 1, amount do --amount times
        print'inserting'
        module.Tokens[#module.Tokens+1]=id
    end
end

function module.RemoveId(id)
for index, v in pairs(module.Tokens) do 
    if v == id then
        print'removing' 
        table.remove(module.Tokens, index)
    end 
end
end

Is there some sort of algorithm or better logic I can use? (Also if you can, point out what I did wrong with the code above?)




How to initialize WELL512 pseudorandom number generator?

I have a WELL512a pseudorandom number generator implementation, but don't know really what is the proper way to initialize it.

The generator has an array of 16 unsigned integers as its state that should be populated. I could use current timestamp, but how? As first entry in the mentioned state array or maybe timestamp should be broken into bits somehow?




Same random guarantee

I have got this code:

BigInteger bigInteger = new BigInteger(64, new Random());
Long longValue=-Math.abs(bigInteger.longValue());
int desiredLen=384;
Random random=new Random(longValue);
byte [] randomString=new byte[desiredLen];
for(int i=0;i<desiredLen;i++)
    randomString[i]=(byte)(Math.abs(random.nextInt())&255);

Now there are these values:

  • longValue - is sent to other side (server) and later used to generate key again on other side
  • randomString - is encryption key generated randomly based on longValue

Simply, client sends message containing first 8 bytes longValue and other stuff is encrypted content by randomString.

What is guarantee that numbers will be generated exactly same on all machines and virtual machines and all Java versions based on received longValue? And how about if client is written in other language like C#?




Wordpress – Random post order

I want to have a random post order, but it does not work: The order of the posts is still by date. Can you help me?

http://ift.tt/1eLWo0C

<!-- T H E   L O O P -->  


<?php query_posts(array('post_type' => 'post', 'orderby' => 'rand', 'posts_per_page' => -1)); ?>
<?php if ( have_posts() ): $i = 0;  ?>

<?php while ( have_posts() ) : the_post(); $i++; ?>

<div class="article-content <?php if ($i % 7 == 0) echo 'seventhclass'?>" id="post-<?php the_ID(); ?>">

<div class="article-thumb">

<?php the_content(); ?>


<!-- Close article-thumb -->
    </div>

<!-- Close article-content -->

</div>

<?php endwhile; ?>


 <!-- /T H E   L O O P -->  




prevent repetition of the numbers by not use of Collection Shuffle [Java]

I used random function in my code however i dont know how could i prevent repetition.Also i read another questions about this subject but i dont want to use "Shuffle".

I have different group of machines and i want to get randomly number of atn machine.

Random rand = new Random();
int range = 20;
for(int j = 1; j <= Const.GROUPA; j++)
{
    String group1 = String.valueOf(j);
    String atn = String.valueOf(rand.nextInt(range-1) + 1);  // +1 prevents the getting 0 value.
    String output1 = "ATN number " + atn + " from group number " + group1 +"A";
    System.out.println(output1);
}

Output :

ATN number 12 from group number 1A
ATN number 1 from group number 2A
ATN number 7 from group number 3A
ATN number 12 from group number 4A   // 2 times number 12!

Thanks for all help and clues.




Create New String with Several Random New Line

I have a string:

String text = "Nothing right in my brain. Nothing left in my brain"

I want to create a new string text2 that has 2-4 random new line from previous, such as:

"Nothing \n right \n in my brain.  \n Nothing left in my brain"

or

"Nothing right in \n my brain. Nothing left in \n my brain"

How to create a new string with random new line between the words? I am thinking to get the index of whitespace, in order to insert new line after random whitespace. But I only keep getting the first whitespace index. Anyone know better approach to solve this? Thank you.




Generating random string of fixed length [duplicate]

This question already has an answer here:

I want to generate a 6 character long unique key in php in which first 3 should be alphabets and next 3 should be digits.

I know about the uniqid() function but it generates 13 characters long key and also it wont fit in my requirement as I need first 3 characters as alphabets and next 3 as numbers.

Any way in which I can modify uniqid() to fit in my requirements?

I also dont want any collisions because if that happens my whole database will be wasted that is why I can't use rand function because it is very likely that I will get collisions




jeudi 25 juin 2015

Generate a random floating point, with no range constraint, but including +inf, -inf, NaN, in python

Python's random number generator allows us to generate a floating point in some range. I wonder how can we generate a floating point number without the range constraint. The random floating point number I want to generate can be NaN, +inf, -inf, or any number in between the minimal and maximal floating point number.

I am looking for a pythonic solution. Thanks.




How to comple the Matrix[4][4] randomly with the numbers I already have?

I am with a doubt about the memory game that I need to create. I made a fixed matrix of the size [4][4]. The number of cards have to be increased according to the difficulty the user had choosen. So here is an example of the logic:

In DIFFICULTY 1 -> There will only be 3 equal pairs into the matrix like:{1,1}{4,4}{5,5}, these numbers have to be randomized but in pairs, so after that I can complete the matrix.

DIFFICULTY 2 -> There will only be 3 equal pairs into the matrix - {1,1}{4,4}{5,5}{3,3} - and again it need to me random numbers in pairs, so after that I can complete the matrix.

DIFFICULTY 3 -> complete the matrix, of the size [4][4], with pair of numbers randomly.

Probably you should take a look at the

for(i=0;i<lim_linha;i++)

my code:

void preencher_mesa(int matriz[4][4], int dificuldade)

{

    int i,j;
    int cartas[7][1]; //cards
    int cont =1; //count
    int lim_col, lim_linha; //limit_colunm //limit_line

    for(i=0; i<4; i++)
        for(j=0;j<4;j++)
            matriz[i][j] = 0;

    if(dificuldade == 1)   //difficulty == 1
    {
        lim_col = 3;                       //estabelecendo limites para que não ultrapaasse o valor da mesa
        lim_linha = 2;
    }
    else if(dificuldade == 2)
    {
        lim_col = 4;
        lim_linha = 2;
    }
    else if(dificuldade == 3)
    {
        lim_col = 4;
        lim_linha = 4;
    }

    for(i=0;i<lim_linha;i++)                        //setando os numeros aleatórios para dentro das
    {                                               // matrizes de acordo com o nivel de dificuldade
        for(j=0; j<lim_col;j++)
        {
                if(dificuldade == 1)
                {

                      int aux=0;
                       while(cont>=1 && cont <=8)
                    {
                        cartas[i][0] = cont;
                        cartas[i][1] = cartas[i][0];                                        
                        cont++;
                        printf("[%d]\n",(rand()%1 +(cartas[i][0])));
                        printf("[%d]\n",(rand()%1 +(cartas[i][1])));
                    }
                 }
             }
}

//Gerando numeros aleatórios em pares por isso [0] e [1]
//sorting numbers in pairs to stabilish the numbers of cards 
//{1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8}

PS: the range of random number should be 1-8 and I cannot have two, or more, same pairs of numbers.




Making functions that set the random seed independent

Sometimes I want to write a randomized function that always returns the same output for a particular input. I've always implemented this by setting the random seed at the top of the function and then proceeding. Consider two functions defined in this way:

sample.12 <- function(size) {
  set.seed(144)
  sample(1:2, size, replace=TRUE)
}
rand.prod <- function(x) {
  set.seed(144)
  runif(length(x)) * x
}

sample.12 returns a vector of the specified size randomly sampled from the set {1, 2} and rand.prod multiplies each element of a specified vector by a random value uniformly selected from [0, 1]. Normally I would expect x <- sample.12(10000) ; rand.prod(x) to have a "step" distribution with pdf 2/3 in the range [0, 1] and 1/3 in the range [1, 2], but due to my unfortunate choice of identical random seeds above I see a different result:

x <- sample.12(10000)
hist(rand.prod(x))

enter image description here

I can fix this issue in this case by changing the random seed in one of the functions to some other value. For instance, with set.seed(10000) in rand.prod I get the expected distribution:

enter image description here

Previously on SO this solution of using different seeds has been accepted as the best approach to generate independent random number streams. However, I find the solution to be unsatisfying because streams with different seeds could be related to one another (possibly even highly related to one another); in fact, they might even yield identical streams according to ?set.seed:

There is no guarantee that different values of seed will seed the RNG differently, although any exceptions would be extremely rare.

Is there a way to implement a pair of randomized functions in R that:

  1. Always return the same output for a particular input, and
  2. Enforce independence between their sources of randomness by more than just using different random seeds?



Vectorized sampling of multiple binomial random variables

I would like to sample a few hundred binomially distributed random variables, each with a different n and p (using the argument names as defined in the numpy.random.binomial docs). I'll be doing this repeatedly, so I'd like to vectorize the code if possible. Here's an example:

import numpy as np

# Made up parameters
N_random_variables = 500
n_vals = np.random.random_integers(100, 200, N_random_variables)
p_vals = np.random.random_sample(N_random_variables)

# Can this portion be vectorized?
results = np.empty(N_random_variables)
for i in xrange(N_random_variables):
    results[i] = np.random.binomial(n_vals[i], p_vals[i])

In the special case that n and p are the same for each random variable, I can do:

import numpy as np

# Made up parameters
N_random_variables = 500
n_val = 150
p_val = 0.5

# Vectorized code
results = np.random.binomial(n_val, p_val, N_random_variables)

Can this be generalized to the case when n and p take different values for each random variable?




generate non-consecutive samples

How can we efficiently generate k random and non-consecutive samples out of [1,...,N]?

Non-desired Example with (N=10, k=4): 2,3,8,10

This is not a desired example since 2 and 3 are consecutive.

Desired Example with (N=10, k=4): 2,6,8,10

This is a good example since the difference between every pair of samples is greater than 1




Generate a Random number in Uppaal

My question is Can I generate a random number in Uppaal?

I would like to generate a number from a range of values. Even more, I would like to generate not just integers I would like to generate double values as well.

for example: double [7.25,18.3]

I found this question that were talking about the same. I tried it. However, I got this error: syntax error unexpected T_SELECT.

It doesn't work. I'm pretty new in Uppaal world, I would appreciate any help that you can provide me.

Regards,




What is the difference between `random.seed` and `numpy.random.seed`?

I'm using Scikit-learn and Numpy and I want to set the global seed so that my work is reproducible.

Should I use np.random.seed or random.seed?




How to change bitmap without adding another child to the stage

I know exactly what this function is doing, however I don't know how to change it so that the 3 symbols only ever add once and only the bitmaps change. Thank you for your help! It's probably something simple, but I can't seem to figure it out, I am an intermediate as3 programmer but still have some holes in my knowledge.

var randCount:int = 3
        function loadImage():void
        {
            for(var i:int = 0; i<randCount; i++)
            {
                var imgLoader:Loader = new Loader();
                var imgRequest:URLRequest = new URLRequest();
                imgRequest.url = "../img/planet" + int(2*Math.random()) +".png";
                trace(imgRequest.url);
                imgLoader.load(imgRequest);
                imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
            }
        }

        function onLoadedImg(e:Event):void
        {
            e.currentTarget.removeEventListener(Event.COMPLETE, onLoadedImg);
            var bmp:Bitmap = e.currentTarget.content;
            bmp.x = 600;
            bmp.y = Math.random() * 520;
            bmp.width = 80;
            bmp.height = 80;
            addChild(bmp);

        }
button.addEventListener(MouseEvent.CLICK, changeBitmap);
        function changeBitmap(event:MouseEvent):void {
            loadImage();
        }




Trying to produce different random numbers every time a loop is executed

SRate = [5,5,5]
Bots = 120
NQueue = 3
TSim = 100
Exp = 2
DDistance = 1
Lambda = 40 # 120/3 = 40
import random

Elist=[]
AvgSRate = 5
def Initilization(AvgSRate,Lambda,Exp):
    return float((Lambda/(AvgSRate**Exp))*(1+(1/10)*(2*(np.random.seed(-28)) - 1)))

for a in range(1,361):
    Elist.append(Initilization)

I am trying to produce a set of randomly generated numbers between 0 and 1, so decimals for the initialization of a simulation, however It spits out the same values every time the loop is executed, so when I print Elist I get a list of all the same values. Also the list has <Function Initialization at "the number">, could someone help me eliminate that portion from the printed list to only have the numbers.




Python Csvwriter Randomize Rows

Is it possible to make a randomizer that randomizes entire rows using the csvwriter? The code I have is similar to this:

 for i in range(45):
    count=count+1
    writer.writerow((count,pattern))

Where pattern is a number which corresponds to count. For example: when count=1 pattern=1; count=2 pattern=9; count=3 pattern=17, and so on... I want a way to randomize the rows so that the correct count corresponds to the correct pattern still. Any help is greatly appreciated!




Random number generation algorithm

I encountered a naive algorithm for random number generation that produce a series of numbers as follows:

for (int i = 0; i < MAX; i++)
   if (rand.nextInt(100) >= 100 - probability) // probability is between 0 and 100
       randomNumbersList.add(i);

I was wondering if there's a way to achieve statistically equivalent results without iterating through each number between 0 and MAX.




Quiz with polish and english months

I'm doing a simple quiz where you getting an question "How is called month xxx in polish?". I've done an array list with the months, random which taking the month from the list, but I don't know how can I check if the typed month is correct. Any ideas? Here is my code with what I've done so far;

Random random = new Random();
            string[] miesiac = { "STYCZEŃ", "LUTY", "MARZEC", "KWIECIEŃ", "MAJ", "CZERWIEC", "LIPIEC", "SIERPIEŃ", "WRZESIEŃ", "PAŹDZIERNIK", "LISTOPAD", "GRUDZIEŃ" }; //months in polish
            string randommonth = (miesiac[random.Next(12)]);
            Console.WriteLine("Cześć, proszę powiedz mi jak jest " + randommonth + " po angielsku.");
            string answer = Console.ReadLine();

And here I am stuck because I do not know how to check if the answer is going to be correct or not.




Random Picker in Google Sheet

On Sheet1, Column A:A, I have a long list of items. On Sheet1, Column B:B, I would like to mark if item in A:A has been chosen.

On Sheet2, it will be a picture/ button, when clicked, it will show a random item from Sheet1 A:A, where Sheet1 B:B is empty.

Thereafter Sheet1 B:B will be marked, so that the same item in Sheet1 A:A will not appear again.

Can any expert teach me how this can be written in Google script? Many thanks in advance.




mercredi 24 juin 2015

How to sort SELECT results randomly, but in "groups" (NOT grouped by)

I have an SQLITE database with info about music files - i.e. with album, track columns (and some more, but for simplicity I will leave them out).

[table SONGS]
ALBUM     TRACK
A1        1
A1        2
A2        1
A2        2
A3        1
A3        2
A4        1
A4        2

I know I can do SELECT album, track FROM songs ORDER BY random(), but I will get the albums scrambled like:

ALBUM     TRACK
A4        2
A3        2
A2        1
A1        1
A3        1
A1        2
A2        2
A4        1

And I want to randomize the order, but keep the albums together, like:

ALBUM     TRACK
A3        1
A3        2
A2        1
A2        2
A1        1
A1        2
A4        1
A4        2

How can I do that? I tried many things (with an additional table with SELECT DISTINCT album FROM songs ORDER BY random()), but none of that worked.

I know I can do that in code (I'm writing in XOJO), but I want to use SQLITE to do that...




Algorithms for selecting a number uniformly randomly from a subset of integers

Suppose that int array a[i]=i, i=0, 1, 2, ..., N-1. Now given that each integer would associate with a bit. I need an algorithm to uniformly randomly select an integer from the subset of integers whose associated bit are 0. It is assumed that the total number of integers whose associated bit are 0 is already given in a variable T.

One straightforward solution I have is to generate r=rand() % T, and then find the r-th integer whose associated bit is 0 (by testing i=0,1,...). However, I wonder would there be any decent algorithms for doing this? Also, if say that the associated bits are stored in some long int variables (which is true in my case), finding the r-th integer whose associated bit is 0 would not be a easy task.

Thanks for your inputs.




Generating a random number not already duplicated in a DoublyLinkedList

I am encountering some difficulty with an algorithmic issue, and it would be great if anyone had some advice.

I have a doubly linked list, and each node holds a string and an integer. The goal is to take a number of specified nodes, delete them, and add a new single, "merged" node at the end of the list. This I have done. However, I also want this new node to have a random four digit integer that does not already exist in the list.

So far I have the following: ('list' is the name of the linked list, 'cur' is the node I am using to iterate through the list.)

int num = (int)(Math.random ()*9999)+1000;
while (cur != null){
    while (num == cur.getNumber())
          num = (int)(Math.random ()*9999)+1000;
    cur = cur.getNext();
} 

Unfortunately, this code allows for the possibility of being halfway through the list and generating a number that already exists in the first half, which I do not want...

Thank you in advance for your help.




r dplyr sample_frac using seed in data

I have a grouped data frame, in which the grouping variable is SEED. I want to take the groups defined by the values of SEED, set the seed to the value of SEED for each group, and then shuffle the rows of each group using dplyr::sample_frac. However, I cannot replicate my results, which indicates that the seed isn't being set correctly.

To do this in a dplyr-ish way, I wrote the following function:

> ss_sampleseed <- function(df, seed.){
>   set.seed(df$seed.)
>   sample_frac(df, 1)
> }

I then use this function on my data:

> dg <- structure(list(Gene = c("CAMK1", "ARPC4", "CIDEC", "CAMK1", "ARPC4", 
> "CIDEC"), GENESEED = c(1, 1, 1, 2, 2, 2)), class = c("tbl_df", 
> "tbl", "data.frame"), row.names = c(NA, -6L), .Names = c("Gene", 
> "GENESEED"))

> dg2 <- dg %>%
>   group_by(GENESEED) %>%
>   ss_sampleseed(GENESEED)

> dg2
Source: local data frame [6 x 2]
Groups: GENESEED

   Gene GENESEED
1 ARPC4        1
2 CIDEC        1
3 CAMK1        1
4 CIDEC        2
5 ARPC4        2
6 CAMK1        2

However, when I repeat the above code, I cannot replicate my results.

> dg2
Source: local data frame [6 x 2]
Groups: GENESEED

   Gene GENESEED
1 ARPC4        1
2 CAMK1        1
3 CIDEC        1
4 CAMK1        2
5 ARPC4        2
6 CIDEC        2

Any help is appreciated. Thanks.




How to Generate the ID of a Random Toggle Button, Then SetChecked(True) That Specific Toggle Button

I have two ToggleButtons and I want to be able to randomly select the id of one of those buttons, and set check that button to true. I tried This but is does not work as setChecked is not available for an Int or String. Any help would be much Appreciated.

int[] buttonIds = new int[] {R.id.player1Button, R.id.player2Button};
Random rand = new Random();
int num = rand.nextInt(buttonIds.length);
int buttonId = buttonIds[num];
findViewById(buttonId).toString();
String randomButton = getString(buttonId);
randomButton.setChecked(true); /// THIS LINE OF CODE WILL NOT WORK




Fast modular multiplication modulo prime for linear congruential generator in C

I am trying to implement a random-number generator with Mersenne prime (2^31-1) as the modulus. Following working code was based on several related posts:

  1. How do I extract specific 'n' bits of a 32-bit unsigned integer in C?
  2. Fast multiplication and subtraction modulo a prime
  3. Fast multiplication modulo 2^16 + 1

However,

It does not work with unint32_t hi, lo;. Which means, I do not understand signed vs. unsigned aspect of the problem.

Based on #2 above, I was expecting the answer to be (hi+lo). Which means, I do not understand why the following statement is needed.

   if (x1 > r)
        x1 += r + 2; 

  • Can someone please clarify the source of my confusion?

  • Can the code itself be improved?

  • Should the generator avoid 0 or 2^31-1 as a seed?

  • How would the code change for a prime (2^p-k)?

--

#include <inttypes.h>
// x1 = a*x0 (mod 2^31-1)
int32_t lgc_m(int32_t a, int32_t x)
{
    printf("x %"PRId32"\n", x);
    if (x == 2147483647){
    printf("x1 %"PRId64"\n", 0); 
        return (0);
    }
    uint64_t  c, r = 1;
    c = (uint64_t)a * (uint64_t)x;
    if (c < 2147483647){
        printf("x1 %"PRId64"\n", c); 
        return (c);
    }
    int32_t hi=0, lo=0;
    int i, p = 31;//2^31-1
    for (i = 1; i < p; ++i){
       r |= 1 << i;
    }
   lo = (c & r) ;
   hi = (c & ~r) >> p;
   uint64_t x1 = (uint64_t ) (hi + lo);
   // NOT SURE ABOUT THE NEXT STATEMENT
   if (x1 > r)
        x1 += r + 2; 
   printf("c %"PRId64"\n", c);
   printf("r %"PRId64"\n", r);
   printf("\tlo %"PRId32"\n", lo);
   printf("\thi %"PRId32"\n", hi);
   printf("x1 %"PRId64"\n", x1); 
   printf("\n" );
   return((int32_t) x1);
}

int main(void)
{
    int32_t r;
    r = lgc_m(1583458089, 1);
    r = lgc_m(1583458089, 2000000000);
    r = lgc_m(1583458089, 2147483646);
    r = lgc_m(1583458089, 2147483647);
    return(0);
}




How to generate random numbers with a set number of duplicates > 0

Is there a specific way to generate random numbers and only obtaining x amount of duplicates of each number in java with Random?




Why would faker produce duplicate data?

I'm using Faker in order to seed a database, I'm doing this using faker methods and lodash#random.

Data generation is inside a loop, but on every execution is producing whole duplicates, how can I avoid it?

faker.locale = "es";
var leagueTeams = [{ "name" : "Perú","id" : "t834"},{"name" : "Venezuela","id" : "t833"},{"name" : "Argentina","id" : "t632"},{"name" : "Uruguay","id" : "t837"},{"name" : "Colombia","id" : "t832"},{"name" : "Bolivia","id" : "t836"},{"name" : "Jamaica","id" : "t1723"},{"name" : "Brazil","id" : "t614"},{"name" : "Mexico","id" : "t659"},{"name" : "Ecuador","id" : "t830"},{"name" : "Chile","id" : "t831"},{"name" : "Paraguay","id" : "t835"}]


for (var i = 0; i < 10; i++) {

    var fakeName = faker.name.findName();
    var fakeEmail = faker.internet.email();
    var fakePassword = faker.internet.password();
    var fakeTeam = faker.hacker.phrase();
    var fakeTeamImage = faker.image.imageUrl();
    var fakeFavoriteTeam  = leagueTeams[_.random(0,11)];
    var fakeBirthday = faker.date.past();

    // Create account
    request.post(  {url:'http://localhost:1337/api/v1/auths/login',
                    form:   {
                                email: fakeEmail,
                                password: fakePassword,
                            }
                    },
                    function (err, httpResponse, body) {

                            body = JSON.parse(body);
                            var iduser = body.user.id;
                            var auth = "Bearer " + body.token;

                            // Create team

                            request.put({
                                            url: 'http://localhost:1337/api/v1/users/' + iduser,
                                            form: {
                                                    name: fakeName,
                                                    gender: ['male','female'][i%2],
                                                    team: {name: fakeTeam, image: fakeTeamImage},
                                                    fanOf: {
                                                        name: fakeFavoriteTeam.name,
                                                        id: fakeFavoriteTeam.id
                                                    },
                                                    birthDate: fakeBirthday,
                                                    iduser: iduser
                                            },
                                            headers: {"Authorization": auth}
                                        },
                                        function (err, httpResponse, body) {
                                            console.log(body);
                                        }
                            );
                    });
}

So whole faker methods like faker.internet.findName(), faker.hacker.phrase() or the statement using lodash var fakeFavoriteTeam = leagueTeams[_.random(0,11)]; is always producing the same result, how could I improve it?




my c++ random number is not random

I am running this

#include <boost/mpi.hpp>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
namespace mpi = boost::mpi;

int main()
{
    mpi::environment env;
    mpi::communicator world;



    srand (time(NULL));
    std::srand(time(0) + world.rank());
    int my_number = std::rand();
    if (world.rank() == 0) {
        std::vector<int> all_numbers;
        gather(world, my_number, all_numbers, 0);
        for (int proc = 0; proc < world.size(); ++proc)
            std::cout << "Process #" << proc << " thought of "
            << all_numbers[proc] << std::endl;
    } else {
        gather(world, my_number, 0);
    }

    return 0;
}

to distributively generate random number, however, it gives me the number around the same magnitude everytime....

dhcp-18-189-66-216:ising2 myname$ make
mpic++ -I/usr/local/include/boost -L/usr/local/lib -lboost_mpi -lboost_serialization main.cpp -o main
mpirun -n 4 main
Process #0 thought of 238772362
Process #1 thought of 238789169
Process #2 thought of 238805976
Process #3 thought of 238822783
dhcp-18-189-66-216:ising2 myname$ make
mpic++ -I/usr/local/include/boost -L/usr/local/lib -lboost_mpi -lboost_serialization main.cpp -o main
mpirun -n 4 main
Process #0 thought of 238805976
Process #1 thought of 238822783
Process #2 thought of 238839590
Process #3 thought of 238856397
dhcp-18-189-66-216:ising2 myname$ make
mpic++ -I/usr/local/include/boost -L/usr/local/lib -lboost_mpi -lboost_serialization main.cpp -o main
mpirun -n 4 main
Process #0 thought of 238856397
Process #1 thought of 238873204
Process #2 thought of 238890011
Process #3 thought of 238906818
dhcp-18-189-66-216:ising2 myname$ 

In the website, http://ift.tt/1LuAXhT , others said they get:

Process #0 thought of 332199874
Process #1 thought of 20145617
Process #2 thought of 1862420122
Process #3 thought of 480422940
Process #4 thought of 1253380219
Process #5 thought of 949458815
Process #6 thought of 650073868

I am very confused.... Any help? Thank you.




Perfect Randomizer

I am trying to make an array, shuffle it, then go through it in order. However, when I shuffle it (START) more than once, it messes up! Also When you get to the last number in the randomized array, it messes up also! please help and thank you!

JS

var minnum = 1;
var maxnum = 104;

function start() {
  var nums = [];
  while(minnum < maxnum+1){
  nums.push(minnum++);
}

function shuffle(o) {
  for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
  }
  var randomnum = shuffle(nums);
  document.getElementById('txt').innerHTML = randomnum;
  localStorage["nums"] = JSON.stringify(randomnum);
  localStorage.setItem("current", 0);
}

function Link() {
  if (localStorage.getItem("current") === null || localStorage.getItem("nums") === null) {
    start();
  }
  var current = localStorage.getItem("current");
  var nums = JSON.parse(localStorage["nums"]);
  document.getElementById('txt').innerHTML = nums;
  document.getElementById('txt1').innerHTML = nums[current];
  current++;
  if(current > 103) {
    location.reload();
    start();
    current = 0;
  }
  localStorage.setItem("current", current);
}

HTML

<body>
  <input type="button" onclick="start()" value="Start" />
  <span id="txt"></span>
  <input type="button" onclick="Link()" value="Next" />
  <span id="txt1"></span>
</body>




Python Custom Zipf Number Generator Performing Poorly

I needed a custom Zipf-like number generator because numpy.random.zipf function doesn't achieve what I need. Firstly, its alpha must be greater than 1.0 and I need an alpha of 0.5. Secondly, its cardinality is directly related to the sample size and I need to make more samples than the cardinality, e.g. make a list of 1000 elements from a Zipfian distribution of only 6 unique values.

@stanga posted a great solution to this.

import random 
import bisect 
import math 

class ZipfGenerator: 

    def __init__(self, n, alpha): 
        # Calculate Zeta values from 1 to n: 
        tmp = [1. / (math.pow(float(i), alpha)) for i in range(1, n+1)] 
        zeta = reduce(lambda sums, x: sums + [sums[-1] + x], tmp, [0]) 

        # Store the translation map: 
        self.distMap = [x / zeta[-1] for x in zeta] 

    def next(self): 
        # Take a uniform 0-1 pseudo-random value: 
        u = random.random()  

        # Translate the Zipf variable: 
        return bisect.bisect(self.distMap, u) - 1

The alpha can be less than 1.0 and the sampling can be infinite for a fixed cardinality n. The problem is that it runs too slow.

# Calculate Zeta values from 1 to n: 
tmp = [1. / (math.pow(float(i), alpha)) for i in range(1, n+1)] 
zeta = reduce(lambda sums, x: sums + [sums[-1] + x], tmp, [0])

These two lines are the culprits. When I choose n=50000 I can generate my list in ~10 seconds. I need to execute this when n=5000000 but it's not feasible. I don't fully understand why this is performing so slow because (I think) it has linear complexity and the floating point operations seem simple. I am using Python 2.6.6 on a good server.

Is there an optimization I can make or a different solution altogether that meet my requirements?




C++ What is contained in the lower 32 bits: Seeding mt

I have a line of code that uses a nano second grab of the high precision clock to seed mersenne twister psudo-random number generator. Something along the lines of this:

rng.seed(duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch().count());

I know that mt in boost can only take in 32 bit integers (which is what seed() takes) and that this duration cast to nanoseconds to is at least 64 bits (I also know that this code will cause a conversion warning that can be taken care of with a static_cast).

My question is when this cast to a 32 bit integer what will be the contents of those bits. I know that the lower 32 bits are what the compiler keeps when casting from a 64 bit integer to a 32 bit integer. I am also on a little endian machine. Since I know the current epoch time in seconds is ~1.4*10^9, Will those lower 32 bits be the first ~10 digits of the epoch time or since this is little endian will it be the random gibberish at the end?

Any advice or points to reading are much appreciated.




How can I create a column of random numbers within set limits?

I need to create a 60x1 column that refers to a set of 10 images (1-10). Each image needs to be referred to 6 times, but in a randomised order. How can I create a randomised column that is within these limits? i.e. that references to image number 5 are randomly distributed but do not appear in the matrix more or less times than 6. I have read the matlab documentation on rand, randi, etc but I can't seem to see anything about this.

Thanks




mardi 23 juin 2015

Is there a way I can get a random number from 0 - 1 billion?

I'm not caring for efficiency right now. I'm just looking for a decent way I can generate random numbers from 0 through 1 billion. I've tried doing rand() * rand() but it's been giving me only numbers estimating greater than about 10 million. I would like the range to be way more spread out. Anyone have any suggestions?




Select one value randomly from 5 values in sas

I have a list of 40000 ids. They are the controls for cases such that every case has 5 controls. So, 8000 cases have 40000 controls.

Now I want to select one control of five for each case randomly. I am using SAS. Any ideas?




NetLogo: excluding items from a list after they have already been chosen

I am using the setxy function to set the area that my turtles will be placed in. I made a list of the x values and y values. But I don't want more than 1 turtle at the same point. I'm not sure how to stop this from happening. This is the code that I am using for this: create-vcells 20 [ setxy one-of [0 0.6 1.2 1.8 2.4 3] one-of [0 0.6 1.2 1.8 2.4]

Does anyone have any insight? Thanks!




How to predict with low standard deviation the outcome of a system that uses random numbers with uniform distribution?

I am working with a system that generates a number of [0, 16] integers using Math.random, an ECMA Script random number generator with uniform distribution within the [0, 1[ range.

I would like to kind of "average" or "predict" the next rolls so that there is no more randomness but instead an accurate modelling of how the system works.

Because of the uniform distribution, there is going to be huge variance and a large standard deviation if I simply take the mean average from the [0, 16] range, i.e. 8.

So, is it possible to do better than a mean average ? My understanding is that this method gives a variance of 25.5 and a standard deviation of 5.05, which is pretty terrible when you have a range of 17.

I would like to reduce the standard deviation to something like 0.1 if at all possible, knowing that the system I am trying to predict will keep using uniform random numbers: I'm merely trying to predict, not change the system.

I found something called "standard normal distribution", which can be accurately approximated by adding together 12 uniform random numbers [0, 1[ and subtracting 6 to the result. But I'm not sure if or how I can use this. It sounds like it's changing the data, but if the system keeps using uniform random numbers, how can converting uniform distribution to normal in the model help predict outcomes with a low standard deviation ?

Thanks if you can help, I hope it is clear enough.

PS: I suck with probability notations and vocabulary.




Can $_SERVER["REMOTE_PORT"] be repeated for more than one device at the same time

I try to make function that generate random id using $_SERVER["REMOTE_PORT"] and microtime() , so i ask if if $_SERVER["REMOTE_PORT"] Can be repeated for more than one device at the same time




Cryptographically secure PRNG (PseudoRandom Number Generator)

What is the best and fastest algorithm to generate cryptographically secure PRNG? My requirements is as follows.

  • In each run, I need to generate few millions of numbers with length of 10.
  • It should not allow one to predict future iterations by observing some number of iterations.
  • Numbers should be unique. No duplicates allowed.
  • Speed is also important since it will generate millions of numbers in each iteration.

I checked Mersenne Twister algorithm but it seems it is not cryptographically secure. They said, it could be predicted by checking 624 iterations.

P.S. It would be better if there is a Java Implementation.




lundi 22 juin 2015

Haskell - generate an use the same random list

In Haskell, I'd like to generate a random list of Ints and use it throughout my program. My current solution causes the array to be created randomly each time I access \ use it.

How can I overcome this problem?




Using rand() to get a number but that number can't be the number that was last generated

I want to use std::rand() to generate a number between 0 and amountOfNumbers, but the generated number can't be the same number that was last generated.

I wrote this function:

void reroll() {
  int newRand;

  while (true) {
    newRand = std::rand() % (amountOfNumbers);
    if (newRand == lastNumber) {
      continue;
    }
    lastNumber = newRand;
    break;
  }

  // do something with newRand
  // ...
}

amountOfNumbers is just an int (> 1) that defines the upper bound (e.g. 5 so the possible number range is 0 to 4). lastNumber which is initially -1 stores the last generated number.

I was wondering if there's a better way to write this.

The function seems to be working so far, but I'm not sure if my code is flawless... it looks kind of bad. That while (true) makes me feel a bit uneasy.




loop that will generate math problems until told to stop

I am learning how to use random and math functions but I never really understood loops. so lets say I need a loop that will ask random math problems until told to stop. For something simple like addition of numbers from 0 to 9 how do I write a loop that keeps generating problems. this is an example of a how it can look like:

Math()
Are you ready? yes 
0 + 5 = 5
4 + 9 = 13
3 + 2 = 89
7 + 7 = 14 
5 + 4 = 9
1 + 8 = stop

so far I have this but I don't know how to make a loop:

def Math():
    ready=input('Are you ready?')
    num1 = int(random.randint(0,10))
    num2 = int(random.randint(0,10))
    if ready = 'yes':
        while result != 'stop':
            num1+'+'+num2 = result

I honestly have no idea how to make a while loop. please help me. Thank you




Randomly swapping file names in Python

I need to swap the names of all the files in a folder but each file has to have it's own unique name.

I tried to loop through the folder adding all the files to a list and then shuffling that list with random.shuffle(), and then looping through the folder again but this time renaming each file by order to the shuffled list.

It was something like this:

for file in os.listdir("images/"):
    os.rename(file, files_shuffle[i])
    i += 1

But I get WinError 183 "Cannot create a file when that file already exists". What would be the best way to approach this problem?




I need your help for my optimazation program?

hi everyone I have write a program in a optimizing software(Xpress) for a problem with known datas now for generalize this programm I need a program in java for randomize the Datas these are datas in my basic problem as you can see all the arrays have 6 characters that is number of periods (T=6) I need write a program that generate a 100% random T and with that random value of T generate the arrays with T characters (size of arrays =T ) and print like below arrays for T=6( with :: and , and [])

T=6

p2::[0,0,0,0,0,0]

h1::[100,2,2,2,100,0]

h2::[1,1,100,1,1,0]

C1::[10,10,10,10,10,10]

C2::[10,10,10,10,10,10]

K1::[100,100,100,100,100,100]

K2::[1,1,1,1,1,1]

d::[5,9,1,8,3,1]

I will be so thankful if someone help me




JAVA: RANDOM Array with Random length of array

I'm Industrial engineer Student and need your help, I want too write a program in java that make a random number (T= number of periods) then generate arrays of random numbers with T number , it means program must to scan T and make arrays of random numbers but with T character , can you help me?




C++ & Qt: Random string from an array area

In my small Qt application, I want to pick a random string out of an array after I clicked on a button. I've read many threads but nothing works for me.

So in my slot there's an array with several strings in it. I also implemented <string>, <time.h> and srand.

#include "smashrandom.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>

SmashRandom::SmashRandom(QWidget *parent)
    : QWidget(parent)
{
    // shortened version
    connect(button, SIGNAL(clicked()), this, SLOT(Randomizer()));
}

void SmashRandom::Randomizer()
{

    srand((unsigned int)time(NULL));

    std::string characters[6] = {"Mario", "Luigi", "Peach", "Yoshi", "Pac Man", "Sonic"};
}

But how can I pick a random string out of my array "characters"? Normally I use rand()% for int or double arrays, but in this case I don't know how to use it for random strings.

In addition to that, it is possible to select a random string from an area inside the array? For example I just want want a random string from Mario to Yoshi so Pac Man and Sonic can't even show up?

I hope you can understand my problem and thanks in advance. :)




Why do i get different result when sorting with one random seed?

I am using elasticsearch 1.3.2 in production with a node of 2 masters with data.

I have a realy strange behavior when i search with a fixed random seed on this cluster. I get exactly 2 different sortings of my results. It seems that every node holds its one random "seed" and depending which node delivers the result the sorting is different.

I want to get same sortings with the same seed.

How can i fix this issue?




dimanche 21 juin 2015

Default_random_engine as a parameter

I am trying to use std::shuffle to create a function that shuffles a word a certain way based on its length. I am not sure on how to use a default_random_engine as a parameter for a function. Does the default random generator need to have a seed before it can be used as a function parameter or can it seed within the function? Sorry if this is confusing, here is a snippet of this function:

string scramble_word(const string & word , default_random_engine& re){
if (word.length() > 3){
    shuffle(word.begin() + 1, word.end() -1, re(0));
    }
if (word.length() <= 3){
    shuffle(word.begin()+1, word.end(), re(0));
    }
return word;

}




srand in C - with just one repetition

i'm trying to build a memory game and I want to ask how I can generate a randomic number with just one repetition. Like 1-1, 2-2, 3-3. I will paste here my function that I created and tell me if I have to create another function just to create a condition to create just a pair from numbers.

void preencher_mesa(int matriz[4][4], int dificuldade) //function to fulfill the table {

int i,j;
int lim_col, lim_linha; //limits of the matriz



for(i=0; i<4; i++)
    for(j=0;j<4;j++)
        matriz[i][j] = 0;


if(dificuldade == 1)
{
    lim_col = 3;
    lim_linha = 2;

}
else if(dificuldade == 2)
{
    lim_col = 4;
    lim_linha = 2;
}
else if(dificuldade == 3)
{
    lim_col = 4;
    lim_linha = 4;
}

srand(time(NULL) );
for(i=0;i<lim_linha;i++)
{
    for(j=0; j<lim_col;j++)
    {
            if(dificuldade == 1)/dificulty ==1
            {
                matriz[i][j] = (rand()%3)+1;

            }
            else if(dificuldade == 2)//dificulty ==2
            {
                matriz[i][j] = (rand()%6)+1;


            }
            else if (dificuldade == 3) //dificulty ==3
            {
                matriz[i][j] = (rand()%8)+1;

            }



    }

}

 mostrar_mesa(matriz); //showtable

}




How to print a 2D array with random numbers

I am trying to write a program that prints a 2d array with random numbers ranging from 100-10000 and prints out the max number in the array,average,and min. The program will ask the user for the number of rows and column and print random numbers in that array.

Here is my code:

Random rand = new Random();

int randomnumber = rand.nextInt(9901) + 100;

Scanner console = new Scanner(System.in);

System.out.println("Enter row");
int n = console.nextInt();

System.out.println("Enter column");
int y = console.nextInt();

int[][] array = new int[n][y];
array[n][y] = randomnumber;

int k;
for (int i = 0; i <= array.length; i++) {
    for (k = 0; k <= array[i].length; k++) {
        System.out.print(array[i][k]);
    }
}




Two random walkers on a 2d plane

So I have this multithreadded program that generates 2 random walkers, each walker is a separate thread since I need them to move simultaneously. Each walker randomly moves in any of the 4 directions. The first problem is that i think stdDraw is not thread safe and therefore without having a lock around my entire function, it tends to draw random squares at random points for no reason and the whole thing become pretty glitchy. When i put a lock around my function then one thread becomes slower that the other since it sometimes has to wait for the lock. So the threas are not simultaneous anymore. Is there a solution to this? The other problem i have is I want it to break out of the loop when the two walkers intersect, but for some reason the two threads dont know about the position of the other. One thinks that the position of the other is always at (0,0). Thanks!

import java.awt.Color;
public class WalkerThread implements Runnable {

String name;
static Integer lock = new Integer(1000);
int num;
static int steps = 0, steps2 = 0;
static int x = 0, y = 0;
static int x2 = -1, y2 = -2;

public WalkerThread(String s, int n) {
    this.name = s;
    this.num = n;
}

@Override
public synchronized void run() {

    int N = 5;
    StdDraw.create(600, 600);
    StdDraw.setScale(-N, -N, +N, +N);
    StdDraw.clear(Color.gray);
    do {
        synchronized (lock) {

            if (num == 1) {
                StdDraw.go(x, y);
                StdDraw.setColor(Color.white);
                darker();
                StdDraw.spot(0.9, 0.9);

                double r = Math.random();
                if (r < 0.25)
                    x--;
                else if (r < 0.50)
                    x++;
                else if (r < 0.75)
                    y--;
                else if (r < 1.00)
                    y++;

                steps++;

                StdDraw.setColor(Color.blue);
                StdDraw.go(x, y);
                StdDraw.spot(0.9, 0.9);
                StdDraw.pause(400);

            }

            if (num == 2) {
                StdDraw.go(x2, y2);
                StdDraw.setColor(Color.yellow);
                StdDraw.spot(0.9, 0.9);
                double r2 = Math.random();
                if (r2 < 0.25)
                    x2--;
                else if (r2 < 0.50)
                    x2++;
                else if (r2 < 0.75)
                    y2--;
                else if (r2 < 1.00)
                    y2++;

                steps2++;
                StdDraw.setColor(Color.green);
                StdDraw.go(x2, y2);
                StdDraw.spot(0.9, 0.9);
                StdDraw.pause(400);

            }
        }// lock
        /*String pict = steps + ".png";
        StdDraw.save(pict);*/
            //if (posX == posX2 && posY == posY2) break;


    } while ((Math.abs(x) < N && Math.abs(y) < N) && (Math.abs(x2) < N && Math.abs(y2) < N));

    System.out.printf("Total steps of %s is %d and %d \n", name, steps, steps2);

}
}




find time taken by user to solve math problems

I need to write a program that will ask simple random addition problems and find the time it takes the user to solve this. The program should keep on asking math problems until told to stop. It should find the average of correct answers, the fastest answer and the average answer time. I started to write the program but it is not working, so I don't even know how to continue. I cannot get it to print the math problems. can you please show me what I am doing wrong and help me with how to find fastest question and average time per question as well as average for how many questions are correct? here is what the problem should look like when run:

>>> Math()
Are you ready? no
Okay fine
>>> Math()
Are you ready? yes 
0+5=5
4 + 9 = 13
3 + 2 = 89 1+5=6
3+3=9
1+7=8
7 + 7 = 14 5+4=9
1 + 8 = stop
You answered 75% problems correctly
Your average answer time is 1.4388 seconds
Your fastest answer time is 1.2247 seconds

this is what I have:

def fastMath():
ready=input('Are you ready?')
num1 = int(random.randint(0,10))
num2 = int(random.randint(0,10))
operator = '+'
math = ((num1)+ operator +(num2))
if ready == 'no':
    print ('Okay fine')
else:
    start=time.clock
    print (math)
    while math = true:
        print (math)




bash - Selecting random object from an array

I have a function that selects a random object form an array. I have wrapped the internal bash function RANDOM, and implemented my function like that:

function rand() { echo $[ $RANDOM % $2 + $1 ]; }
function rand_obj() { objs=($@); index=$(rand 1 $#); echo ${objs[$index]} ; }

It works just fine, but I would love to learn a way of implementing it without the intermediate array objs. Any ideas? Thanks in advance




Java save a int in a JTextfield when a boolean is true

When I clicked on my txtField, it sets a boolean true, second click it sets the boolean false.

When it is false, the int shouldn't change, when it is true, it should be changed. The boolean is often changed. But it doesn't work this.wat When I clicked the JTaxtFields, the color changed to red and in the Console it prints the right thing when it should be true, it it true. When it is Red, it is false. When it is false, it shouldn't change the int. But it changed the int when it is false. What is wrong?

private JTextField zahl1;
private JTextField zahl2;
private boolean rnd1 = false;
private boolean rnd2 = false;

//JtxtField

zahl1 = new JTextField();
     zahl1.setEnabled(false);
     zahl1.setEditable(false);
     zahl1.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {

            if ( rnd1 == false)
            {
                 rnd = true;
                 zahl1.setBackground(SystemColor.RED);
            }
            else if ( rnd == true)
            {
                 rnd = false;
                 zahl1.setBackground(SystemColor.menu);
            }

        }
    });

// Button to change

    JButton btnNewButton = new JButton("W\u00FCrfeln");
    btnNewButton.setBounds(720, 583, 141, 41);
    panel.add(btnNewButton);
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (rnd1 = true)
            {
                setzahl1(logic.Randoms());
            }
            if(rnd2 = true)
            {
                setzahl2(logic.Randoms());
            }
        }
    });

// create the randoms

public int Randoms()
{   
    rnd = NumGenerator(1,6);
    return rnd; 
}

public static int NumGenerator(int min, int max)
{ 
    Random rnd = new Random();
    int randomNumber = rnd.nextInt((max - min) + 1) + min;
    return randomNumber;
}