mercredi 28 février 2018

MATLAB-How can I randomly select smaller values with higher probabilities?

I have a column vector "distances", and I want to select a value randomly from this vector such that smaller values have a higher probability of being selected. So far I am using the following, where "possible_cells" is the randomly selected value:

w=(fliplr(1:numel(distances)))/100
possible_cells=randsample((sort(distances)),1,true,w)

Basically, I flipped the distance vector to create probabilities of selection "w" (if I am understanding randsample correctly), so that the smallest value has the probability of being selected equal to the highest value. To check how well this works, I randomly drew 50 values and by using a histogram, I see that the values are higher than I would expect. Does anyone have any idea on how else to do what I described above? 0 Comments




how to make the math.random stop?

Im trying to figure out how to make the Math.random stop. I have a confirm statement if the the user gets a write answer, it'll alert and ask to confirm. however, math random keeps asking a new question instead of stopping the script when the user clicks "cancel",also if the answer is wrong it shouldn't ask a new question unless the user gets it right. How do I correct this? (sorry Im a newbie, and thanks!)

<h1>Math Random</h1>
<hr>
<br>
<p id="question"></p>

<script>
    var x = Math.round(Math.random() * 10);
    var y = Math.round(Math.random() * 10);

    var outHTML = "How much is " + x + " times " + y + "?";

    document.getElementById("question").innerHTML = outHTML;

    function getAnswer() {

        if (parseInt(document.getElementById("answer").value) == x * y) {
            alert("Very Good!");
            confirm("Want more?");

        } else {
            alert("Try again!");

        }
    }

</script>

<form>
    <input id="answer" type="number" placeholder="answer here">
    <button onclick="getAnswer()">Submit</button>
</form>




How do I generate a random process value given a set of moments or cumulants?

How would a create a data set from a known set of data moments or cumulants.

Its fairly easy to generate a random number with a known variance and mean. I would like to get something that lets me submit an array of cumulants (or moments)

Example: (ci = cumulent, mi = momemts)
  c1 = m1 or ‘mean’
  c2 = m2 − m1 = σ2 or ‘variance’ (σ = standard deviation)
  c3 = m3 − 3*m1*m2 + 2*m3 or ‘skewness’
  c4 = m4 − 3*m2 − 4*m1*m3 + 12*m1*m2 − 6*m1 or ‘kurtosis' 

So I would like a function, f, that takes a bunch of ci values and produces a single data point whose array of historical values maintains the specified cumulants.

 y(i) = f(c1,c2,c3,..., and optionally [y(i-1), y(i-2), ...])

See Moments, Cumulants and Scaling




swift + firebase + query random object + sequential ID

I'm looking for an easy way to query my database in firebase using swift to retrieve a random object. I've read a lot of threads and there doesn't seem to be an easy way. One example showed it can be done be creating a sequential number but there's no information on how to create this sequential number for each record.

So either I need information on how to create a sequential number each time a record is created or if someone knows an easy way to retrieve a random record from a database that would be very helpful. In swift preferably.

My Database structure:

database structure




How to round a double to two decimals through Formatting, then using the number afterwards?

Im currently making a program that generates a random number and then calculates the amount of 20 dollar, 1 dollars, quarters, pennys etc it would take to make that number. This is what im using to calculate the double, with randomValue being the random double.

double rangeMin = 1;
double rangeMax = 100;
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin ) * r.nextDouble();

The problem I have is that it keeps giving me a double with 16 decimal places, so i tried using a formatter

Formatter fmt = new Formatter();
fmt.format("%.2f", x);

(its x because I sent randomValue through parameters to another class)

now my big problem is i cant use the number i formatted in anything. For example i cant use it in an if statement, as it gives me an error

    if(fmt > 1000) {
    System.out.print("it worked");
}

i know i cant compare a Formatter to an int in the same way i cant compare strings and longs, but how do i get the random double number i formatted or somehow change it back into a double so that i can use it?




Scipy randint vs numpy randint

I have a simple yet broad question regarding two methods:

scipy.stats.randint

and

numpy.random.randint

After reading the API for both methods I'm a bit confused as to when it is best to use each method; therefore, I was wondering if someone could outline the differences between the two and possibly offer some examples of when one method would be preferable to use over the other. Thanks!

Edit: Links to each method's documentation -> numpy.random.randint, scipy.stats.randint




How to generate random text from regex to fill an excel cell

Im creating a large amount of excel test files with different values in many columns.

These files are going to be imported into a database later using other unkown tool, so I just have to prepare only these files filled with valid data.

Each file has different columns, so different ranges of valid characters are necessary per column.

What would I want to do?

Use a Formula witch receive a regex and generate/and fill the cell with a random string based on that regex and if possible specify how many characters the string should be.

Can someone guide me in the creation of a macro to accomplish this purpose or suggest me a plugin to facilitate this work?




Generate specific date in bash

Hi I have written down some bash to generate the date in format YYYYDDMM.

I know that is not perfect but the final thing will be:

Generate a range of 2 dates that are 31 days apart from each other and start with a minimum of today + one day and the older ones end at the end of this year. In format YYYYMMDD

month="$(awk -v min=1 -v max=12 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')"
day="$(awk -v min=1 -v max=31 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')"
year="$(date +%Y)"



if (( "${month}" < 10 )); then
    month_proper="$(echo 0"${month}")"
else
month_proper="$(echo "${month}")"
fi
if (( "${day}" < 10 )); then
    day_proper="$(echo 0"${day}")"

else
day_proper="$(echo "${day}")"
fi



echo month "${month}"
echo month with 0 if smaller than 10 : "${month_proper}"
echo day "${day}"
echo day with 0 smaller than 10 : "${day_proper}"

ok="$(date -d ""$year""${month_proper}""${day_proper}"" +"%Y%m%d")"
echo date with proper format "${ok}"
date -d "$year""${month_proper}""${day_proper}"

In which direction would I have to expand this script to get the final result? I already have the date generation, but there is no checking if there is one day ahead of today.




Why isnt my Random array returning random values?

Okay, so essentially, what I want to do is create and print an array of 100 random numbers. My attempts seem to be failing... instead of getting 100 random numbers, I seem to be getting numbers put in order from 0-99. Can someone explain how I can resolve this issue, please? Much appreciated.

public static void enterRandom()
{
    System.out.println("Welcome to the random number generator and arranger!");
    System.out.println("Now, watch me generate 100 random numbers, and print them in order...");
    System.out.println("...");
    System.out.println("...");
    System.out.println("...");

    Random what = new Random ();
    int[] store = new int [100];

    for (int i = 0; i <= store.length; i++)
    {
        store[i] = what.nextInt(100); //not in random?
        System.out.println(i);
    }

    return;
}

}




How to oversample an array of n string elements into an array of m string elements

l would like to oversample an array of n element into an array of m elements such that m > n.

For instance let's take n=3

colors=['red','blue','green']

set m =7

What l'm looking for ?

 oversampled_colors=['green','blue','red','red','blue','green','blue']




How to obtain different random numbers in the same programme

I wrote this :

#include <boost/random.hpp>
#include <boost/random/normal_distribution.hpp>

int main()
{
  boost::mt19937 rng(time(0)); 
  boost::normal_distribution<> nd(0.0, 1.0);

  boost::variate_generator<boost::mt19937&, 
                       boost::normal_distribution<> > var_nor(rng, nd);
 double d = var_nor();
 }

d gives me random numbers as I want. How should I do if I need more random numbers LIKE THIS ONE in the same programme and in the same cicle for example?! Now I am seeding it with the time of th computer . And I am using the boost library.




Can't generate different random numbers in Python

I'm having this problem in python where I can't generate different random numbers in a loop. Every loop generates same numbers. My code looks like this:

import random

class Dna :
    genes = []
    lifespan = 0

    def __init__(self, lifespan) :
        self.lifespan = lifespan

        sum = 0
        for i in range(lifespan) :
            self.genes.append(PVector(random.randrange(-10, 10), random.randrange(-10, 10)))
            sum += self.genes[i].mag()

        print(sum)

Here, I'm trying to generate random vectors in the range -10 and 10 but every different DNA object prints the same sum. Here is the main file:

import dna

def setup() :

    size(600, 600)

    d = dna.Dna(200)
    d2 = dna.Dna(200)

And I'm using processing.py for this.




Battleship Game Java

I need to place ships randomly in to dynamic array with size 10 by 10. The data type of the ships is char, like 'x'and there are 4 types of ships 1,2,3 and 4 x ships. Program should place this ships in to array randomly. Can anyone explain how i can place this ships in to array randomly? import java.util.Random;

public class Source {

    public static void main(String[] args) {

        char arr[][] = new char [10][10];
        Random r = new Random();

        int x = r.nextInt(10);
        int y = r.nextInt(10);

        arr [x][y] = 'x';






        for(int i=0; i<arr.length; i++) {
            for(int j = 0 ; j<arr.length; j++) {
            System.out.println(arr[x][y]);

            }
        }       
    }
}




Assigning a random value to a variable

I'm very new to code so I might not understand some answers. I'm having trouble turning a variable into a random number between 1 and 10 in this code.

<script type="text/javascript">
var money = 0

function Random() {
  money = Math.floor((Math.random() * 10) + 1);
}
</script>

I've read that I need to put return followed by the randomizing code somewhere but I just don't understand where I place that on how I use it.




mardi 27 février 2018

Stratified random assignment [duplicate]

This question already has an answer here:

I need to use stratified random assignment of 8 subjects to control and treatment groups based on their body condition score (BCS) which can be high or low.

1. high
2. high
3. high
4. high
5. low
6. low
7. low
8. low

I need to randomly get 2 groups with equal number of high and low BCS in each group.




Random Sampling in R to give an exact sum

I want to sample 140 numbers between 1000 to 100000 such that the sum of these 140 numbers is around 2 million (2000000)

sample(1000:100000,140) such that sum(sample(1000:100000,140)) = 2000000

Any pointers how can I achieve this?




Unable to use pre-definded global variable outside function [duplicate]

This question already has an answer here:

I have the following random quote generator: https://jsfiddle.net/zachariepertgen/dxnqrkbf/7/

However, I am unable to access the currentQuote variable outside of the quote function.

My goal is to populate the currentQuote variable, so I can later append it to a URL to tweet the current quote.

My understanding is that by declaring the variable outside of the function, I have made it global, and it should be accessible anywhere in my script.

When I call the currentQuote variable to an alert dialog outside of the function I get undefined, however if I call it inside I sucessfully get the quote which leads me to believe it is a scoping issue.

var pickQuote;
var currentQuote;

function quote() {
pickQuote = Math.floor(Math.random() * (quotes.length));
currentQuote = quotes[pickQuote];
document.getElementById('demo').innerHTML = currentQuote;
}

document.addEventListener('DOMContentLoaded', quote, false);
window.alert(currentQuote); `

Please let me know if I am taking a wrong turn somewhere.

Thank you!




Python 3: Fastest and most efficient way to iterate randomly over all lines in a big file (+1 million lines)

Ok, so I have multiple textfiles, each containing well over 500.000 or even 1.000.000 lines.

Currently I do something like this:

import random

def line_function(line):
    # Do something with given line

def random_itteration(filepath):
    with open(filepath) as f:
        lines = f.readlines()
        shuffled_lines = random.shuffle(lines)
        for line in shuffled_lines:
            result = line_function(line)

The thing is that the Python Docs on random.shuffle() clearly state (emphasis added by me):

Note that even for small len(x), the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.

So the question is:

What would be the fastest and most efficient way to make my setup work as intended?

Further info:

There is a reason why I want to apply line_function() to a random line and not simply iterate over them in the sequence they are in. Also note that I highly prefer to only process each line once.

Finally, shuffling the textfile up front, or dividing it into smaller files unfortunately isn't an option. And isn't what I am asking.


Any insights are more then welcome! Thnx in advance guys.




Generating random integers according to a Boolean slice in Go

I want to generate random integer values where indices in a Boolean slice is true in an efficient way. As an example consider the following Boolean slice:

BooleanSlice = [false, false, true, false, true]

This slice has two indices which have the true value, index 2 and index 4. The algorithm should then pick randomly between values 2 and 4. This should hold for any Boolean slice.

One solution would be to generate a random integer and then check if that value is true in the Boolean slice, picking a new value if false. However, that method seems very inefficient if the slice is large and there are only a few true values.

Is there anyway optimal way to generate random numbers following the above requirements?




How does runif work with array?

I try to understand a small simulation code. However, I just confused about the result from runif function stored in an array.

Here is the code:

 N=10
 dim=3
 v = array(NA, c(dim, dim))
 x <- array(NA, dim=c(N, dim))
  for(s in 1:N)
     {
  w <- runif(dim)
  x[s,1] <- w[1]
  v[1,1] <- w[1]
  }
 x

w will be 3 uniform numbers. x[s,1] is the first column of x array. x[s,1] <- w[1] that means all the values in the first column must take the first value of the vector w. However, when I print x I got 10 different values. It is really confused me. When I try to use x[1,1] <- w[1], it works just fine! However, x[s,1] <-w[1] is just x[,1] <- runif(N) see the comments of @zx8754.

Do I miss something? How does this code work? Any help, please?




Oracle - updating table with single special character

I have table where I need to update one column with single random special character. So far I have tried two ways:

1) using dbms_random.string with 'P'

BEGIN
FOR I IN 1..100
  LOOP
    UPDATE
        my_schema.data_table
      SET
        special_char =
        (
          SELECT
              SUBSTR(regexp_replace (str,'[A-Za-z0-9<>"&]',''),1,1)
            FROM
              (
                SELECT
                    dbms_random.string('P', 20) str
                  FROM
                    dual
              )
        );
END LOOP;
COMMIT;
END;

2) creating a simple table with few rows which contain set of special character (1st row - !, second row - _ etc) and running this script:

DECLARE
  v_special_char VARCHAR2(5);
BEGIN
  FOR i IN 1..100
  LOOP
    SELECT
        special_char
      INTO
        v_special_char
      FROM
        (
          SELECT
              special_char
            FROM
              my_schema.char_table
            ORDER BY
              dbms_random.value
        )
      WHERE
        rownum = 1;
    UPDATE
        my_schema.data_table
      SET
        special_char = v_special_char;
    COMMIT;
  END LOOP;
END; 

But none of these works properly - each time column gets updated with the same character - ! or _

I'd be grateful for any help!




Generate binomial random variables based on inverse transformation in R

It's my first coding course at uni, and I'm stuck with the two algorithms asked below.

I've been asked to develop an algorithm in R that generates binomional random variables based on the inverse transformation. And to develop an algorithm again in R that generates Normal random variables based on the acceptance-rejection technique.

I've been looking around, but i'm not sure how to do it. I know there are internal R functions to generate random variables from different distributions (like: rnorm (n, mean, stddev) ) but I can't use them.




lundi 26 février 2018

Java: How to put values into a object from a list of randomly generated numbers

Ok so I am new to Java and this is what I need to do. Write a Java program that will allow a user to specify how many random numbers he/she would like to be generated between 1 and 100. Then produce the random and list them in your output. You should also compute the highest, lowest, sum and average. The part I need help on is getting the lowest and highest. I can't use arrays since we haven't really touched upon them yet. what I need help doing throwing something in int lowest from my randomInt.

public static void main(String[] args) 
{
     Scanner sc = new Scanner(System.in);
     Random rnd = new Random();
     int r;
     int sum = 0;
     int lowest=0;
     int highest=0;

     System.out.println("Please enter enter how many numbers "
             + "you would like to generate.");

     int userInput = sc.nextInt();

     for(r=1;r<=userInput;r++) 
    {  // was unsure how to remove the comma from the last number
        int randomInt = (int)(rnd.nextFloat()*100)+1;            
        System.out.print(randomInt + ",");

        sum += randomInt;

        if(randomInt < lowest)
        {
            lowest = randomInt;
        }            
    }    
     System.out.println(" The total sum of these random numbers are " 
             +sum);
     int average = sum / userInput;
     System.out.println("The average of all those numbers is "
             + average);
     System.out.println(lowest);
}




Hot to get a random double within a range?

I need to be provided a random number, say, between 2 and 4, but it needs to be a double. Does any of you got any ideas on how I would do this? Thanks.




Array without repeating of the only number

  • I have to create an array in range [-10: 10];
  • without ZERO;
  • quantity of positive and negative numbers must be equal.

The main issue is that array is not always consist of 50/50 of percent of positive and negatime numbers. If you can show me much simply way to code it you are welcome!

public static void main(String[] args) throws IOException {
        int array[] = new int[12];
        int positiveCounter = 0;
        int negativeCounter = 0;

        for (int i = 0; i < array.length; i++) {
            array[i] = createRandom();
            while (array[i] == 0) {
                array[i] = createRandom();
            }

            if (positiveCounter > array.length / 2) {
                array[i] = -1 * array[i];
                positiveCounter--;
                negativeCounter++;
            }
            if (negativeCounter > array.length / 2) {
                array[i] = -1 * (-array[i]);
                negativeCounter--;
                positiveCounter++;
            }

            if (array[i] > 0) {
                positiveCounter++;
            }
            if (array[i] < 0) {
                negativeCounter++;
            }
        }
        System.out.println(Arrays.toString(array));
        System.out.println("Pos: " + positiveCounter);
        System.out.println("Neg: " + negativeCounter);
    }

    static int createRandom() {
        Random random = new Random();
        int x = -10 + random.nextInt(11 - (-10));
        return x;
    }




Generate a random number between negative and positive in swift

So I'm trying to generate a random number between negative and positive range because I need to give an object a position on the x axis. I've tried with arc4random and arc4random_uniform but it doesn't work. I need a way to generate a random position on the x axis, negative and positive.




Java random math equation generating random answers

I am coding a problem where it will be x (+ or - or *) y =z and it will generate 4 possible answers for the user which has 1 good and 3 wrong answers. I made most of the code but I do not get how I make the same formula used again for Reponse() because right now when I execute the code, Equation() makes his own one and Reponse() does another different formula. Also I need to know how I can make sure that the code works by adding a system that will show a formula like 5 +5 = ? and the code will show 4 answers which has one good one.

here's the code:

    public class Equation {

    int x, y, z;


    public Equation() {
        Random r = new Random();
        x = r.nextInt(50) + 1;
        y = r.nextInt(50) + 1;
        z = 0;
        char operator = '?';

        switch (r.nextInt(3)) {
            case 0:
                operator = '+';
                z = x + y;
                break;
            case 1:
                operator = '-';
                z = x - y;
                ;
                break;
            case 2:
                operator = '*';
                z = x * y;
                ;
                break;
            default:
                operator = '?';
        }

        System.out.print(x);
        System.out.print(" ");
        System.out.print(operator);
        System.out.print(" ");
        System.out.print(y);
        System.out.print(" = ");
        System.out.println(z);

    }

}

and for Reponse() the one that generates the answers:

    public class Reponse {
    Equation equ = new Equation();
    int a, b, c, d;
    char operator = '?';

    public Reponse() {
        Random r = new Random();
        switch (r.nextInt(4)) {

            case 0:
                a = r.nextInt(2 * equ.z);
                break;

            case 1:
                b = r.nextInt(2 * equ.z);
                break;

            case 2:
                c = r.nextInt(2 * equ.z);
                break;
            case 3:
                d = equ.z;
                break;
            default:
                operator = '?';
        }
    }
}




Random multiplication table generator

im creating an multiplication table system in PHP.

But I am trying to build my algorithm in such an way that if the user selects the table 7 and 20 questions that it would random give me 20 questions from the table 2 to the input number table, so 7.

At this point I just fill an array like this:

$nCount = $_POST['count'];
$nHighest = $_POST['table'];
$aSums = [];
$nCounter = 0;
while($nCount > 0){
    $cSumString = rand(2, $nHighest) . "*" . rand(1, 10);
    $aSums[$nCounter] =
    $nCount--;
    $nCounter++;
}

And this works even if there are better ways. so when I want to parse them all ill explode them on the *. but I want to parse them in multiple ways:

3 * 5 = ... (normal)
... * 5 = 25 (first number to fill in)
8 * ... = 16 (second to fill in)

This needs to be random aswell, so it can occur that there are 3 normal questions first then 2 second place to fill and then a normal again.

And to be honest im kind of clueless. I did alreade make some code to prevent the same questions like: 2*8 and 8*2 and so on. But for this im clueless.

Can anyone push me in the right direction? Im not asking for instacode or something im really willing to do this myself but everything ive tried up until now is completely rubbish. everytime I think ive got it I realise it doesnt work.

Thanks in advance and happy coding.




Linux 'add_interrupt_randomness' implementation - low entropy contribution by cycles and jiffies?

currently I'm analyzing the process of entropy generation of a linux 64-bit kernel during system startup (for enducational purpose). The system is hosted as/on a (64 bit) virtual machine (Xen domU). For a deep analysis, I'm tracking the state of relevant input parameters i.e. how those are proccessed. In function 'add_interrupt_randomness' I found some code whose itention is not comprehensible to me: The handling of 'cycles' (value provided by cpu cycles counter) and 'now' (jiffies). Both are unsigned 64 bit values, and proccessed as followig:

c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
j_high = (sizeof(now) > 4) ? now >> 32 : 0;
fast_pool->pool[0] ^= cycles ^ j_high ^ irq;

So c_high/j_high (__u32) are assigned with the upper 32 bit of cycles/now and then assigened (after xor) to the fast entropypool. Hence a maximum variation of the values provided by c_high and j_high should be desireable(?). But since c_high and j_high are based on cycles and now/jiffies ,which are purely incremented variables, there is very little/no variation in the upper 32-bits as the traced values reveal:

Values in call no. 1 of 'add_interrupt_randomness':

cycles:0xFFFEA432A6C2CB89

c_high:0xFFFEA432

now_jiffies:0x00000000FFFEDB0A

j_high:0x00000000

Values in call no. 4265* of 'add_interrupt_randomness':

cycles:0xFFFEA43FBA85B313

c_high:0xFFFEA43F

now_jiffies:0x00000000FFFEE80C

j_high:0x00000000

*(startup is completed at this point)

So my question is: why are the upper 32 bits proccessed instead of the lower, which would provide more randomness? Thanks for enlightenment!

If interessted: this is the complete definition of 'add_interrupt_randomness':

void add_interrupt_randomness(int irq, int irq_flags)
{
    struct entropy_store    *r;
    struct fast_pool    *fast_pool = this_cpu_ptr(&irq_randomness);
    struct pt_regs      *regs = get_irq_regs();
    unsigned long       now = jiffies;
    cycles_t        cycles = random_get_entropy();
    __u32           c_high, j_high;
    __u64           ip;
    unsigned long       seed;
    int         credit = 0;

    if (cycles == 0)
        cycles = get_reg(fast_pool, regs);
    c_high = (sizeof(cycles) > 4) ? cycles >> 32 : 0;
    j_high = (sizeof(now) > 4) ? now >> 32 : 0;
    fast_pool->pool[0] ^= cycles ^ j_high ^ irq;
    fast_pool->pool[1] ^= now ^ c_high;
    ip = regs ? instruction_pointer(regs) : _RET_IP_;
    fast_pool->pool[2] ^= ip;
    fast_pool->pool[3] ^= (sizeof(ip) > 4) ? ip >> 32 :
        get_reg(fast_pool, regs);

    fast_mix(fast_pool);
    add_interrupt_bench(cycles);

    if (!crng_ready()) {
        if ((fast_pool->count >= 64) &&
            crng_fast_load((char *) fast_pool->pool,
                   sizeof(fast_pool->pool))) {
            fast_pool->count = 0;
            fast_pool->last = now;
        }
        return;
    }

    if ((fast_pool->count < 64) &&
        !time_after(now, fast_pool->last + HZ))
        return;

    r = &input_pool;
    if (!spin_trylock(&r->lock))
        return;

    fast_pool->last = now;
    __mix_pool_bytes(r, &fast_pool->pool, sizeof(fast_pool->pool));

    /*
     * If we have architectural seed generator, produce a seed and
     * add it to the pool.  For the sake of paranoia don't let the
     * architectural seed generator dominate the input from the
     * interrupt noise.
     */
    if (arch_get_random_seed_long(&seed)) {
        __mix_pool_bytes(r, &seed, sizeof(seed));
        credit = 1;
    }
    spin_unlock(&r->lock);

    fast_pool->count = 0;

    /* award one bit for the contents of the fast pool */
    credit_entropy_bits(r, credit + 1);
}

from: https://elixir.bootlin.com/linux/v4.15.6/source/drivers/char/random.c#L1118




How to alert a single element from an array in javascript?

Hello everyone I am new here and I am just starting to learn javascript.

I need to come up with a piece off code that alerts a single random element from an array. I have managed to come up with the random element but it alerts all ten of them from the array. While I need t to alert a single one and stop.

This is what I have so far.

    var myList = new Array("gusty", "long", "tremendous", "play", "white", 
    "literate", "baboon", "dusty", "government", "cheer");

    for(i = 0; i < myList.length; i++)
    {
        var y = Math.floor(Math.random() * 10);
        alert(myList[y]);
    }

So when I load this in a browser I get ten random words. But I just want one. I tired putting the var inside the alert but that didn't do anything.




Select randomly from array with probabilites

Assume I have an array of items [1,2, ...n], and probabilities array [p1,p2,....,pn]

where n: a very large number may reach to thousands and the sum of all probabilities = 1.

I need to select 3 unique items randomly each time, the item with high probability its chance to select is higher. I need to do the selection for more than 20k times.

I've implemented the required by creating new array that contains the items with repetition based on its probability, for example, if probabilities for item1,item2, item3 are [2/n,4/n,1/n] respectively ... then the new array will contain [1,1,2,2,2,2,3, ...]

It works fine but it's not efficient especially in this method the chance to select the same item is possible, then reselect another item and this consumes time.

Is there any efficient methods or ready functions in MATLAB for that purpose.

Thanks,




How do you estimate the mean and variance of a piecewise linear function?

For example, what would be the mean and variance of the probability density function fx(x)=34,0≤x≤1;14,2≤x≤3;0 otherwise?




dimanche 25 février 2018

Is srand() required in Julia?

Some low-level languages like C require the programmer to set seed (usually srand(time(0)) if the user wants a different sequence of random numbers whenever the program runs. If it is not set, the program generates the same sequence of random numbers for each run.

Some high-level languages automatically set the seed if it is not set at first.

In Julia, if I want to generate a new sequence of random numbers each time, should I call srand()?




What is the best way of Under sampling in R

I have a dataset with attribute A,B, C. C has 2 labels x and y. number of (x) > number of (y), I want to under sample my data set so that in the new data has same no of x and y values




How do I get the answer to the random flash-card by clicking the panel?

I am trying to make a random flash card type of generator for javascript syntax. When i hit the random question button, it will display a random question such as "What is a variable?" but on clicking the panel, it should display the answer out of the answer array. All of the answers are in an object. I am 3 months new to programming, so any advice is appreciated.

$('button').on('click', function(){
  var ranQuestion = Math.floor(Math.random()* arrOfQuestions.length);
  $('#panel').html(arrOfQuestions[ranQuestion]);

  //produce answer in the panel html onclick
  $('#panel').on('click', function(){
    var pan = $('#panel').html();
    if(pan === arrOfQuestions){
       $('#panel').html(test);
    }
   })
})

enter link description here




Return random event out of last 2 events

Assume the following Esper events (Esper Tryout page):

StockTick={symbol='event1', price=1}
t=t.plus(10 seconds)
StockTick={symbol='event2', price=2}
t=t.plus(10 seconds)
StockTick={symbol='event3', price=3}
t=t.plus(10 seconds)
StockTick={symbol='event4, price=4}

I would like to return the last two events every 3 seconds.

Apart from a window and an output every 3 seconds I assume the statement must contain some Random() variable but I can't make it work. I am grateful about any ideas.




Receiving wrong byte socket java

I am implementing a simple client-server program where I would like to send a 64 bit random number from the client program to the Server. I am running into an issue where the received byte array at the Server isn't same as the one sent from the client. Any assistance in figuring out the mistake would be greatly appreciated !

I used Socket send and receive byte array as a reference for my implementation.

Client program :

    SecureRandom random=new SecureRandom();
    byte[] r_a=new byte[8];
    random.nextBytes(r_a);
    DataOutputStream bos = new DataOutputStream(client_soc.getOutputStream());
    bos.writeInt(r_a.length);
    bos.write(r_a);

    bos.flush();
    bos.close();
    client_soc.close();

Server program :

            byte[] r_a;
            DataInputStream bis= new DataInputStream(ser_soc.getInputStream());
            int length_rand=bis.readInt();
            if(length_rand>0)

            { r_a= new byte[length_rand];
            bis.readFully(r_a,0,length_rand);
            System.out.println("r_a : "+ r_a);
            System.out.println("r_a length : "+ r_a.length);

            }
            bis.close();
            ser_soc.close();

My results : Client program sends r_a : [B@78308db1

Server program received r_a : [B@2689d3df




snake game random position(fruit) not being eating

I am trying to create a random place for the piece of fruit to be placed on the board and it does work but when my snake 'O' eats the 'F' piece,the 'F' does not disappear instead it stays there and worst yet sometimes without even eating it,it will randomly disappear and a new piece of fruit will appear in a new place,can anyone see why this is happening?

bool gameOver;
const int WIDTH = 20;
const int HEIGHT = 20;
int fruitX,fruitY,x,y;
edir dir;


void setUp(){

  gameOver = false;
  dir = STOP;
  x = WIDTH/2;
  y = HEIGHT/2;
  srand(time(NULL));
  fruitX = rand() % WIDTH-1;
  fruitY = rand() % HEIGHT-1;
  if(x == fruitX && y == fruitY){
    fruitX = (rand() % WIDTH-1)+1;
    fruitY = (rand() % HEIGHT-1)+1;
  }
}

void draw(){

     system("cls");

      for(int i = 0; i < WIDTH+1; i++){

        cout << "#";
      }
      cout << endl;

      for(int i = 0; i < HEIGHT; i++){

        for(int j = 0; j < WIDTH; j++){

            if(j == 0){

                cout << "#";
            }
            if(j == WIDTH-1){
                cout << "#";
            }
            if(i == x && j == y){

                cout << "O";
            }
            else if(i == fruitY && j == fruitX){

                cout << "F";
            }
            else{

                cout << " ";
            }
        }
        cout << endl;
      }
      for(int i = 0; i < WIDTH+1; i++){

        cout << "#";
      }


   }

void logic(){

 switch(dir){

 case UP:
     x--;
     break;
 case DOWN:
     x++;
     break;
 case LEFT:
    y--;
    break;
 case RIGHT:
    y++;
    break;
 }

 if(x > WIDTH || x < 0 || y > HEIGHT-2 || y < 0) // check for in bounds
    gameOver = true;
  if(x == fruitX && y == fruitY){
        fruitX = (rand() % WIDTH-1)+1;
        fruitY = (rand() % HEIGHT-1)+1;
    }

}

int main()
{
   setUp();
   while(!gameOver){

   draw();
   input();
   logic();
   }
   if(gameOver){
    cout << endl;
    cout << endl;
    cout << "GAME OVER!!!!!!!!!!!!" << endl;
   }
}




Separate Words in Random Word Generator

I wrote a small word generator. I currently have the generator providing the different words, but can't figure out how to use the split function to insert a hyphen between each randomly generated word when the password is printed

Current output: thisisapassword

Desired output: this-is-a-password

answer = urllib.request.urlopen('http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain')
txt = answer.read()
words = txt.splitlines()

password = ''
 for c in range(3):
password += random.choice(words)
print(password)




JS Dice - Assigning Math.random value to an html image using if condition

Hello i'm using Javascript to create a random dice output (from 1-6) including an image of the dice side.
The mathRandomDice function is working fine but my 'if' condition which assigning it to the image is not...
My goal is to assign the Math.random value to an image.

function mathRandomDice() {
    document.getElementById("dice").innerHTML = Math.floor(Math.random() * 6) + 1; 

}

var x = mathRandomDice;

  if (x = 1) {
            d.innerHTML = '<img src=https://image.ibb.co/cQKOhc/dice1.png>';
    }

function mathRandomDice() {
    document.getElementById("dice").innerHTML = Math.floor(Math.random() * 6) + 1; 

}
  body {
    text-align:center;}


/* button */

button {
  display: inline-block;
  padding: 15px 25px;
  font-size: 24px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

button:hover {background-color: #3e8e41}

button:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
 <h5> Press the button for a random dice number<h5>
    <span id="yournum"></span>
   <p id="dice"></p>
<button onclick="mathRandomDice()">Roll The Dice</button>
<br><br>
   <img src="https://image.ibb.co/cQKOhc/dice1.png" alt="1" class="center">
   <img src="https://image.ibb.co/cmyG2c/dice2.png" alt="2" class="center">
   <img src="https://image.ibb.co/bPNyFx/dice3.png" alt="3" class="center">
   <img src="https://image.ibb.co/fmkJFx/dice4.png" alt="4" class="center">
   <img src="https://image.ibb.co/d6D5vx/dice5.png" alt="5" class="center">
   <img src="https://image.ibb.co/nFqkvx/dice6.png" alt="6" class="center">



How Java handles random number generation?

I am not getting any algorithm wherein I can be assured how Java generate a random number?




Check if value is within range otherwise calculate nearest value

I have these value:

let previous = 170
let min = 100
let max = 800

So what I´m doing is that I´m generating a random number between min and max, with these rules:

  • min not less than 100
  • max not more than 800
  • I only want to have +200 from previous or -200 from previous

So for the above example the random number should be between:
min: 100 and max 370.

Min is 100 because min can´t be less than 100 and max is basically previous: 170 + 200.

I tried the "pattern-match" operator ~=: but it did not feel like the right component to do here.

Any ideas of how to solve this?




samedi 24 février 2018

Matrix entered by user

Can someone help me? I'm new to Python and I want to create a matrix of 3x3, with random entries (among 0, 1, 2, 3, 4, 5) that the user is going to give (he'll have to press 'Enter' to start, but my code doesn't run. Here it is:

import math
line = ' '.join(map(str, range(4*4))) # Take input from user
'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15'
items = map(int, line.split()) # convert str to int
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
3 = int(math.sqrt(len(items))) # len(items) should be n**2
4
matrix = [ items[i*3:(i+1)*3] for i in range(3) ]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]

Can someone help me please?




uniform_real_distribution

I am currently working on importance sampling, and for testing purposes I need to be able to generate all possible values that uniform_real_distribution<float> may generate. My idea was to generate integer numbers which I can then convert to floating point numbers. From the tests I made it seems that there is a perfect bijection between uniform single-precision floats in [0,1] and integers in [0,2^24] (I am a bit bothered by the fact that it is not [0,2^24-1] and I am still trying to figure out why, my best guess is that 0 is simply special for floats and 1 to 2^24 all result in floats that have the same exponent). My question is whether the floats generated this way are exactly the floats that can be generated from uniform_real_distribution<float>. You can find my integer <-> float tests below:

void floatIntegerBitsBijectionTest()
{
    uint32 two24 = 1 << 24;
    bool bij24Bits = true;
    float delta = float(1.0) / float(two24);
    float prev = float(0) / float(two24);
    for (uint32 i = 1; i <= two24; ++i)
    {
        float uintMap = float(i) / float(two24);
        if (uintMap - prev != delta || uint32(uintMap*float(two24)) != i)
        {
            std::cout << "No bijection exists between uniform floats in [0,1] and integers in [0,2^24].\n";
            bij24Bits = false;
            break;
        }
        prev = uintMap;
    }
    if(bij24Bits) std::cout << "A bijection exists between uniform floats in [0,1] and integers in [0,2^24].\n";
    std::cout << "\n";

    uint32 two25 = 1 << 25;
    bool bij25Bits = true;
    delta = float(1.0) / float(two25);
    prev = float(0) / float(two25);
    for (uint32 i = 1; i <= two25; ++i)
    {
        float uintMap = float(i) / float(two25);
        if (uintMap - prev != delta || uint32(uintMap*float(two25)) != i)
        {
            std::cout << "No bijection exists between uniform floats in [0,1] and integers in [0,2^25].\n";
            if (i == ((1 << 24) + 1)) std::cout << "The first non-uniformly distributed float corresponds to the integer 2^24+1.\n";

            bij25Bits = false;
            break;
        }
        prev = uintMap;
    }
    if (bij25Bits) std::cout << "A bijection exists between uniform floats in [0,1] and integers in [0,2^25].\n";
    std::cout << "\n";


    bool bij25BitsS = true;
    delta = 1.0f / float(two24);
    prev = float(-two24) / float(two24);
    for (int i = -two24+1; i <= two24; ++i)
    {
        float uintMap = float(i) / float(two24);
        if (uintMap - prev != delta || int(uintMap*float(two24)) != i)
        {
            std::cout << i << " " << uintMap - prev << " " << delta << "\n";
            std::cout << "No bijection exists between uniform floats in [-1,1] and integers in [-2^24,2^24].\n";
            bij25BitsS = false;
            break;
        }
        prev = uintMap;
    }
    if (bij25BitsS) std::cout << "A bijection exists between uniform floats in [-1,1] and integers in [-2^24,2^24].\n";
}




How to get something random/different, 10 times?

I will admit I'm stuck on a school project right now.

I have defined functions that will generate random numbers for me, as well as a random operator (+, -, or *).

I have also defined a function that will display a problem using these random numbers.

I have created a program that will generate and display a random problem and ask the user for the solution. If the user is correct, the program prints 'Correct', and the opposite if the user is incorrect.

I have put all of this inside of a loop that will make it repeat 10 times. My issue is that I need it to generate 10 different problems instead of the same problem that it randomized the first time, 10 times.

Sorry for the weird wording.

*I am using python but am showing the code here using the CSS viewer because I couldn't get it to display any other way.

Thank you.

import random

max = 10

def getOp(max): #generates a random number between 1 and 10
    randNum = random.randint(0,max)
    return randNum
randNum = getOp(max)


def getOperator(): #gets a random operator 
    opValue = random.randint(1,3)
    if opValue == 1:
        operator1 = '+'
    elif opValue == 2:
        operator1 = '-'
    elif opValue == 3:
        operator1 = '*'
    return operator1

operand1 = getOp(max)
operand2 = getOp(max)
operator = getOperator()

def doIt(operand1, operand2, operator): #does the problem so we can verify with user
    if operator == '+':
        answer = operand1 + operand2
    elif operator == '-':
        answer = operand1 - operand2
    elif operator == '*':
        answer = operand1 * operand2
    return answer
answer = doIt(operand1, operand2, operator)

def displayProblem(operand1, operand2, operator): #displays the problem
    print(operand1, operator, operand2, '=')


###My program:
for _ in range(10): #loops the program 10 times
    displayProblem(operand1, operand2, operator)

    userSolution = int(input('Please enter your solution: '))

    if userSolution == doIt(operand1, operand2, operator):
        print('Correct')

    elif userSolution != doIt(operand1, operand2, operator):
        print('Incorrect')



Calculations using random numbers of a specific range in a 2D array in c

I have to populate a 2D array using random numbers between 3 and 19. The array is 4 x 3, the first two columns will represent two sides to a right triangle and the third column is the hypotenuse. I'm pretty new to c, so I'm not sure where I'm going wrong. my output gives me the headers just fine but just one single vertical line of numbers instead of a 4 x 3 grid. Here's my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define ROW 4
#define COL 3

void printChart(double array[ROW][COL]);

int main(void)
{
    double chart[ROW][COL];
    double *ptrchart = &chart[0][0];

    srand(time(NULL));
    for (size_t i = 0;i < ROW;i++)
    {
        for (size_t j = 0;j < COL;j++)
        {

            chart[i][j] = 3 + (rand() % 19);
        }
    }

    for (size_t i = 0;i < ROW;i++)
    {
        chart[i][2] = 0;
    }

    printChart(ptrchart);

    for (size_t i = 0;i < ROW;i++)
    {
        chart[i][2] = (double)sqrt(pow(chart[i][0], 2) + pow(chart[i][1], 2));

    }

    puts(" ");

    printChart(ptrchart);

    return 0;

}

void printChart(double array[ROW][COL])
{
    printf("%s", "Side A\tSide B\tHypotenuse(Side C)\n");
    for (size_t i = 0;i < ROW;i++)
    {
        for (size_t j = 0;j < COL;j++)
        {
            printf("%.3f\t",  array[i][j]);

            if (j = 2)
            {
                puts(" ");
            }
        }
    }
}

Any help would be greatly appreciated, and if I need to clarify anything please let me know.




vendredi 23 février 2018

How to create a thread-safe rand.Source?

The documentation for the standard-library rand.NewSource function states that,

Unlike the default Source used by top-level functions, this source is not safe for concurrent use by multiple goroutines.

Is there a way to create a thread-safe rand.Source?

Context: I have a type with a method that may be called by multiple go-routines, and this method uses random numbers. I want to support dependency injection for testing, so I can't use the default Source.




Mysterious Bug Within Python Loop?

So, I was working on some basic finance, trying to simulate a number of random stock price paths, when I encountered this inscrutable bug in the code.

My code so far:

# Imports.

%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from math import *

# Error-producing section - randnorm holds a 10x10 vector of normally distributed 
# random numbers, used in calculating my price path.

sims = 5
intervals = 5
r=.02
T=1
sigma=.15

randnorm = [[np.random.normal() for x in range(10)] for y in range(10)]
# print(randnorm)

for i in range(sims):
    for j in range(1,intervals):
        paths[i][j] = paths[i][j-1] * exp((r - .5*sigma**2)*(T/intervals) + sqrt(T/intervals)*randnorm[i][j-1])
        print(paths[0][1])

I knew something was wrong with my previous code, so I tried debugging by printing in each loop, and I get this,

0.5937221173702402
0.5937221173702402
0.5937221173702402
0.5937221173702402
1.4849274521869171
1.4849274521869171
1.4849274521869171
1.4849274521869171
0.860018700453769
0.860018700453769
0.860018700453769
0.860018700453769
1.0709782525755074
1.0709782525755074
1.0709782525755074
1.0709782525755074
0.7184834195858915
0.7184834195858915
0.7184834195858915
0.7184834195858915

What gives? I seriously do not know where I could be wrong here. It's not my random numbers, which are all different, or an index issue.




Getting "No line found" when pulling values from an external file

Alright, so I need to grab some strings at random from a file not of a fixed size. So, to do this, I start by counting the lines in the file using a simple while loop. After that, I simply feed that value to a random object and store the ten values I need into the array:

int[] select = new int[10];

I run into problems however with this code.

 String[] value = new String[10];
 for (sel = 0; sel <= 9; sel++){
      int w = select[sel];
      Scanner input = new Scanner(file.txt);      
      for (int q = 0; q <= w; q++){ 
        String bank = input.nextLine();
        input.nextLine();
        value[sel] = bank;
      }

The code works, but it seems that if the value the code is looking for is too high, (tested at about 90+) I get the exception:

java.util.NoSuchElementException: No line found




The If statement evaluates False condition even when the condition is True [duplicate]

This question already has an answer here:

On function when the value of random integer generated by computer and the guess number given by the user matches the IF statement doesn't evaluates to True. What is the possible cause of malfunction in this program.

##In this program, the user must try to guess a random number generated by the computer
from random import randint
def guess_game():
    """ A function to check whether the number guessed by the user matches the number generated by computer"""

    while True:
        random_num = randint(0,10)
        print random_num
        guess = raw_input("Enter a number: ")
        print guess
        if random_num == guess:
            print "your guess is correct"
            break
        else:
            print "Try Again"

guess_game()




jeudi 22 février 2018

How do i return random String from array list?

Im trying to return a string from my arraylist but i keep getting an outofbounds exception which i assume its a problem with the "RandomArray.size-1". The array has 10 strings and I need 1 random one to be generated.

///////////////my arraylist where the string is stored///////////////

 ArrayList<String> RandomArray = new ArrayList<>();

/////////my else statment to get the random string//////////

 else {
         phrase=RandomArray.get(rng.nextInt(RandomArray.size()-1));  
    }
  /////////////////////`where i added the phrases into the list`
public String randomPhrases() {

    String phrase1 = "its morping time";
    RandomArray.add(phrase1);
    String phrase2 = "its lit";
    RandomArray.add(phrase2);
    String phrase3 = "head over heels";
    RandomArray.add(phrase3);
    String phrase4 = "shot in the dark";
    RandomArray.add(phrase4);
    String phrase5 = "a chip on your shoulder";
    RandomArray.add(phrase5);
  return string;




Picking Random number gives NullPointerException

I am trying to get a random integer to use as index so i can get a random element from a string array. I have a function that does it,checked online and its similar to what other people are using. What am I doing wrong and I'm getting a NullPointerException?

This is the function I am using:

    public static String getRandom(String[] array) {
    int rnd = new Random().nextInt(array.length);
    return array[rnd];
    }

I am getting the Null pointer exception on the 2nd line. An example of one of the Strings is:

       String[] president = {"Jefferson","Johnson","Filmore","Obama","Trump"};




How can I generate pseudo random numbers that shows patterns in its image using python?

I want to generate a code that gives the best example of a bad Random number generator using python. This is taken from http://boallen.com/random-numbers.html

How can I generate an image using python that is similar to this or that has visible patterns?




Python and Javascript Pseudo Random Number Generator PRNG

I am looking for a way to generate the same sequence of pseudo random integer numbers from both python and javascript.

When I seed in python like this I get the below results:

random.seed(3909461935)   
random.randint(0, 2147483647) = 162048056
random.randint(0, 2147483647) = 489743869
random.randint(0, 2147483647) = 1561110296

I need the same sequence in javascript.

  • Note: I used 2147483647 as the range in the randint method because I am assuming javascript can only handle 32 bit INTs.

Are there any libraries on both sides I can use to generate the same set of pseudo random numbers given the same seed?




instead of MySQL ORDER BY RAND

Good day! I use this query:

SELECT f.id FROM articles f
        JOIN ( SELECT RAND() * (SELECT MAX(id) FROM articles) AS max_id ) AS m
        WHERE f.id >= m.max_id
        ORDER BY f.id ASC
        LIMIT 5

The problem is that It returns the unexpected amount of the rows. It can be 1 row or 3 rows or 5 rows. But I need exactly 5 rows. Is there any way to fix it?




np.random choice weighted dropout over time?

I have a df where I want to show the number of people randomly added to a sports team a year where the inverse of rank is used as a normalizing weight. The code has 10 individuals to assign to a team each year. I have code for this that works fine. My problem is how can I drop teams and their weights out over time once they hit their max number of team members assigned, without dropping them from the df? I know this would require readjusting the weights and choices each year something dropped out but I'm not sure how to implement that.

      df_input

     Rank1 Team  max_num   current_num  
       1    Foo    15          6       
       2    Bar    16          5       
       3    Baz    14          9        
       3    Cat    18          10       



   df_output

     Rank1 Rank2  Team  max_num   current_num  Y1 Y2  Y3   Final_total
       1    3      Foo    15          6        4   5   4         19
       2    2      Bar    16          5        4   3   2         14
       3    1      Baz    14          9        1   2   2         14
       3    1      Cat    18          10       1   0   2         13

Current code :

      def Team_picker(df):
            new_weight = {1:3,3:1}
            df['Rank2'] = df.Rank.map(new_weight)
            All_Teams = df['Team'].tolist()
            weights = df['Rank2'].tolist()
            norm = [float(i)/sum(weights) for i in weights]

            for x in range(1,4):
                 year = 'Y %d'% x
                 T = [choice(All_Teams, p=norm) for _ in range(10)]
                 Player_counts = Counter(T)
                 df[year] = df['Team'].map(Player_counts)
            T_Years = [col for col in df.columns if col.startswith('Y')]
            df['Final_Total']= df['current_num'] + (df[T_Years].sum(axis=1))

            return df

However, the df I'm aiming for would look more like this:

      df_output2

  Rank1 Rank2  Team  max_num   current_num  Y1 Y2  Y3   Final_total
   1    3      Foo    15          6         4   5   0         15
   2    2      Bar    16          5         4   3   4         16
   3    1      Baz    14          9         1   2   2         14
   3    1      Cat    18          10        1   0   4         15 

TL;DR How can keep all of the teams in the random draw until they reach the max and then drop them out without dropping them from the DF while also changing the weights for the next draw year. Also can I implement this during a draw year if say something ranked really high only needs one more person to hit their max?




Fact Generator (Not Random)

I'm adding a random fact generator to my company's about page. It currently looks like this:

JS:

 <script>var targetemployee = document.getElementById('targetemployee');
var factsemployee = [

  'Fact1',
  'Fact2',
  'Fact3',
  'Fact4',
  'Fact5',
];
function newEmployeeFact () {
  var i = Math.floor(Math.random() * factsemployee.length) | 0;
  targetemployee.innerText = factsemployee[i]

}

newEmployeeFact();

</script>

HTML:

<p class="funfact" id="targetemployee"></p><button type="button" class="hover-shadow" style="text-align: middle; font-size: 0.8em; bottom: 0px" onclick="newEmployeeFact()"> NEW FACT </button>

</div>

My problem is that after clicking it a few times, it will sometimes show the same fact instead of a new one so I just want to change is so that it's sequential. Any tips? I'm a JS beginner so I appreciate y'all's help!




Generate random graphs with different topologies and a variable number of vertices preserving that topology

I'm a newbie at using networkX package. So l would like to generate random graphs as illustrated in the following figure :

such that for each topology let's take Ring :

1)l can generate 5 variants of ring by addding more nodes (1 ,3 ,5 ..) and it preserves topology of ring. (same for other topologies)

2) Assign to each vertice a random vector of 200 values

3) Assign to each vertice a different color (randomly : red, green or blue).

enter image description here

Here is what l tried :

import matplotlib.pyplot as plt
import networkx as nx
import random as random
from random import randint
import numpy as np
from itertools import chain

def colors(n): # generate n random colors (n is the number of vertices)

        ret = []
        color = []
        r = int(random.random() * 256)
        g = int(random.random() * 256)
        b = int(random.random() * 256)
        step = 256 / n
        for i in np.arange(n):
            r += step
            g += step
            b += step
            r = int(r) % 256
            g = int(g) % 256
            b = int(b) % 256
            get_max = np.argmax((r, g, b))
            if get_max == 0:
                ret.append((r, g, b))
                color.append('red')
            elif get_max == 1:
                ret.append((r, g, b))
                color.append('green')
            else:
                ret.append((r, g, b))
                color.append('blue')
        return ret, color


def main(p):
    n = p  #number of vertices
    k = np.arange(n)
    list_node = list(k)
    #G= nx.star_graph(n) # l don't get enough variability, when l increase the number of vertices l lose star topology
    #G=nx.generators.wheel_graph(n) # l don't get enough variability, when l increase the number of vertices l lose wheel topology topology
    #G = nx.random_geometric_graph(n,radius=3)

    G.add_nodes_from(list_node)
    list_edges = []
    for i in np.arange(30): # generate random edges 
        (x, y) = randint(1, n), randint(1, n)
        list_edges.append((x, y))
    for j in k: # loop to be sure that the graph is connected and each vertice has at least one edge
        if j not in list(chain.from_iterable(list_edges)):
            r = randint(1, n)
            if r == j:
                while r == j:
                    r = randint(1, n)
                p, z = (j, r)
                list_edges.append((p, z))
            else:
                list_edges.append((j, r))
    # print(list_edges)
    G.add_edges_from(list_edges)

    rgb, color = colors(n + 1)
    x = 0
    node_color = color

    for v in G.nodes():
        print('inde node ', v)
        print(rgb[v])
        G.node[v]['value'] = rgb[v]
        print('graph')
        print(G.nodes(v))
        x += 10
    #print(G.node[1]['value'])
    nx.draw(G, node_color=node_color, with_labels=True)
    plt.title('Star graph with '+str(p+1)+ ' nodes')
    plt.show()

My purpose is to get for instance line graph with 5 vertices, 10 vertices, 50 vertices but the topology is preserved. The same for the remaining topologies

Hope it's more clear.

Thank you for your help




Random Files Generator With Python [on hold]

How Do I Make A Program With Python Which Generates Random Files in Computer With While True Like Virus




how to randomize a string by daily date with Javascript

help , I'm trying to create a quote generator that will randomize a quote on daily basic's.

```var date = new Date(); var quotes = ["Hello World", "Good morning", "Good Night", "i love you"]; var randomQuotes= quotes[Math.floor(Math.random() * quotes.length)];

        document.getElementById("quotes").innerHTML = randomquotes;```




Using a header file to define mt19937 and normal_distribution

I am using the following routine to generate random numbers chosen from a Gaussian/Normal distribution:

When everything is in a single file to compile it's rather straightforward:

#include <iostream>
#include <math.h>
#include <random>

using namespace std;

int main()
{
    double m;
    double v;
  int seed=100; 
    int samplesize=10;
    double ls [samplesize]; //to store as a list

    m = 0.0;
    v = 0.05;
    mt19937 e2(seed);

    normal_distribution<float> dist(m, sqrt(v));

  for (int i=0; i<samplesize; i++){
        ls[i] = dist(e2);
        cout << ls[i] << endl;
    }

    return 0;
}

Now I am trying to do something similar but I'd like to be able to define e2 and the dist globally, or simply first in a hearder file .h and then call them in various .C files of my program. My attempts keep running into error: invalid use of non-static member function ‘std::mt19937 e2(int)’ kind of errors.

The aim is to:

  • Define e2 and dist in a header file.
  • Seed the e2 in a .C file that loads a file of parameters containing where the seed is given.
  • Use dist(e2) in my .C files whereever I have to generate such number.

My attempt:

In the header file I have written:

#include <random>

std::mt19937 e2(int sd); //sd for seed to be read from file later.
std::normal_distribution<float> dist(double meanNormal, double varNormal); //define generally, mean and var to be read from file.

Then in my setup.C file where I read the parameters I try to generate an instance of e2 and dist:

e2(seed); //seed read from file before.
dist(mean,sqrt(var)); //mean and var are double variables defined in this file. 

Now in my main program file, when I try to generate a number from dist using dist(e2) I get a non-static member function error as shown above. Any help in how to achieve this would be much appreciated.




Find a random user according to a distribution based on the number of users' "likes"

I'm trying to find the most efficient approach to randomly pick a user from my users table.

It would be very easy if the expected distribution would be uniform : same probability for every user.

But in my case, I want this probability to be based on the number of 'likes' received by the user : the more 'likes' the user got, the most probable is to pick this user. I know that GameKit provides a class GKGaussianDistribution to generate random numbers following a Gaussian Distribution, but I don't think this fulfill my needs.

Another approach would be to fill an array with a unique Id for every "likes" from every users, and to pick one of them with arc4random_uniform(), and then look-up to its owner user, but I'm not sure that it is the most efficient way to proceed.

I guess this is a common problem that many of us had to resolve once in a life ?




mercredi 21 février 2018

How to generate a list of lists with random numbers of the same length

How do you generate a random list of lists? I can generate a random list using the following [random.sample(range(80), 20)].

You can use the * function to make it list of lists but the numbers aren't random for each list. I can find answers relating to the creation of random list of lists that produce variable lengths but I can't find anything that will produce random numbers with the same length.




How to change random key + secret values in php?

How to change random key + secret values in php?

I have the following values:

key1: 111111111
secret1: 1111111111111111111111111 

key2: 222222222
secret2: 2222222222222222222222222

How to change random key + secret

$access_key = '111111111';
$access_secret = '1111111111111111111111111';

or

$access_key = '222222222';
$access_secret = '2222222222222222222222222';

Note: not show

$access_key = '1111111111';
$access_secret = '2222222222222222222222222';

Thanks for everyone's help !




Haskell random IO to Int

I recently picked up Haskell and the syntax is really confusing to me. I am trying to get a random number between 0 and 51 using

randomRIO (0, 51)

But I dont know how to make this an actual Int (now its type IO a). I believe you are supposed to be able to do:

gen <- randomRIO (0, 51)

and then gen is supposed to be an Int but I have to do this in a do block? How do I create the function that takes this and return an Int. From googeling I'm afraid that there is something basic that I do not understand. I am completely lost.




Selenium - generating random number

This is my code. I want to generate numbers between 20 and 30, instead of just counting till 15.

How do I do that?

int index = (int)(Math.random()*15);




Efficient sampling of a fixed number of rows in BigQuery

I have a large dataset of size N, and want to get a (uniformly) random sample of size n. This question offers two possible solutions:

SELECT foo FROM mytable WHERE RAND() < n/N

→ This is fast, but doesn't give me exactly n rows (only approximately).

SELECT foo, RAND() as r FROM mytable ORDER BY r LIMIT n

→ This requires to sort N rows, which seems unnecessary and wasteful (especially if n << N).

Is there a solution that combines the advantages of both? I imagine I could use the first solution to select 2n rows, then sort this smaller dataset, but it's sort of ugly and not guaranteed to work, so I'm wondering whether there's a better option.




How can I multiply 2 separate rand values within one argument in Ruby?

I would like to multiply 2 separate random numbers within an argument, to match the following (for example):

rand(1..6) + rand(1..6)

=>9 (result could be anything between 2-12)

I am in early stages of learning Ruby, so forgive me, but how do I achieve the same with multiplication? For example, the following will only multiply the same random number twice:

2 * rand(1..6)

=>2 (will only produce 2,4,6,etc)

Which is what you would expect. But how do I alter that statement to signify each rand should be a unique number that's being multiplied by the stated amount? Thank you.




Understanding how pseudo random numbers in Matlab imply statistical independence

Consider the following Matlab code in which I generate some data and then extract some rows of them at random. I would like your help to understand "how" random are these draws from a statistical point of view, in the terms I explain below.

I first set some parameters

%%%%%%%%Parameters
clear
rng default
Xsup=-1:6; 
Zsup=1:10; 
n_m=200; 
n_w=200; 
R=n_m;
T=100000; %number of draws

Then I generate the data

%%%%%%%%Creation of data [XZ,etapair,zetapair,etasingle,zetasingle]

%Vector X of dimension n_mx1
idX=randi(size(Xsup,2),n_m,1); %n_mx1
X=Xsup(idX).'; %n_mx1

%Vector Z of dimension n_wx1
idZ=randi(size(Zsup,2),n_w,1); 
Z=Zsup(idZ).'; %n_wx1

%Combine X and Z in a matrix XZ of dimension (n_m*n_w)x2 
which lists all possible combinations of values in X and Z
[cX, cZ] = ndgrid(X,Z);
XZ = [cX(:), cZ(:)]; %(n_m*n_w)x2

%Vector etapair of dimension (n_m*n_w)x1
etapair=randn(n_m*n_w,1); %(n_m*n_w)x1

%Vector zetapair of dimension (n_m*n_w)x1
zetapair=randn(n_m*n_w,1); %(n_m*n_w)x1

%Vector etasingle of dimension n_mx1
etasingle=max(randn(n_m,R),[],2); %n_mx1 

%Vector zetasingle of dimension n_wx1
zetasingle=max(randn(n_w,R),[],2); %n_wx1

Then I extract some rows at random

%%%%%%%%%%Random draws from [XZ,etapair,zetapair,etasingle,zetasingle]
idm=unidrnd(n_m,T,1); %Tx1
idw=unidrnd(n_w,T,1); %Tx1
idmupair=idm+n_m*(idw-1); %Tx1

Xsample=X(idm); %Tx1
Zsample=Z(idw); %Tx1
etapairsample=etapair(idmupair);%Tx1
zetapairsample=zetapair(idmupair);%Tx1
etasinglesample=etasingle(idm); %Tx1
zetasinglesample=zetasingle(idw); %Tx1

Let me now translate these draws into statistical terms:

For t=1,...,T, Xsample(t) can be thought as a realisation of a random variable X_t

For t=1,...,T, Zsample(t) can be thought as a realisation of a random variable Z_t

For t=1,...,T, etapairsample(t) can be thought as a realisation of a random variable E_t

For t=1,...,T, zetapairsample(t) can be thought as a realisation of a random variable Q_t

For t=1,...,T, etasinglesample(t) can be thought as a realisation of a random variable Y_t

For t=1,...,T, zetasinglesample(t) can be thought as a realisation of a random variable S_t

Since I draw realisations of these random variables at random with replacement (through the function unidrnd) I thought I could claim that (X_1,...,X_T, Z_1,...,Z_T, E_1,...,E_T, Q_1,...,Q_T, Y_1,...,Y_T,S_1,...,S_T) are mutually independent

As a check of this hypothetical claim, I define W_t:=-E_t-Q_t+Y_t+S_t and empirically compute Pr(W_t<=1|X_t=5, Z_t=1)

If mutual independence holds, then Pr(W_t<=1|X_t=5, Z_t=1)=Pr(W_t<=1) and their empirical counterparts below, named option1 and option2, should be ALMOST the same.

%option 1: conditional probability
num1=zeros(T,1);
for h=1:T
    if -etapairsample(h)-zetapairsample(h)+etasinglesample(h)+zetasinglesample(h)<=1 && Xsample(h)==5 && Zsample(h)==1
        num1(h)=1;
    end
end
den1=zeros(T,1);
for h=1:T
    if  Xsample(h)==5 && Zsample(h)==1
        den1(h)=1;
    end
end
option1=sum(num1)/sum(den1);


%option 2: unconditional probability
num2=zeros(T,1);
for h=1:T
    if -etapairsample(h)-zetapairsample(h)+etasinglesample(h)+zetasinglesample(h)<=1 
        num2(h)=1;
    end
end
option2=sum(num2)/T;

Question: the difference between option1 (=0.0034) and option2 (=0.0013) is referred to the "ALMOST" or I am doing something wrong?




Adding two numbers using a randomised operator

The following is my code, and it works. It creates two random numbers, a random operator and puts them together, however it does not sum them after doing this. What I need is for the program to recognise it as an equation, rather than simply printing out the individual variables.

So, to avoid confusion; my question is: How would I get firstNumber and secondNumberto be summed together using whatever operator is selected, rather than simply printing them out together?

from random import choice
from random import randint

ranOperator = ["*", "/", "+", "-"]

def askQuestion():
    firstNumber = randint(1,10)
    secondNumber = randint(1,10)
    operator = choice(ranOperator)

    generateQuestion = ' '.join((str(firstNumber), operator, str(secondNumber)))
    print(generateQuestion)

askQuestion()

Current output (example):

4 + 3

Using the same numbers above, what I would want to happen:

7




How to generate 1000 random vertices and edges in Python?

I need to generate 1000 vertices and edges, where the edges have different weights and all the vertices are connected to each other as shown in the image.enter image description here

The output of the code should be represented in numerical values, like (0, 1, 10) <--point 0 to point 1 and the weight of the edge is 10.




Fill a 2D array with random uppercase characters

I have this constructor for building a word search game (or are those called "alphabet soups"?). Its purpose is to create a two-dimensional array and then fill it with random uppercase letters.

SopaLetras(int numFilas, int numColumnas){
    this.numFilas = numFilas;
    this.numColumnas = numColumnas;
    char letra;
    cuadricula = new char[numFilas][numColumnas];
    for (int i = 0; i > numFilas; i++){
        for (int j = 0; j < numColumnas; j++){
            letra = (char)(65+(int)(Math.random()*26));
            cuadricula[i][j] = letra;
        }
    }
}

However, whenever i initialize this cuadricula[][] and try to check for any of its spaces, it always returns an empty character. I've checked the usage of Math.random(), it is correct and that statement is able to return a random uppercase character when putting it in a System.out.println().

¿What is it that makes me unable to assign that char to that place in the array?

Any help would be appreciated.




Random video generator in macOS app

I'd like to make a random video generator for macOS. I have four QuickTime video files with Apple ProRes 422 codec: 0001.mov, 0002.mov, 0003.mov, 0004.mov.

I've got a code for making a random photo generator. How to correct this code to get a video generator in my macOS app?

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    @IBOutlet weak var view1: NSImageView!
    @IBOutlet weak var view2: NSImageView!
    @IBOutlet weak var view3: NSImageView!
    @IBOutlet weak var view4: NSImageView!

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        let arrayOfViews: [NSImageView] = [view1, view2, view3, view4]

        let photos = (1...4).map {
            NSImage(named: NSImage.Name(rawValue: "000\($0)"))
        }

        for view in arrayOfViews {
            let randex = Int(arc4random_uniform(UInt32(photos.count)))
            view.image = photos[randex]
        }
    }
}

enter image description here




mardi 20 février 2018

Select sublist where each element has a 1.5% chance to be included

     tmp = []
     while len(tmp) == 0:
         for i in range(0,385):
             # Multiplying by 100 in order to remove the decimal point
             if randint(0,10000) < chance*100:
                 tmp.append(i)
     return tmp

This is the code I'm currently using to help clear things up. The output will be something like this.

[34, 234, 243, 321]

My current solution is very inefficient. I tried this:

sample(range(0,385), math.ceil(chance*3.85))

But it doesn't produce the same effect. Also if you could tell me the name of what this is called that would be great.




Letters and Symbols are printed when trying to store random numbers into an array [duplicate]

This question already has an answer here:

I've written this program to find 20 random numbers and store them into an array. Which then calls onto another class to print the array.( It was required to use two classes). Both of my programs compile fine however the output I recieve is

[I@12f55e8

instead of a list of numbers that were stored into the array. Can anyone tell me why this might be. Here is my program

Here is my displayArray method. It is just a method to print the array

**
 * Displays array 
 * pre: array made
 * post: array printed 
 * 
 */

 public class DisplayArrayAP
 {
 //



public static int[] toString (int[] array) 
{
   return(array);
}
}

Here is my main program

import java.util.*;
import java.io.*;

import java.util.Random;

public class TesterRandomAP
{
public static void main(String[] args) {

    //creating a new display object with an array with 20 indexes


    int[] array = new int[20];

   DisplayArrayAP result = new DisplayArrayAP(); 
    //creating a random object 
    Random rand = new Random();

    //loop to access array
    for(int index = 0; index < array.length; index++) {

        //stores random number into array
        array[index] = rand.nextInt(30)+1;


    }




  System.out.println(result.toString(array));
  }
} 




python random distribution from dimension

I have a 4D array, and I am trying to select from this array all of the first three dimensions and then a random distribution of the fourth dimension

samples = np.unique( np.random.randint(subset_start, subset_end, size=50) )    
layer_tensor = model.layer_tensors[model_layer][:, :, :, samples]

Which gives me:

ValueError: Shapes must be equal rank, but are 0 and 1
    **From merging shape 2 with other shapes. for 'strided_slice/stack_1' (op: 'Pack') with input shapes: [], [], [], [44].**




IOZone Min Xfer is very small sometimes

So I am running iozone to measure Random throughput and notice some weird behavior that I cannot explain and hoping someone here might shed some lights for me. When running random test for a certain blocksize. I noticed that the random write sometimes have skip value for a certain thread and then pick up again. I looked in the log and saw that the min xfer value is very small meaning the file was not completely written so that's why it's skewed the result so skipping. However, the test ran fine for the next thread. Anyone can shed me some lights as what is going on or how to go around this?

Children see throughput for 12 random writers   =   13978.97 KB/sec
Min throughput per process          =     731.76 KB/sec 
Max throughput per process          =    1854.75 KB/sec
Avg throughput per process          =    1164.91 KB/sec
Min xfer                    =     160.00 KB

The filesize here is 1GB and this is using 32k record size at 12 threads. Below is the full results for this random test:

  32 KB:
      1:     4.46 MB/sec      6.41 MB/sec
      3:     9.48 MB/sec     14.94 MB/sec
      6:    15.65 MB/sec     29.35 MB/sec
     12:                     52.29 MB/sec
     24:    22.81 MB/sec     87.42 MB/sec
     48:  ->27.41 MB/sec    128.32 MB/sec
     96:    25.49 MB/sec    149.81 MB/sec
    144:                  ->154.43 MB/sec

As you can see from the above result, thread 12 has no value since the min xfer is too low which I don't understand how / why that is.




Random number increment

I want to change starting number by +1/-1 value.

Example:

$startNumber = 1;

Echo $startNumber randomly, if number is 1 echo random 0 or 2, if number is 2 echo random 1 or 3.

I hope I explained well, is it possible to do this?




Programs illustrating calculations using pseudorandom number generators for uniform distribution

I need to create a program illustrating calculations using pseudorandom number generators (distribution diagrams). Generators of pseudorandom numbers for uniform distribution in java(method reverse cumulative distribution).

To be fair I don't know how I should do this but I need to :(. I'm really bad in programing but my teacher insisted on this procjet. Can anyone help me?




How to make HTML Incremental Number

excuse me if this is obvious, but i am an amateur.

I need to insert a forever incrementing (or counting) number into a piece of html code. Each time the page is loaded, the number should go up.

Whats the easiest way to do this?




How to fix random_state in random.sample

I'm making unittests for my code and need to fix random state, but It doesn't work. Does anybody have an idea how to deal with it? Here is simple example:

swap=5
while swap>0:
    random_state=0
    a,b,c=random.sample(range(10), 3)
    print(a,b,c)
    swap=swap-1

I get:

5 7 2
5 6 4
9 3 4
2 9 7
8 3 7

I need:

5 7 2
5 7 2
5 7 2
5 7 2
5 7 2




Bash (MAC): How to get a random file name in a directory

I want to get and open a random file from a folder.

Let's say I have a group of files in: /Users/Me/Downloads/Stuff/

I want a command that return the filepath of a randomly chosen file in the Stuff folder.

aka.

randFile = /Users/Me/Downloads/Stuff/randVid.exe

then I want to open with

open -a "QuickTime Player" randFile

I understand how to open the file with the desired program but I am having trouble finding out the solution to getting a randomly chosen file since I am not too well versed in bash.

Thanks for your time!




The usage of np.random.seed

According to What does numpy.random.seed(0) do?, we understand the usage concept of this code.

But, How we can understand what value is appropriate for seed? For example, in http://emcee.readthedocs.io/en/latest/tutorials/line/ we can see the value (123) and (42). np.random.seed(123) and np.random.seed(42). is it based on specific principle?

I appreciate your help and your attention.




Shuffle One Variable Within Group

This question is an extension of the excellent answer provided by Robert Picard here: How to Randomly Assign to Groups of Different Sizes

We have this dataset, which is the same as in the previous question, but adds the year variable:

sysuse census, clear
keep state region pop
order state pop region
decode region, gen(reg)
replace reg="NCntrl" if reg=="N Cntrl"
drop region
gen year=20 
replace year=30 if _n>15
replace year=40 if _n>35

If I just wanted to re-randomly assign reg's across all observations (without regard to group), I could implement the answer to the previous post:

tempfile orig
save `orig'
keep reg
rename reg reg_new
set seed 234
gen double u = runiform()
sort u reg_new
merge 1:1 _n  using `orig', nogen

How would the code be modified so that reg is shuffled, but only within year? For example, there are 15 observations where year==20. These observations should be shuffled separately than the other years.




How to get my population for a genetic algorithm from list of arrays in DEAP Python

I have program which produces list of lists as output:

[[1, 0, 1, 1,...], [..],...]

I want each array in this list to be treated as chromosome and my initial population to be selected from this list of lists as I put number of chromosomes I need for initial population.

I am using deap with Python 3.6.




How to make more random images

I have a wish. How to make more random images on one page with folder reading? How does it look like this php code? Please help me!




lundi 19 février 2018

monte carlo of a preexisting program

This is the Problem Set Up. I have to answer these questions:

The probability of winning the game at the first dice roll.

The probability of winning the game if the first roll gives a 4.

The probability of winning the game.

The probability of a game to require more than 5 dice rolls.

I know that all of these answers can easily be supplied through the code itself. My problem is that I have no idea how to edit the python code to give these desired outputs.

Here is the code:

# ===============================
# IMPORTS RANDOM NUMBER GENERATOR
# ===============================
import random

# ================================================================
# GENERATES RANDOMLY THE SUM OF TWO INTEGERS IN THE [1,6] INTERVAL
# ================================================================
def rollDices():
  return int(random.randint(1,6) + random.randint(1,6))

# ================================================
# RETURN THE OUTCOME STRING GIVEN AN INTEGER STATE
# ================================================
def getOutcome(outcome):  
  if(outcome == 0):
    result = "Lost at first roll."
  elif(outcome == 1):
    result = "Won at first roll."
  elif(outcome == 2):
    result = "Won on [4,5,6,8,9,10]"
  elif(outcome == 3):
    result = "Lost on [4,5,6,8,9,10]"
  return result

# ==============
# PLAYS THE GAME
# ==============
def playGame():

  # Define Variables
  gameFinished = False
  wonGame = False
  totRolls = 0

  while (not(gameFinished)):

# ROLL DICES
totScore = rollDices()
totRolls += 1;

# GAME IS LOST
if(totScore in [2,3,12]):
  gameFinished = True
  wonGame = False
  return 0,wonGame,totRolls,totScore

# GAME IS WON
if(totScore in [7,11]):
  gameFinished = True
  wonGame = True
  return 1,wonGame,totRolls,totScore

# JUST CONTINUE PLAYING
if(totScore in [4,5,6,8,9,10]):      

  # REPEAT UNTIL YOU FIND THE SCORE AGAIN OR 7
  newScore = 0
  while((newScore != totScore)and(newScore != 7)):

    newScore = rollDices()
    totRolls += 1;

    # CHECK IF YOU WIN OR LOOSE
    if(newScore == totScore):
      gameFinished = True
      wonGame = True
      return 2,wonGame,totRolls,totScore

    if(newScore == 7):
      gameFinished = True
      wonGame = False
      return 3,wonGame,totRolls,totScore

# ============
# MAIN PROGRAM
# ============
if __name__ == "__main__":

  intVal,wonGame,numRolls,lastScore = playGame()

  print("Outcome: %s" % (getOutcome(intVal)))
  if(wonGame):
    print("You have won the game.")
  else:
    print("You have lost the game.")
  print("Total rolls needed for this game: %d" % (numRolls))
  print("Last outcome: %d" % (lastScore))




R: how to sample rows with custom frequencies

I have a data frame in R that has two columns, one with last names, the other with the frequency of each last name. I would like to randomly select last names based on the frequency values (0 -> 1).

So far I have tried using the sample function, but it doesn't allow for specific frequencies for each value. Not sure if this is possible :/




RtlGenRandom/CryptGenRandom or other WinAPI to generate cryptographically secure random numbers (first quarter of 2018)

I swear, this seems to be changing every time I check the MSDN documentation. When I coded my executable Microsoft was suggesting to use RtlGenRandom API to generate cryptographically strong random numbers.

Now when I'm checking documentation for RtlGenRandom, the note there suggests using CryptGenRandom instead. But then another note for CryptGenRandom states this:

Important: This API is deprecated. New and existing software should start using Cryptography Next Generation APIs. Microsoft may remove this API in future releases.

So can someone show an example in C of how to use those "Cryptography Next Generation APIs" to generate a byte array of random numbers that Microsoft recommends now?




CountDownTimer + Random Number returns different values on TextSwitcher and logs

I'm writing a game that shows number to player and when such a number is divisible by 3, user has to tap the screen, if number isn't divisible user is doing nothing and waits for next number to show.

Numbers are shown in TextSwitcher and user has 3 secs to take action. Here is main logic:

public CustomTimer gameLoop(int time){
    this.time = time;
    return new CustomTimer(time, time + 5000) {
        @Override
        public void onTick(long millisUntilFinished) {
            //setting level depending on game itaration count
            switch (i) {
                case 10:
                    scopeMin = 49;
                    scopeMax = 200;
                    progressScope = 15;
                    break;
                case 25:
                    scopeMin = 120;
                    scopeMax = 300;
                    progressScope = 20;
                    break;
                case 45:
                    scopeMin = 390;
                    scopeMax = 620;
                    progressScope = 35;
                    break;
                case 80:
                    //disabling progress,because there are no more levels
                    progressBar.setVisibility(View.GONE);
                    nextLevel.setVisibility(View.GONE);
                    break;
            }

            //load random;
            randomNumber = scopeMin + random.nextInt(scopeMax - scopeMin +1);
            //present random to player
            textSwitcher.setText(String.valueOf(randomNumber));
            //progress bar logic
            if (progressBar.getProgress() == progressBar.getMax()) {
                Toast.makeText(MainActivity.this,MainActivity.this.getText(R.string.level_up), Toast.LENGTH_SHORT).show();
                progressStatus = 0;
                progressBar.setProgress(progressStatus);
                progressBar.setMax(progressScope);
            }
            //circle time animation
            animation.start();

        }

        @Override
        public void onFinish() {
            if (!Utils.succesCondition(randomNumber)) {
                //happens then user didn't do anything when he shouldn't
                scoreCount++;
                success();
            } else {
               //happens then user didn't tap the screen, but number was meeting conditions;
                backToStart();
            }
        }
    };
}

@Override
public void onClick (View v){
    if (Utils.succesCondition(randomNumber)) {
        //happens when user taps screen on number that meets conditions;
        loop.cancel();
        scoreCount+= 2;
        vibe.vibrate(50);
        success();
    } else {
        //happens when user taps screen on number that doesn't meets conditions
        backToStart();
    }
}


public void success() {
    scoreView.setText(MainActivity.this.getText(R.string.score) +" "+ String.valueOf(scoreCount));
    if (scoreCount == highScore && scoreCount != 0) {
        Toast.makeText(MainActivity.this, MainActivity.this.getText(R.string.new_record), Toast.LENGTH_SHORT).show();
    }
    if (scoreCount > highScore) {
        editor.putInt(HIGH_SCORE, scoreCount);
        editor.commit();
        highScoreView.setText(MainActivity.this.getText(R.string.high_score) +" "+ String.valueOf(scoreCount));
    }
    vibe.vibrate(25);
    i++;
    progressBar.setProgress(progressStatus +=1);
    loop.start();
    regresBar.clearAnimation();
}

  //returns to startAcvivity, contains info about last shown number and earned score
public void backToStart(){
    loop.cancel();
    Intent i = new Intent(MainActivity.this, StartActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    i.putExtra("scoreKey", String.valueOf(scoreCount));
    i.putExtra("numberKey", randomNumber);
    startActivity(i);
    overridePendingTransition(R.anim.slide_from_left,R.anim.slide_to_right);
    onPause();
    layout.setClickable(false);
}

In onCreate here is simple call:

 Utils.textSwitcherConfiguration(textSwitcher, MainActivity.this);
        loop = gameLoop(time).start();
        layout.setOnClickListener(MainActivity.this);

Problem is:

Sometimes TextSwitcher shows different number than it actually is (based by logs where I've seen different random number than was presented to player). For example player sees number 30, taps the screen and game says he lost because there was number 62...

Also sometimes I can see that when in Text Switcher animation passed number goes away it can change itself to another value, which looks like it's doing it between countdowns...

That obviously makes game unplayable. However that what I noticed is that bug appears way more frequent on slower, older or mid-range devices.




C++ rand() function acting really weirdly [duplicate]

I'm currently learning C++, and to practice a bit I'm coding a little game, that picks a word in a file, then changes its characters positions randomly so the player has to find the word (e.g "nalep": the user has to find the word "plane").
The game in itself works, but I'm getting a weird issue while trying to pick a random word from the file.
This is how my algorithm does the job:
- Counts the lines of the file
- Picks a random number between 1 and the number of lines
- Sets the position in the file back to the starting - Reads each line up to the good one

The problem I have is that each time I play the game, the same word is taken. You may say I'm using rand() the wrong way, but rand() only picks an other number when I change the content of my file..! (I can't even figure how these two elements are related)

Example content of the file:

game
book
file
computer

My code:

void playSecretWord() {

    ifstream file("C:\\Users\\chris\\Desktop\\word.txt"); // Opens file

    if (file) {
        string word; // Contains the word to find

        // Counts lines
        int count(0);
        while (getline(file, word)) { count++; } // Reads all lines and adds 1 to count each line

        // Goes back to the starting of the file
        file.clear();
        file.seekg(ios::beg);

        int random = rand() % count + 1; // Picks a random number that corresponds to a line

        for (int i(1); i <= random; i++) { getline(file, word); } // Reads each line up to the chosen one

        upper_string(word); // Capitalizes the word
        string goodAnswer = word; // Stores the word

        string newWord(""); // Word randomly written
        while (word.size() > 0) {
            int characterIndex = rand() % word.size(); // Takes a random character from the initial word
            newWord += word[characterIndex]; // Adds it
            word.erase(characterIndex, 1); // Removes it from the initial word
        }

        cout << "(" << random << ") What is this word : " << newWord << endl;

        string answer("");
        int i(0);
        while (answer != goodAnswer) {
            ++i; // Adds 1 to the number of tries
            cout << i << " > "; // Prints the number of the try
            cin >> answer; // Asks for the answer
            upper_string(answer); // Capitalizes the answer so it can be compared to the good answer (that has been capitalized too)
        }

        cout << "Good answer ! Tries : " << i << endl;

    }
    else {
        cout << "Error while opening file. Make sure the file exists." << endl;
    }
}

Thanks :)