jeudi 31 octobre 2019

Should I use std::seed_seq to seed std::mt19937?

Is it ok that 624 integers generated by random_device are directly used to seed mt19937? Should I use seed_seq?

class RDSeq {
public:
    template <typename It>
    void generate (It first, It last) const {
        std::random_device rd {};
        std::generate(first, last, std::ref(rd));
    }
};

std::mt19937 random {};
RDSeq seq {};
random.seed(seq);



Random sampling of elements from an array based on a target condition

I have an array (let's call it 'ElmInfo') of size N x 2 representing a geometry. In that array the element number and element volume are on the column 1 and column 2 respectively. The volume of elements largely vary. The sum of the volume of all elements leads to a value 'V' which can be obtained in Matlab as: V=sum(ElmInfo(:,2));

I want to randomly sample elements from the array 'ElmInfo' in such a way that the volume of sampled elements (with no repetition) will lead to a target volume 'V1'. Note: V1 is less than V. So I don't know the number of elements to be sampled. I am giving an example. For a sampling case number of sampled element can be '10' whereas in other sampling number of sampled element can be '15'.

There is no straightforward Matlab in-built function to meet the target condition. How can I implement the code in Matlab?




How To Get A Unique Random Token Without Searching The Database

I came up with a function that seems to generate a different random token every time, and decided to share it incase it is useful. The token generator includes milliseconds since 1970 to improve randomness.

function randomTimeBasedToken(){
    function getTokenNumber(){
        let d = new Date();
        let millis1 = Math.floor(d.getTime()/1000);
        let wait = 1;
        while(Math.random() > 0.4 && wait < 25){wait++;}
        d = new Date();
        let millis2 = Math.floor(d.getTime()/1000);
        let millis = (millis1*millis2)+(wait*Math.floor(Math.random()*10000));
        millis = Number(millis.toString().split('').reverse().join(''));
        return millis+wait.toString()+Math.floor(Math.random()*10000);
    }
    let numString1 = getTokenNumber(); let numString2 = getTokenNumber();
    while(numString1.length < numString2.length){numString1 += '0';}
    while(numString2.length < numString1.length){numString2 += '0';}
    numString1 = numString1.split(''); numString2 = numString2.split('');
    for(let i = 0; i < numString1.length; i++){
        if(numString1[i] && numString2[i]){
            numString1[i] = (Number(numString1[i])+Number(numString2[i])).toString();
        }
    }
    numString1 = numString1.join(''); numString2 = numString2.join('');
    let tokenNumber = numString1.toString()+numString2.toString();
    let token = btoa(tokenNumber).split('=').join('');
    token = token.split('');
    let editDigit = 0;
    for(let i = 0; i < token.length; i++){
        if(i % 10 === 0){
            editDigit = 1;
            token[i] = Math.floor(Math.random()*1000);
        }else if(editDigit > 0 && editDigit <= 5){
            editDigit++;
            token[i] = '';
        }
    }
    token = token.join('');
    return token.toString();
}

I put together this little function to scan for duplicate tokens:

let tries = 10000;

let randTokens = []; let tokenMatches = 0;
for(let i = 0; i < tries; i++){
    let token = randomTimeBasedToken();
    if(randTokens.includes(token)){
        tokenMatches++;
    }
    randTokens.push(token);
}
console.log('');
console.log('Token Duplicates:', tokenMatches);
console.log('Tries: ', tries);

I've tested this with 100000 tries, and it returned 0 duplicates I would try 1 million, but so far it seems that will take my computer 30 minutes to an hour to process 1000000. Processing 1 doesn't take long, but looping the function 100000 times takes about a minute or 2.




How to make a player move to a random X Position?

I want to develop my first game, but I have the problem that I don´t know how to make my player move to a random X Position. Instead of "0" (down) at Food.MoveTo(0, Game.SceneBounds.Top); it should be something that makes my player move to a random position.

      if(Food.Position.Y <= Game.SceneBounds.Bottom + Turtle.Size.Height / + 10 && Food.Position.X != Turtle.Position.X)
           {
               Food.MoveTo(0, Game.SceneBounds.Top);
                lives--;
           }



Is there a function for selecting a specific part of a 2d array in Java?

So, I have a school project that has 2 players and uses classes for weapons, traps and food and randomly places them on a specific part of the array. I have constructed a 2d array with the corresponding class type for each one of them, each one respectively called WeaponAreaLimits, FoodAreaLimits and TrapAreaLimits.

public class Board{

int[][] weaponAreaLimits = { {-2,2}, {2, 2}, {-2, -2}, {2, -2} };
int[][] foodAreaLimits = { {-3, 3}, {3, 3}, {-3, -3}, {3, -3} };
int[][] trapAreaLimits = { {-4, 4}, {4, 4}, {-4, -4}, {4, -4} }; //These are the specific coordinates that limit the placement of said weapons etc.
....

Catch is, weapons can be inside the box made from those points, but, food must be on the points surrounding weapons, not inside the box made from -3,3 3,3 -3,-3 and 3,-3. I constructed a method called createRandomFood() that randomly gives properties to Food objects. The ones I'm stuck on are the x and y ones, and how to only use those surrounding points and don't put them in a place they shouldn't be. Take a look on what I've wrote:

....
public void createRandomFood(){

    for(int i = 1; i < food.length; i++){
        food[i].setId(i + 1);
        food[i].setX; 
        food[i].setY; 
        food[i].setPoints(rand.nextInt(10) + 1); //Ignore the other setters
    }
}

My question is, is there a method or way to eliminate those points?




About rand() in c

q1)

Is this implementation of rand() and srand():

  • correct?
  • required by the standard?
unsigned int __seed;

void srand(unsigned int s) {
    __seed = s;
}

int rand() {
    __seed = __deterministic_and_fast_mathematical_expression_that_depend_only_of_seed(__seed); // Call it expr(), Declared somewhere
    return __seed;
}

q2)

Then, if q1) is true (or in another way), is it true to say that there is cycles in such function, that rand() can be interpreted as a cyclic sequence given at a random point?

// Hypotetically
srand(a)
if rand() = b then expr(a) = b
if rand() = a then expr(b) = a
// Then any call to rand would give successively [a, b, a, b, a, ...] infinitely
// This example is for two values but can work for a sequence of any length

I assume that the rand() function is cyclic after a maximal of 2^64 iterations on 64 bits and 2^32 on 32 bits. For example, if somewhere in the sequence there is:

12891, 872821, 33, 872821, 33, 872821, ... Infinitely

We can isolate the part 33, 872821 and the part before and make a arrow from second to first. Then the rand function could be described by this graph, generated by this procedure:

for(int i = 0; i < RAND_MAX; i++) {
    srand(i);
    while(rand() != i);
    // ISolate the cycle for seed = i
}

q3)

If q2) is true (or in another way), how can we ensure that this function won't give any "broken" sequence with repetitions or very fewly, or just it's unspecified?




counting elements in randomly generated binsize

I have generated a list of random extracted numbers

max = 1000;
rnorms2 = RandomVariate[UniformDistribution[{0, max}], 100];

I would like to count the number of elements that fall into randomly generated intervals. I generated the intervals as such:

t0 = 0;
tmax = 1000;
rnorms1 = Sort[RandomVariate[UniformDistribution[{t0, tmax}], 10]]

So that I could count the elements that fall between the i-th and the i+1-th element of rnorms1. I suppose I should use the Count function, but I am not sure how... can someone help?

thanks




Randomizing the order of an arrayList

The goal of this project is to take in a matrix of courses with prerequisites and print out a schedule with no prereq conflicts. I have gotten as far as adding the courses to the ArrayList of courses and printing it all out, however, im having issues doing a random restart on the ArrayList. I have tried swapping the indexes of the items in the array (although i don't know if im doing it correct), and I have also tried doing a collections.sort() on the ArrayList.

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

// Class DelivC does the work for deliverable DelivC of the Prog340

public class DelivC {

    File inputFile;
    File outputFile;
    PrintWriter output;
    Graph g;
    Node n;
    Edge e;
    int conflicts = -1;
    int counter = 0;
    int minConflicts = Integer.MAX_VALUE;
    String sem1 = "20203: ";
    String sem2 = "20205: ";
    String sem3 = "20211: ";
    String sem4 = "20213: ";
    String sem5 = "20215: ";
    String sem6 = "20221: ";
    String sem7 = "20223: ";
    ArrayList<Node> courseArray = new ArrayList<Node>();

    public DelivC(File in, Graph gr) {
        inputFile = in;
        g = gr;

        // Get output file name.
        String inputFileName = inputFile.toString();
        String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
        String outputFileName = baseFileName.concat("_out.txt");
        outputFile = new File(outputFileName);
        if (outputFile.exists()) { // For retests
            outputFile.delete();
        }

        try {
            output = new PrintWriter(outputFile);
        } catch (Exception x) {
            System.err.format("Exception: %s%n", x);
            System.exit(0);
        }

        /**
         * DELIVERABLE C.
         */

        // ADDING COURSES TO COURSEARRAY
        for (int i = 0; i < g.nodeList.size(); i++) {
            courseArray.add(g.nodeList.get(i));
        }

        while (counter < 10) {// conflicts != 0) {
            conflicts = 0;
            // SETTING SEMNUM AND SEM STRING
            for (int i = 0; i < g.nodeList.size(); i++) {
                if (i < 3) {
                    g.nodeList.get(i).setSemNum(1);
                    ;
                    sem1 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 6) {
                    g.nodeList.get(i).setSemNum(2);
                    ;
                    sem2 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 9) {
                    g.nodeList.get(i).setSemNum(3);
                    ;
                    sem3 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 12) {
                    g.nodeList.get(i).setSemNum(4);
                    ;
                    sem4 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 15) {
                    g.nodeList.get(i).setSemNum(5);
                    ;
                    sem5 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 18) {
                    g.nodeList.get(i).setSemNum(6);
                    ;
                    sem6 += g.nodeList.get(i).getName() + " ".toString();
                } else if (i < 21) {
                    g.nodeList.get(i).setSemNum(7);
                    ;
                    sem7 += g.nodeList.get(i).getName() + " ".toString();
                }
            }

            // CHECKING FOR CONFLICTS IN EDGE
            for (int k = 0; k < g.edgeList.size(); k++) {

                String edgeLabel = g.getEdgeList().get(k).getLabel();
                if (edgeLabel == ">") {
                    if (g.getEdgeList().get(k).getHead().getSemNum() >= g.getEdgeList().get(k).getTail().getSemNum()) {
                        conflicts++;
                    }
                } else if (edgeLabel == ">=") {
                    if (g.getEdgeList().get(k).getHead().getSemNum() > g.getEdgeList().get(k).getTail().getSemNum()) {
                        conflicts++;
                    }
                }
            }

            // PRINTING OUT SCHEDULE
            // if (minConflicts > conflicts) {
            System.out.println(courseArray);
            System.out.println(" ");
            System.out.println("There are currently " + conflicts + " conflicts.");
            System.out.println(sem1);
            System.out.println(sem2);
            System.out.println(sem3);
            System.out.println(sem4);
            System.out.println(sem5);
            System.out.println(sem6);
            System.out.println(sem7);
            System.out.println(" ");
            System.out.println(" ");
            // minConflicts = conflicts;
            // }

            // RESETS THE SEMESTER STRINGS
            sem1 = "20203: ";
            sem2 = "20205: ";
            sem3 = "20211: ";
            sem4 = "20213: ";
            sem5 = "20215: ";
            sem6 = "20221: ";
            sem7 = "20223: ";

            // RESETS THE CONFLICTS
            if (conflicts == 0) {
                conflicts = 0;
            } else {
                conflicts = -1;
            }
            counter++;
            // conflicts = 0;

            // RANDOMLY ASSIGNS NEW SEMESTERS TO EACH COURSE
            // randomRestart();
            Collections.sort(courseArray);
        }

    }

    public void randomRestart() {
        Random r = new Random();
        for (int i = 0; i < courseArray.size(); i++) {
            int nodeIndex = courseArray.indexOf(i);
            int swapIndex = r.nextInt(courseArray.size());
            Node currentNode = courseArray.get(i);
            Node swapNode = courseArray.get(swapIndex);
            Node tempNode = currentNode;
            currentNode = courseArray.get(swapIndex);
            swapNode = tempNode;

        }
    }

}



Implementing specific distribution in python

i want to return 1<l<10 with probability 1/(2^(l-1))

how i should do this rather then:

    x = random()
    if x < 0.5:
       return 2

and so on

thank you




beginner: How to convert random generated number into number from 1 to 7

I am still a beginner to the world of programing in c lang and i would like if i get your help!

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

int main()
{
    int week;

    /* Input week number from user */
    printf("Enter week number(1-7): ");
    scanf("%d", &week);

    switch(week)
    {
        case 1: 
            printf("Monday");
            break;
        case 2: 
            printf("Tuesday");
            break;
        case 3: 
            printf("Wednesday");
            break;
        case 4: 
            printf("Thursday");
            break;
        case 5: 
            printf("Friday");
            break;
        case 6: 
            printf("Saturday");
            break;
        case 7: 
            printf("Sunday");
            break;
        default: 
            printf("Invalid input! Please enter week number between 1-7.");
    }

    return 0;
}

Thats the question that i am trying to do:

"Write a C program that keeps a number from the user and generates an integer between 1 and 7 and displays the name of the weekday."

the only thing that is missing for me currently is that i want to make the usuer enters a random number then generate random number between 1 and 7




How to i prevent duplicates when generating a random number

I want 7 different variables generating from 1-36 however the variables must not have the same number as before without using an array or arraylist within the shortest possible line

private final int getconsolationprice1=rand.nextInt(36);
private final int getconsolationprice2=rand.nextInt(36);
private final int getconsolationprice3=rand.nextInt(36);
private final int getconsolationprice4=rand.nextInt(36);
private final int getconsolationprice5=rand.nextInt(36);
private final int getconsolationprice6=rand.nextInt(36);
private final int gettopprice=rand.nextInt(36);



Create a vector that runs random numbers in R

How i can create a vector that runs 10 random numbers between 1=100 and then to create variables that store the 10 variables of their square value.




mercredi 30 octobre 2019

How to execute several functions in random order?

I have defined four functions. These functions return the same varables but have different parameters.

Here is a simple example:

def func1(studentID, homework1, T1):
    if len(homework1) > T1:
        score[studentID] = 1
    else:
        score[studentID] = 0
    return score

def func2(studentID, homework2, T2, attendance):
    if len(homework2) > T2 and attendance == 1:
        score[studentID] = 1
    else:
        score[studentID] = 0
    return score

Now I need to execute these functions in a random order, i.e., sometimes func1 firstly and func2 secondly, but sometimes otherwise. I only know how to do that without parameters and returns as following:

import random
functions = [func1, func2]
random.shuffle(functions)
for i in functions:
    i()

But have no idea how to do it with parameters and returns.




How to make a1,a2, and a3 to be read in the looping?

I have a problem where I need to randomize the value in the array, but I need to declare a1, a2 and a3 outside because a1, a2 and a3 need to be equal to 100. But when I do that, there cannot be randomize.. the looping keep execute the same value of random.

a3=rd.randint(0,1)
a2=rd.randint(0,50)
a1=100-a2-a3
random_array =  np.array([np.array([rd.randint(0,1), rd.randint(0,2), a2, a1, a3]) for _ in range(x)])

Here the result that I got:

[ 0  2  6 94  0]   
[ 1  0  6 94  0]  
[ 1  1  6 94  0]   
[ 0  2  6 94  0] 
[ 1  0  6 94  0]   
[ 1  2  6 94  0]  
[ 0  2  6 94  0]  
[ 1  0  6 94  0]   
[ 1  1  6 94  0]   



Fill an array with random names

i'm entirely new at Python and i have a cool idea i want to put to work,

futurely i want to learn neural nets.

but my question right now is :

how to create an array named "names" and fill it with random generated names (the names don't have to exist, could be like = "asdddds asdasd"

i want to make massive array with this.

like :

names[1000000000]

i have no clue about random generated results.

and fullfil al the results with a random generated name.

Thank you!




Draw random numbers from pre-specified probability mass function in Matlab

I have a support (supp_epsilon) and a probability mass function (pr_mass_epsilon) in Matlab, constructed as follows.

supp_epsilon=[0.005 0.01 0.015 0.02]; 

suppsize_epsilon=size(supp_epsilon,2);

pr_mass_epsilon=zeros(suppsize_epsilon,1);

alpha=1;
beta=4;

for j=1:suppsize_epsilon
    pr_mass_epsilon(j)=betacdf(supp_epsilon(j),alpha,beta)/sum(betacdf(supp_epsilon,alpha,beta));
end

Note that the components of pr_mass_epsilon sum up to 1. Now, I want to draw n random numbers from pr_mass_epsilon. How can I do this? I would like a code that works for any suppsize_epsilon.




How to find the largest multiple of n that fits in a 32 bit integer

I am reading Functional Programming in Scala and am having trouble understanding a piece of code. I have checked the errata for the book and the passage in question does not have a misprint. (Actually, it does have a misprint, but the misprint does not affect the code that I have a question about.)

The code in question calculates a pseudo-random, non-negative integer that is less than some upper bound. The function that does this is called nonNegativeLessThan.

trait RNG {
  def nextInt: (Int, RNG) // Should generate a random `Int`. 
}

case class Simple(seed: Long) extends RNG {
  def nextInt: (Int, RNG) = {
    val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL // `&` is bitwise AND. We use the current seed to generate a new seed.
    val nextRNG = Simple(newSeed) // The next state, which is an `RNG` instance created from the new seed.
    val n = (newSeed >>> 16).toInt // `>>>` is right binary shift with zero fill. The value `n` is our new pseudo-random integer.
    (n, nextRNG) // The return value is a tuple containing both a pseudo-random integer and the next `RNG` state.
  }
}

type Rand[+A] = RNG => (A, RNG)

def nonNegativeInt(rng: RNG): (Int, RNG) = {
  val (myInt, nextRng) = rng.nextInt
  val nnInt = {
    if (myInt == Int.MinValue) Int.MaxValue
    else if (myInt < 0) -myInt
    else myInt
  }
  (nnInt, nextRng)
}

def nonNegativeLessThan(n: Int): Rand[Int] = { rng =>
  val (i, rng2) = nonNegativeInt(rng)
  val mod = i % n
  if (i + (n-1) - mod >= 0) (mod, rng2)
  else nonNegativeLessThan(n)(rng2)
}

I have trouble understanding the following code in nonNegativeLessThan that looks like this: if (i + (n-1) - mod >= 0) (mod, rng2), etc.

The book explains that this entire if-else expression is necessary because a naive implementation that simply takes the mod of the result of nonNegativeInt would be slightly skewed toward lower values since Int.MaxValue is not guaranteed to be a multiple of n. Therefore, this code is meant to check if the generated output of nonNegativeInt would be larger than the largest multiple of n that fits inside a 32 bit value. If the generated number is larger than the largest multiple of n that fits inside a 32 bit value, the function recalculates the pseudo-random number.

To elaborate, the naive implementation would look like this:

def naiveNonNegativeLessThan(n: Int): Rand[Int] = map(nonNegativeInt){_ % n}

where map is defined as follows

def map[A,B](s: Rand[A])(f: A => B): Rand[B] = {
  rng => 
    val (a, rng2) = s(rng)
    (f(a), rng2)
}

To repeat, this naive implementation is not desirable because of a slight skew towards lower values when Int.MaxValue is not a perfect multiple of n.

So, to reiterate the question: what does the following code do, and how does it help us determine whether a number is smaller that the largest multiple of n that fits inside a 32 bit integer? I am talking about this code inside nonNegativeLessThan:

if (i + (n-1) - mod >= 0) (mod, rng2)
else nonNegativeLessThan(n)(rng2)



Python random unique value for multiple variables

The issue I'm having is that I need to set letters a-z a random unique value from 1 to 26. The same number equalling multiple letters is what I want to avoid. Current methods I have is over 70 lines and is just while loops of each letter to not equal the value given previously for a different letter. Any ideas?




Simulating correlated lognormals in Python

I'm following the answer in this question How can I sample a multivariate log-normal distribution in Python?, but I'm getting that the marginal distributions of the sample data fail to have the same mean and standard deviation of the inputted marginals. For example, consider the multivariate distribution below in the code sample. If we label the marginals as X, Y, and Z, then I would expect that the scale and location parameters (implied from the sample data) to match inputted data. However, for X, you can see below that the scale and location parameters are 0.1000 and 0.5219. So the scale is what we expect, but the location is off by 4%. I'm thinking I'm doing something wrong with the covariance matrix, but I can't seem to figure out what is wrong. I tried setting the correlation matrix to the identity matrix and then the location and scale of the sample data match with the inputted data. Something must be wrong with my covariance matrix, or I'm making another fundamental error. Any help would be appreciated. Please advise if the question is unclear.

import pandas as pd
import numpy as np
from copy import deepcopy

mu  = [0.1, 0.2, 0.3]
sigma = [0.5, 0.8, 0.6]
sims = 3000000
rho = [[1, 0.9, 0.3], [0.9, 1, 0.8], [0.3, 0.8 ,1]]

cov = deepcopy(rho)
for row in range(len(rho)):
    for col in range(len(rho)):
        cov[row][col] = rho[row][col] * sigma[row] * sigma[col]

mvn = np.random.multivariate_normal(mu, cov, size=sims) 

sim = pd.DataFrame(np.exp(mvn), columns=['X', 'Y', 'Z'])

def computeImpliedLogNormalsParams(mean, std):
    # This method implies lognormal params which match the moments inputed 
    secondMoment = std * std + mean *mean
    location = np.log(mean*mean / np.sqrt(secondMoment))
    scale = np.sqrt(np.log(secondMoment / (mean * mean)))
    return (location, scale)

def printDistributionProp(col, sim):
    print(f"Mean = {sim[col].mean()}, std = {sim[col].std()}")
    location, scale = computeImpliedLogNormalsParams(sim[col].mean(), sim[col].std())
    print(f"Matching moments gives a lognormal with location {location} and scale {scale}")


printDistributionProp('X', sim)

Output:

Mean = 1.2665338803521895, std = 0.708713940557892
Matching moments gives a lognormal with location 0.10008162992913544 and scale 0.5219239625443672   

Observing the output, we would expect that scale parameter to be very close to 0.5, but it's a bit off. Increasing the number of simulations does nothing since the value has converged.




How do I create a vectorized version of randsample in Matlab

I have a support (supp_epsilon) and a probability mass function (pr_mass_epsilon) in Matlab, constructed as follows.

    supp_epsilon=[0.005 0.01;
                  0.01  0.015;
                  0.015 0.02;
                  0.02  0.025]; 

    suppsize_epsilon=size(supp_epsilon,1);

    pr_mass_epsilon=zeros(suppsize_epsilon,1);

    mu_epsilon=[0; 0];
    sigma_epsilon=[1 0.5; 0.5 1];

    pr_mass_epsilon=zeros(suppsize_epsilon,1);

    for j=1:suppsize_epsilon
 pr_mass_epsilon(j)=mvnpdf(supp_epsilon(j,:),mu_epsilon.',sigma_epsilon)/sum(mvnpdf(supp_epsilon,mu_epsilon.',sigma_epsilon));
     end

Note: supp_epsilon is 4x2. Each 1x2 row of supp_epsilon is an element of the support of interest.

Question: I want to draw n=10 vectors of size 1x2 from pr_mass_epsilon. Each of these vectors has to be a row of supp_epsilon. For n very large the empirical frequency of the drawn vectors have to be close to pr_mass_epsilon.

How can I do this?

Note: This question addresses the scalar case where the answer suggests to use randsample.




whats problem with this code. why its giving a wrong output?

I was trying to make a simple rock paper game using random function but i am unable to understand why its printing output two times... the problem is coming with scanf function as first time its working perfectly second time it refuses to accept a vale and then then again it works perfectly

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
void main()
{
    int i,r,cp=0,pp=0;
    char c,p;
    srand(time(0));
    while(cp<5&&pp<5)
    {
        r=rand();
        do
        {
            r=r/10;
            if(r==0)
            {
                r=rand();
            }
        }
        while (r>10||r<2);
        printf("enter your choice");
        scanf("%c",&c);
        if(r<=3)
        p='r';
        else if(r<=6)
        p='p';
        else
        p='s';
        printf("\ncomputer choose  %c\n",p);
        if(p=='r'&&c=='p')
        cp++;
        if(p=='p'&&c=='s')
        cp++;
        if(p=='s'&&c=='r')
        cp++;
        if(c=='r'&&p=='p')
        pp++;
        if(c=='p'&&p=='s')
        pp++;
        if(c=='s'&&p=='r')
        pp++;
        printf("computer score = %d\nyour score = %d\n",pp,cp);

    }
}



If/elif wrong display of "random" output

## After input amount of chips and amount of bet and choose number, the number is always red, this worked few days ago but i changed something and there is impossible to get "black" ## If elif statement is considering only when IF is not True, then i dont get why spin= number from second pool of numbers but there is "red" from first statement

import random
#program
while True:
    print("Enter 'rules' to show rules")
    print("Enter 'play' to play the game")
    print("Enter 'author' to show info about creator")
    print("Enter 'quit' to end the program")
    user_input=input()
    if user_input.lower()=="quit":
        break
    elif user_input.lower()=="rules":
        print(cont)
    elif user_input=="play":
        while True:       #LOOOP IN DA LOOOP
            start=int(input("How much chips you want for start?\n"))
            amount=int(input("How much you want bet\n"))
            bet=int(input("Place your bet\n"))
            spin=random.randint(0,36)
            #Continue/break?
            if bet>36:
                print("There is only 36 numbers!")
            elif bet<0:
                print("You need bet number beetwen 0 and 36")
            elif spin==bet:
                print("You won",amount*35)
                print("Now you have",start-amount+amount*35)
            else:
                print("You lose")
                print("Now you have",start-amount) #Aktualizacja stacka
                if spin==1 or 3 or 5 or 7 or 9 or 12 or 14 or 16 or 18 or 19 or 21 or 23 or 25 or 27 or 30 or 32 or 34 or 36:
                    print(spin,"red")
                elif spin==2 or 4 or 6 or 8 or 10 or 11 or 13 or 15 or 17 or 20 or 22 or 24 or 26 or 28 or 29 or 31 or 33 or 35:
                    print(spin,"black")
                else:
                    print(spin,"green")
    elif user_input=="author":
         print("Jacob X")
    else:
         print("Unknown command")



Creating sequences in MySQL?

I saw in articles that can we use functions rand() and floor() to create a sequences from 0 and 1

mysql

SELECT floor(rand(0)*2) FROM security.users;

+------------------+
| floor(rand(0)*2) |
+------------------+
|                0 |
|                1 |
|                1 |
|                0 |
|                1 |
|                1 |
|                0 |
|                0 |
|                1 |
|                1 |
|                1 |
|                0 |
|                1 |
|                1 |
|                1 |
|                0 |
+------------------+
16 rows in set (0.00 sec)

is there any another way to achieve this ?
* i dont talk about auto_increment ;




How to get random product url from amazon?

I try since the last week to get a random URL from amazon using python, I tried boto3, websites etc but I didn't success to do it. Can anyone help me to do it? Thank you for your help.




How to insert blank cells randomly on rows

How In Excel vba I can insert blank cells randomly in each rows (shift cell to right) with parameters to fix the number of cells inserted. There's a lot of rows




String disappears after clicking on another textbox

I'm trying to generate random integer value (Barcode) when I click on a button. Then, I 'm checking two tables (stocks, units) if the new barcode already exist or not. If it's unique, the new barcode will be written in the textbox.

It's all working but when I click on another texbox of form the barcode disappears.

PS: I defined newBarcode in global area as Integer..

        {
            BarcodeGenerator();
            string _newBarcode = newBarcode.ToString();
            if (context.Stocks.Any(c => c.Barcode == _newBarcode) || context.Units.Any(c => c.Unit == _newBarcode))
            {
                BarkodOlustur();
                return;
            }
            else
            {
                txtBarcode.Text = _newBarcode;
            }
        }



 private void BarcodeGenerator()
        {
            Random rnd = new Random();
            newBarcode = rnd.Next(10000000, 99999999);
        }



mardi 29 octobre 2019

Generate an Asymmetric NxM matrix whose Rows and Columns Independently Sum to 1

Given a target matrix size of N rows and M columns, is it possible to pick values such that all rows and columns sum to 1, on the condition that the matrix is not symmetric across the diagonal? Here's a target matrix I was able to generate when N==M (The problems arise when N!=M - see below):

[[0.08345877 0.12844672 0.90911941 0.41964704 0.57709569]
 [0.53949086 0.07965491 0.62582134 0.48922244 0.38357809]
 [0.80619328 0.27581426 0.31312973 0.26855717 0.4540732 ]
 [0.11803505 0.88201276 0.1990759  0.2818701  0.63677383]
 [0.57058968 0.75183898 0.07062126 0.6584709  0.06624682]]

I'm writing this in numpy. Currently I've written the following (brute force) code, which I know works when n==m. However, if n != m, rowwise and columwise sums don't converge to 0, and the ratio of rowwise sums to columwise sums converges to (n/m):

n,m = (5,4)
mat = np.random.random((n,m))
for i in range(100):
    s0 = mat.sum(0)
    s1 = mat.sum(1)[:,newaxis]
    mat = (mat/s0)
    mat = (mat/s1)
    if i%10 == 0:
        print(s0[0]/s1[0,0])

The final output in this case is 1.25 (I.e. n/m, or 5/4). I'm beginning to think this might not be mathematically possible. Can someone prove me wrong?




How to insert random numbers into an array and sort them

My code is supposed to take the random number generated in the random method and sort them but it's only giving me one number.

My program is a random number generator that is supposed to make 1000 numbers that I can sort but my code only inserts one number into the array.

public static void main(String[] args) {
    // write

    int max = 1000;
    int min=0;
    int range = max - min + 1;

    // generate random numbers within 1 to 10
    for (int i = 0; i < 1000; i++) {
        int rand = (int) (Math.random () * range) + min;
        System.out.println ( rand );




        int array[] = {rand};
        int size = array.length;

        for ( i = 0; i < size - 1; i++) {
            int min1 = i;

            for (int j = i + 1; j < size; j++) {
                if (array[j] < array[min1]) {
                    min = j;
                }
            }
            int temp = array[min1];
            array[min1] = array[i];
            array[i] = temp;
        }

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



permutation test on throwing three dice with sides labelled in a binary way

I want to model throwing three, six-sided dice permuted n number of times (say 6,000 times), where each die has three sides labelled 1 and 0.

I want to test whether three dice getting either all 1s or all 0s ~600/6000 times is more than expected by chance, but don't know how to do it on R.

Any help is greatly appreciated or links to tutorials (this didn't help much: https://docs.tibco.com/pub/enterprise-runtime-for-R/4.0.2/doc/html/Language_Reference/base/sample.html)




How to obtain an array without repeated values with one function

I want to create two arrays, none of them can have repeated values and if posible I look for an answer in the same loop.

for(int i=0;i<MAX;i++){//MAX=vector's number of values
            scanf("%d", &vector[i]);//reads the number from the keyboard
            while(j!=i){//Looks for each vector[i] if there is a vector[j], with j<i, with that value already. j starts at 0
                    if(vector[j]==vector[i]){
                            printf("\nWrite another number\n");
                            scanf("%d",&vector[i]);
                            j=0;
                    }
                    else
                            j++;
            }
    }

for this second loop I look for the same result, a non repeated set of values, but with random numbers.

for(int i=0;i<MAX;i++){
            vector[i]=(rand()%MAX-MIN+1)+MIN;
            while(j!=i){
                   if(vector[j]==vector[i]){
                            vector[i]=(rand()%MAX-MIN+1)+MIN;;
                            j=0;
                    }
                    else
                            j++;
            }
    }

I have been trying to come with a way to generate a random number between two intervals, like (2,10)U(12,20), so whenever you found a repeated value the next random number does not contain it, but I can not find any way to do it that way.

Thanks for your help




How do I simulate intermittent demand in MATLAB?

In R, there is a function to simulate intermittent demand called simID in the tsintermittent package.

Is there a MATLAB equivalent? If not, how do I generate random samples of intermittent demand in MATLAB?

Relevant parameters include variability and intermittency.




How to get same random number seen by multiple classes (like a global variable)

I have a random number class (and I've experimented with making it static, but then for some reason I can't generate a random number if it's static because it says that the random class is not defined within the scope).

 public class GlobalRandom
        {
            public int generateRandom()
            {
                Random rnd = new Random();
                int randomNum = rnd.Next(0, 10);
                return randomNum;
            }
        }

Then I create an instance of it in another class and method where I want the random number.

GlobalRandom globalrandom = new GlobalRandom();
int randomNumber = globalrandom.generateRandom();

However, I want the SAME random number to be seen across the whole program and able to be used by any class. I can do this with other variables, but not with random because if you try and create a static method it won't let you use the random class. I'm at a loss at how to do this.

Background info: This is for an ASP.NET web app, so helping me with a console-style system won't be relevant, since I'm not creating instances of the other classes, but rather returning a JSON object for AJAX. The object I'm returning is determined by the random number, then I send a value back to the controller that has to match up with a value that was picked by the same random number, otherwise it just won't work!




How to generate certain length Credit Card number with prefix?

Trying to generate a certain length credit card number with a prefix given.

    while len(str(cc_number)) < (len(str(length)) - 1):
        digit = str(random.randrange(0, 9))
        cc_number = str(cc_number) + str((digit))
        return cc_number

I'm expecting to get say 16 digits long number with a variable size prefix given. How do i make this piece of code generate a right size string of numbers? This code by the way only concatenates 1 random digit to the end of the string... So i expect to get '4349578451278456', but the actual output is '41'




Notify_one doesn't choose random thread, as intended

Thanks for advance for any help. Trying to make a program that would create 6 threads, then each 2 seconds randomly choose one and make it print its number. I am obviously doing something wrong, because it just keeps printing 0-1-2-3-4-5 endlessly. Here's the code:

#include <thread>
#include <memory>
#include <chrono>
#include <condition_variable>
std::condition_variable* cv = new std::condition_variable();
std::mutex cv_m;

void threadFunc(std::shared_ptr<bool> flag2, int id)
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(cv_m);
        cv->wait(lock);
        if (true)
            if (*flag2) std::cout << "Thread" << " " << id << std::endl;
    }
}
int main() {

    std::shared_ptr<bool> f2 = std::make_shared<bool>(false);

    std::thread threads[6];

    for (int i = 0; i < 6; i++)
        threads[i] = std::thread(threadFunc, f2, i);
    *f2 = true;

    while (true)
    {
        cv->notify_one();
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }

    return 0;
}```



SwiftUI View struct without reloading

I would like to create a starry background view in SwiftUI that has its stars located randomly using Double.random(), but does not reinitialise them and move them when the parent view reloads its var body.

struct ContentView: View {
    @State private var showButton = true

    var body: some View {
        ZStack {
            BackgroundView()
            if showButton {
                Button("Tap me"){
                    self.showButton = false
                }
            }
        }
    }
}

I define my background view as such.

struct BackgroundView: View {
    var body: some View {
        ZStack {
            GeometryReader { geometry in
                Color.black
                ForEach(0..<self.getStarAmount(using: geometry), id: \.self){ _ in
                    Star(using: geometry)
                }
                LinearGradient(gradient: Gradient(colors: [.purple, .clear]), startPoint: .bottom, endPoint: .top)
                    .opacity(0.7)
            }
        }
    }

    func getStarAmount(using geometry: GeometryProxy) -> Int {
        return Int(geometry.size.width*geometry.size.height/100)
    }
}

A Star is defined as

struct Star: View {
    let pos: CGPoint
    @State private var opacity = Double.random(in: 0.05..<0.4)

    init(using geometry: GeometryProxy) {
        self.pos = CGPoint(x: Double.random(in: 0..<Double(geometry.size.width)), y: Double.random(in: 0..<Double(geometry.size.height)))
    }



    var body: some View {
        Circle()
            .foregroundColor(.white)
            .frame(width: 2, height: 2)
            .scaleEffect(CGFloat(Double.random(in: 0.25...1)))
            .position(pos)
            .opacity(self.opacity)
            .onAppear(){
                withAnimation(Animation.linear(duration: 2).delay(Double.random(in: 0..<6)).repeatForever()){
                    self.opacity = self.opacity+0.5
                }
            }
    }
}

As one can see, a Star heavily relies on random values, for both its animation (to create a 'random' twinkling effect) as well as its position. When the parent view of the BackgroundView, ContentView in this example, gets redrawn however, all Stars get reinitialised, their position values change and they move across the screen. How can this best be prevented?

I have tried several approaches to prevent the positions from being reinitialised. I can create a struct StarCollection as a static let of BackgroundView, but this is quite cumbersome. What is the best way to go about having a View dependent on random values (positions), only determine those positions once?


Furthermore, the rendering is quite slow. I have attempted to call .drawingGroup() on the ForEach, but this then seems to interfere with the animation's opacity interpolation. Is there any viable way to speed up the creation / re-rendering of a view with many Circle() elements?




Sampling from normal distribution not working in tflite model

In variational autoencoders, the model samples from a normal distribution in the latent space. That means that even when providing the same inputs for the model, the output will be slightly different during each run. I want to use such a VAE as tflite model.

Even though the model is convertible and can be loaded, the result is always exactly the same. Due to the random functions not being included in tflite as of now, I allow the model to use actual tensorflow ops. Below is the code for training, converting and testing the model.

import numpy as np
import tensorflow as tf
from tensorflow import keras

print(tf.__version__)

### TRAINING DATA
training_data = np.random.rand(1000, 10)
train_dataset = tf.data.Dataset.from_tensor_slices((training_data, training_data))
train_dataset = train_dataset.shuffle(1000).batch(100)

### MODEL WITH RANDOM NORMAL
x = keras.layers.Input(shape=(10,))
z_mu = keras.layers.Dense(5)(x)
z_sigma = keras.layers.Dense(5, activation=tf.nn.sigmoid)(x)
eps = tf.random.normal(shape=(5,))  # THIS should ensure different outputs on each run
z = z_mu + eps * z_sigma
x_decoded = keras.layers.Dense(10)(z)
model = keras.models.Model(x, x_decoded)

### LOSS
recon_err = tf.reduce_sum(tf.abs(x - x_decoded), axis=1)
kl_div = -.5 * tf.reduce_sum(1 + 2 * tf.math.log(z_sigma) - tf.square(z_mu) - tf.square(z_sigma), axis=1)
total_loss = tf.reduce_mean(recon_err + kl_div)
model.add_loss(total_loss)

### TRAINING
model.compile(optimizer='adam')
print(model.summary())
model.fit(train_dataset, epochs=5)

### SAVE
keras_file = 'vae_test.h5'
keras.models.save_model(model, keras_file)

### CONVERSION
converter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file(keras_file)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS,
                                       tf.lite.OpsSet.SELECT_TF_OPS]
tflite_file_name = 'vae.tflite'
tflite_model = converter.convert()
open(tflite_file_name, 'wb').write(tflite_model)

### TEST DATA
dataset = np.zeros((1, 10)).astype(np.float32)

### TEST THE MODEL
interpreter = tf.lite.Interpreter(model_path=tflite_file_name)
interpreter.allocate_tensors()
input_detail = interpreter.get_input_details()[0]
output_detail = interpreter.get_output_details()[0]
print('Input detail: ', input_detail)
print('Output detail: ', output_detail)

interpreter.set_tensor(input_detail['index'], dataset)
interpreter.invoke()
pred_litemodel = interpreter.get_tensor(output_detail['index'])
print(f'\nPrediction')
print(pred_litemodel)
print()

interpreter.set_tensor(input_detail['index'], dataset)
interpreter.invoke()
pred_litemodel = interpreter.get_tensor(output_detail['index'])
print(f'\nPrediction')
print(pred_litemodel)
print()

Can somebody explain why the model behaves like a deterministic function?




Does Spark Random Forest Classifier Balance Subsamples?

I cannot tell if Spark is implementing any sort of (outcome) label balancing when subsampling data in ensemble models. Neither of the argument descriptions mentions a specific sampling implementation. I would like to know if the sample is being balanced in any way.

If it is a simple bootstrap sample, what would happen if a rare outcome was being modeled and a subsample with no instances of one label was drawn?

From the Ensembles documentation:

subsamplingRate: This parameter specifies the size of the dataset used for training each tree in the forest, as a fraction of the size of the original dataset. The default (1.0) is recommended, but decreasing this fraction can speed up training.

From the Decision Tree documentation:

subsamplingRate: Fraction of the training data used for learning the decision tree. This parameter is most relevant for training ensembles of trees (using RandomForest and GradientBoostedTrees), where it can be useful to subsample the original data. For training a single decision tree, this parameter is less useful since the number of training instances is generally not the main constraint.




Creating a 2D array with random numbers WITHOUT NUMPY (Python)

How can I create a 2D array with random numbers without using NumPy (Python)




How can I get a binary sequence from rand() function of C?

I need to get a sequence of bits which will represent the work of LCG in rand() function in C, but I've no idea how to do it. Found a code example which looks like this

// C program for generating a 
// random number in a given range. 
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

// Generates and prints 'count' random 
// numbers in range [lower, upper]. 
void printRandoms(int lower, int upper,  
                             int count) 
{ 
    int i; 
    for (i = 0; i < count; i++) { 
        int num = (rand() % 
           (upper - lower + 1)) + lower; 
        printf("%d ", num); 
    } 
} 

// Driver code 
int main() 
{ 
    int lower = 0, upper = 1, count = 30; 

    // Use current time as  
    // seed for random generator 
    srand(time(0)); 

    printRandoms(lower, upper, count); 

    return 0; 
}

but I'm not sure if the sequence from this program will be an LCG binary sequence. Is there any other ways of getting bitstream from rand?




Reading file's lines randomly and logger them

I'm trying to read a text file with a lot of lines and log them by using logger via bash scrip. I achieved to read the file line by line with following code

#!/bin/bash

filename=logger.txt
[[ -f ${filename} ]] || exit 1
x=0
while read -r line; do
            logger "$line";
           sleep 0.1;
    done < $filename
    exit 0

but how to read lines randomly and log them.

I'm trying it with this but without any success

#!/bin/bash

filename=logger.txt
[[ -f ${filename} ]] || exit 1
x=0
while read -r line; do

         logger "%06d %s\n" $RANDOM "$line";
         sleep 0.1;
         done < $filename
         exit 0

How could I implement the RANDOM function into the script or is there another option to achieve it? I tried shuf but it read just one line and then stopped.




Extracting a random word in a string

I would like to extract a random in a given line so I called a random number to use it as an index. But it keeps giving me an error.

terminated called after throwing an instance of 'std::out_of_range'.

I know it occurs because the index value is exceeded size of the string. But I can not find any mistake in my code.

do {
    int size = line.length();
    srand(time(NULL));
    index = rand() % size;
} while (isspace(line.at(index)));

This is a random number generator. I extract a line from a text file.

I used do { } while (isspace(line.at(index))); because I do not want it to be space, in order to generate a random number again if it is space.

What I want is this.

0123456789

Example... Index : 4

F---i----L F : First, L : Last

if (index == 0) {
    while (!isspace(line.at(last + 1))) {
        last = last + 1;
    }
}

else if (index == (size - 1))) {

    while (!isspace(line.at(first - 1))) {
        first = first - 1;
    }
}

else {
    while (!isspace(line.at(first - 1))) {
        first = first - 1;
    }

    while (!isspace(line.at(last + 1))) {
        last = last + 1;
    }
}

for (int i = first; i <= last; i++) {
    targetword += line.at(i);
}

This is how I calculate first and last index and print out the chosen word and it should not make any error...

please help me thank you




lundi 28 octobre 2019

How to autogenerate a random, unique, alphanumeric string as serial number of a product in laravel

I would like to have a string which is unique and which can be autogenerated from the controller to the table directly. How am I to handle that In the controller

I would like to have a $serail_number somewhere that will be unique

public function store()
{

    Slaughter::create($this->validateRequest());
    return redirect('/slaughter')->with('message', 'Clinic Details Attached');
}

private function validateRequest()
{ 

    return request()->validate([
        'animal_id' => 'required',
        'slaughter_id' => 'required',
        'slaughtering' => 'required',
    ]);
}



Sample dataframe with number of records sampled per hour predefined

I have to sample a dataframe (df1) and I have another dataframe (df2) that tells me how many records I should retrieve from each hour of the day.

For example, df1:

   Hour number
0.  00    A
1.  00    B
2.  00    C
3.  01    D
4.  01    A
5.  01    B
6.  01    D

df2:

   Hour number
0.  00    1
1.  01    2

So that in the end, I would get for example, record number 1 for midnight and records 3 and 5 for 1 am (or any other combination so long as it respects the number in df2)

The thing is that I need to write this in a function in order for me to call this inside another function.

So far I have

def sampling(frame):
     return np.random.choice(frame.index)

but I am failing to add the constraints of the df2.

Could anybody help?




Why "While" doesn't show anything after input command?

Just i did somethin wrong with while loop i supposed

After print menu section u can input something but than program ends.

print("Welcome in American Roulette")
rules=("blabla rules of roulette")
import random


while True:
    print("Enter 'rules' to show rules")
    print("Enter 'play' to play the game")
    print("Enter 'author' to show info about creator")
    print("Enter 'quit' to end the program")
    user_input=input()
    if user_input=="quit" or "Quit":
        break
    elif user_input=="rules" or "rule" or "Rules" or "Rule":
        print(rules)
    elif user_input=="play":
        bet=int(input("Place your bet\n"))
        amount=float(input("How much you want to bet?"))
        spin=random.randint(0,36)
        if bet>36:
            print("You need to bet number beetwen 0 and 36!")
        elif bet<0:
            print("You need to bet number beetwen 0 and 36")
        elif spin==bet:
            print("You won",amount*35)
            print("Now you have",start-amount+amount*35)
        else:
            print("You lose")
    elif user_input=="author":
        print("Jacob X")
    else:
        print("Unknown command")

Added some text here becouse my code is mostly code ffs




How can I randomize numbers while validating that the output exists in another dataset?

I have one data set on US Loans but the the zip-codes have the last 2 digits blanked out so 35401 would be listed in the data as 354XX. To make the data plot-able, I wanted to randomize the last two digits so that the last two digits would be a random value from 00-99 where the output zip code would be a real zip code in the US (I have another data set that is simply a list of current US Zip codes). How could I do this in R?




Loop for every x object in JSON aray

I'm working on this small project (extension) where I fetch data from a JSON array with rapidapi, I'm able to get the data. But i'm unclear and new to get how to loop thru the whole dataset (which eventually I would try to store on the localstorage, but that's irrelevant for know)

concrete: I want to loop randomly thru the whole array and show every 1ste object of every second array in the whole array.

example of JSON array

0:{4 items
"kanji":{6 items
"character":"一"  ----> this one
"meaning":{...}1 item
"strokes":{...}3 items
"onyomi":{...}2 items
"kunyomi":{...}2 items
"video":{...}3 items
}
"radical":{...}7 items
"references":{...}3 items
"examples":[...]9 items
}
1:{4 items
"kanji":{6 items
"character":"飼"  ----> or this one
"meaning":{...}1 item
"strokes":{...}3 items
"onyomi":{...}2 items
"kunyomi":{...}2 items
"video":{...}3 items
}
"radical":{...}7 items
"references":{...}3 items
"examples":[...]6 items
}

And so one.

I've tried to get the JSON array and show an object of it. Then I tried to change the [1] number to a variable. But there I got stuck. I can't figure out how to create a random generator that picks every 1st object of the array like shown in the json array above.

var myfetch = fetch("https://kanjialive-api.p.rapidapi.com/api/public/kanji/all", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "x",
        "x-rapidapi-key": "x"
    }
})




/** Parse response object
 * returns object parsed from json
 */
const getJsonFromRes = (res) => res.json();

/**  Logs some data. 
 * returns undefined
 */
//const logData = (data) => console.log(data[1].kanji.character);

/** Ignores its data parameter. Attempts to set an element to an uninitialized variable.
 */
const accessKanji = (data) => document.getElementById('kanji').innerHTML = data[1].kanji.character;

// print error to console. returns undefined.
const logError = (err) => console.log(err);

myfetch 
  .then(getJsonFromRes) 
  //.then(logData) 
  .then(accessKanji) 
  .catch(logError);

I want to get a new object (the character object) every time at random. (how I would activate that is another step in my project) 

Any guidance or link to tutorials about this that work well is very much appreciated!! 
Or a an example of course would be ideal.



Random generation for a particular distribution

I have two probability density functions f1 and f2 that I have combined in a function f using credibility theory. Now I want to generate random points using f, how can I do that?

Moreover, suppose I do not have the density función, but I have the cumulative distribution function or its inverse, is it also possible to generate random numbers?

I know that if the distribution is standard (normal, gamma, weibull, etc.) I can use rnorm, etc., and the problem is solved. But I do not know how to do it if the density function is not one of those.




'Random' python module inside loops

I am trying to create a python script that takes a string and adds random numbers in random parts of the string. For example:

str = 'PinguinsAreFun' output = 'Pi2ngu2in4sAre4F7un'

I tried to search for a module that does this very thing but I had no luck. So I thought it would be a good idea to write my own code that will get the job done... Well.. It wasn't a good idea that's for sure...

This is what I came up with:

import random

num = '0123456789'

str = 'This_Is_A_String'

while k > 15:

    k =+ 1

    rndm = random.choice(num)

    result = str[:int(rndm)] + rndm + str[int(rndm):]

print(result)

The problem is that it only works 1 time. It outputs something like: This_i7s_A_String

Since I'm defying rndm inside the while loop I would guess that on every loop its value would change but that doesn't seem to be the case. It's unlikely that the random value assigned to rndm just happened to be the same 15 times :/

So... Any ideas on what's going on?




Single random number generation [on hold]

I am in my first couple months of learning python in college. I am trying to figure out how to generate a random number I click and show it on the screen in pygame, however because my game is in a while true sort of loop, it generates a new number every frame, and I would like it to choose one number each time. I have gotten it to choose one number and print it each time, but the problem is that it is the same number.




Generating n new datasets by randomly samplng existing data, and then applying a function to new datasets

I'm very grateful in advance for any advice.

For a paper I'm writing I have subsetted a larger dataset into 3 groups, because I thought the strength of correlations between 2 variables in those groups would differ (they did). I want to see if subsetting my data into random groupings would also significantly affect the strength of correlations (i.e. whether what I'm seeing is just an effect of subsetting, or if those groupings are actually significant).

To this end, I am trying to generate n new data frames by randomly sampling 150 rows from an existing dataset, and then want to calculate correlation coefficients for two variables in those n new data frames, saving the correlation coefficient and significance in a new file.

But...HOW?

I can do it manually, e.g. with dplyr, something like

newdata <- sample_n(Random_sample_data, 150)
output <- cor.test(newdata$x, newdata$y, method="kendall")

I'd obviously like to not type this out 1000 or 100000 times, and have been trying things with loops and lapply (see below) but they've not worked (undoubtedly due to something really obvious that I'm missing!!!).

Here I have tried to assign each row to a different group, with 10 groups in total, and then to do correlations between x and y by those groups:

Random_sample_data<-select(Range_corrected, x, y)
cat <- sample(1:10, 1229, replace=TRUE)
Random_sample_cats<-cbind(Random_sample_data,cat)

correlation <- function(c) {
  c <- cor.test(x,y, method="kendall")
  return(c)
}
b<- daply(Random_sample_cats, .(cat), correlation)

Error message:

Error in cor.test(x, y, method = "kendall") : 
      object 'x' not found



VBA random function problem - not working when closing workfile

I made a code generator with random function, but it generates the same codes when closing and opening the macro again. When running macro more times on 1 opening, it works fine but when I close the file with macro, open again, It generates the same codes. It is something like this - example:

  1. open excel file, generated: 1111, generated: 2222, close
  2. open file with macro, generated: 1111, generated 2222, generated 3333 close worksheet
  3. Open file, generated: 1111

      For i = 15 To 38
      ws2.Cells(i, 2) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 3) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 4) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 5) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 6) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 7) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 8) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 9) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 10) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 11) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 12) = Int((9999 - 0 + 1) * Rnd + 0)
      ws2.Cells(i, 13) = Int((9999 - 0 + 1) * Rnd + 0)
    
      Next i
    

Expected result (example):

  1. open file, generate: 1111, generate: 2222, close
  2. open file with macor, generated: 3333, generated 4444, generated 5555 close worksheet
  3. Open file, generated: 6666



Select random sample of one column based on groupby of 3 columns of a R dataframe [on hold]

I need to select a random sample of one column of a R dataframe by grouping by on three other columns. This is some what similar to what has been discussed below:

Groupby and Sample pandas

and I do not know how to replicate in the Python code in R.

My bad, I haven't posted what i tried so far. I used data.table package.

library(data.table)
sample_df <- df[, .SD[sample(x = .N, size = 50)], by = id]

However, I am not sure how to sample one column by using 3 other columns as groupby




In Java make random 3byte String [duplicate]

This question already has an answer here:

How do I generate a random 3byte string in Java?

Below is the code I've written in python:

import random

def random_unicode(length):
    random_unicodes = [chr(random.randrange(0x999D)) for _ in range(0, length)] 
    return u"".join(random_unicodes)

I am trying to implement this code in Java.




C++ RNG (Random Number Generation) Optimization

First of all I'd like to clarify I'm quite new to C++, and I've put together some code that outputs a random set of 16 digits. For that I used a tutorial online and the comparatively higher batch experience (this idea came from a batch file that was running quite slowly and I wanted to migrate both batch files to c++ to compare how they ran, as there were two similar projects, one of them for random number generation, which is this one, and another for random string generation). As I'm not that great with c++, I'd like some help optimizing the code, as I feel it can be done in fewer lines Now that you've got the background, my code is as follows

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    std::srand(std::time(0));
    int random0 = 0;
    int random1 = 0;
    int random2 = 0;
    int random3 = 0;
    int random4 = 0;
    int random5 = 0;
    int random6 = 0;
    int random7 = 0;
    int random8 = 0;
    int random9 = 0;
    int random10 = 0;
    int random11 = 0;
    int random12 = 0;
    int random13 = 0;
    int random14 = 0;
    int random15 = 0;


    for (int i = 0; i < i+1; ++i)
    {
        random0 = std::rand() % 9;
        random1 = std::rand() % 9;
        random2 = std::rand() % 9;
        random3 = std::rand() % 9;
        random4 = std::rand() % 9;
        random5 = std::rand() % 9;
        random6 = std::rand() % 9;
        random7 = std::rand() % 9;
        random8 = std::rand() % 9;
        random9 = std::rand() % 9;
        random10 = std::rand() % 9;
        random11 = std::rand() % 9;
        random12 = std::rand() % 9;
        random13 = std::rand() % 9;
        random14 = std::rand() % 9;
        random15 = std::rand() % 9;

        std::cout << random0 << random1 << random2 << random3 << random4 << random5 << random6 << random7 << random8 << random9 << random10 << random11 << random12 << random13 << random14 << random15 << std::endl;
    }
    return 0;
}

Thanks in advance for any help, and I'm sorry if I trigger any experienced c++ coder's OCD.




dimanche 27 octobre 2019

how to generate 3 words using random class

I am given a multi-array (based on page, paragraph, and line number chosen randomly) that tells a story. I need to generate a password containing 3 words taken randomly from the array. Rules have to be given to creating the password (eg: it must be 10 characters long, no repetition of the same word);

This is for Java. I made sure I was using the random class to make sure my 3 words are selected randomly from the array given. I've declared the variables for page, paragraph and line number so that it can pick any single string from array. Then I used split() to separate each word in the random string.

I created an if-else statement for a rule I made to creating a password. If a rule(s) is not followed, the program must always go back to the step where the page, paragraph and line number are chosen randomly, and I have to use random class to generate random numbers using nextInt() method.

 import java.util.Random;

 public class passGen {

   public static void main(String[] args) {

   Random r=new Random();

int pageNum = r.nextInt(story.length);
    int paraNum = r.nextInt(story.length);
    int lineNum = r.nextInt(story.length);

    System.out.print("Password = ");

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

        String sentence = story[pageNum][paraNum][lineNum]; // story is the array given
        String[] string = sentence.split(" ");  
        int index = new Random().nextInt(string.length);            
        String randomWord = string[index];

        if (randomWord.equals("a") || randomWord.contains("\n")) {
        }
        else 
            System.out.print(randomWord);

    }
      }
    }

Let's say the random generator picks a random sentence from the array: story[0][1][5] gives "The boy is riding on a bicycle\n". Using split() and then randomly selecting the word based on its index, it picks the random word "bicycle\n". I made a rule that if it picks a word with new line ('\n') it must go back to the step where it generates random numbers again and gives me a new array and finds me a new random word until it finds me a word that doesn't have \n. For example, let's say story[0][1][6] is "He is having fun."

I expected the output to print one password with 3 random words combined all the time.

         password =  boyfun.riding   // fun. is considered as one word with the period.

but there were cases that when it failed, it only prints out words that passed the restriction ('\n'). Sometimes it would print 1 word, or 2 words, or it will give an error when I run the program.

password = ridingfun

password = boy 

Password = Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Assign3Q1.main(passGen.java:123)

// line 123 happens is the String sentence = story[pageNum][paraNum][lineNum];



How can I reverse the output of my array when given an input of random numbers generated by the computer?

The issue I am currently having is that my code creates and prints 40 numbers into an array. When attempting to print this set of code backwards it will only print the final number in the regular/normal array when I need it to print the entire first array in reverse order. Thanks for the help. I am using c++.

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

int main(void) 
{ 
    int i;
    int lower = 0, upper = 100; //Random number between 1 and 100 is generated
    int rand_num; 
    int num[40];

    srand(time(0)); 

    printf("Your array is shown:\n");
    for(i = 0; i < 40; i++)
    {
        rand_num = (rand() % (upper - lower + 1)) + lower;
        num[rand_num] = rand_num;

        printf("%d ",num[rand_num]);

    }


    printf("\nYour array backwards is:\n");
    for(i = 39; i >= 0; i--)
    {
        printf("%d ", num[rand_num]);

    }


    return 0; 
} 



Tham khao tieu chi mua va su dung giuong tang hoa phat dung cach

Tham khao mau giuong tang, tham khao thong qua bai viet Các mẫu Giuong tang Hoa Phat hiện nay đã quá quen thuộc với người tiêu dùng, nó không chỉ tiện dụng cho trường học, nối trú, hay công nhân mà hiện nay giuong tang hoa phat có thể sử dụng ở nhiều môi trường khác nhau, tùy vào nhu cầu sử dụng. Thiết kế đơn giản, tiện dụng, với mức giá thành hợp lý có làm bạn thực sự hài lòng. Nội thất Hòa Phát luôn mang đến những tiện ích tốt nhất dành cho khách hàng. https://hoaphat.net/tieu-chi-lua-chon-giuong-tang-hoa-phat-hop-ly.html

MỌI CHI TIẾT XIN LIÊN HỆ : Số điện thoại : 024.3550 5888

Mobile : 0932.317.198 - 0967.317.555 - 0934.534.777

Fax : 024.37 37 30 88

Địa chỉ : Tầng 5, tòa nhà Ngôi Sao, ô 15, đường Nguyễn Cảnh Dị, KĐT Đại Kim, Hoàng Mai, HN

Email: hoaphat185@gmail.com

Website : https://hoaphat.net/




numpy.random.uniform applied to index of array produces integers

I want to populate an array with uniformly chosen floats, but when I try to do that I get integers instead:

#Initial parameters
P = np.full(1, 0)
lower_bounds = np.full(1, 0)
upper_bounds = np.full(1, np.pi)

def candidate(P):
    for k in range(len(P)):
        P[k] = np.random.uniform(lower_bounds[k],upper_bounds[k])
    return P

print(candidate(P))

This prints [0], [1], [2], or [3], whereas

print(np.random.uniform(lower_bounds[0],upper_bounds[0]))

prints a float, as desired. I'm not sure why this happens.




selenium random user agent realistic combination? [duplicate]

This question already has an answer here:

how can i use realistic user agents random, i wanna set a list of user agents which python can use random?

ua = UserAgent(cache=False, use_cache_server=False)
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')
browser = webdriver.Chrome(chrome_options=options)

my problem with this python make random user agents but with unrealistic system combinations

i use python on windows 64 bit

thats one of these useragent my script make.

Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36




How can I generate random pics with python?

I'm trying to solve this problem, I want to draw an image in random positions, so I've declared a global variable that at the beggining is assigned at a negative value (count = -randint). Then in tick function (which is called by main() every 30ms) I increment the count variable and when it's higher than a established value I create the object Hole (that is the pic that I want to draw) and I reset count to the value count = -randint. The problem I've faced is that the different pics are not generated randomly but they are placed in a specific series that is repeated each time they are generated. I put in the description also the module I've used to run the graphycs. Thanks for your attention. https://github.com/tomamic/fondinfo/tree/master/examples Is called g2d.py Here is the code:

#Title: Rovers and Backgrounds
#Date 07/10/19
#Autor: Giovanni Sgobazzi
#Identification number: 305356

import g2d
from random import randint
from actor import Actor, Arena
sprites = g2d.load_image("moon-patrol.png")
bckd = g2d.load_image("moon-patrol-bg.png")
arena = Arena((1000, 700))
ARENA_W, ARENA_H = arena.size()
count = -randint(200,500)

class Background():

    def __init__(self, arena):
        self._arena_w, self._arena_h = arena.size()
        self._w, self._h = 512, 150
        self._w1, self._h1 = 512, 125
        self._dx = 0
        self._x = 0
        self._dx1 = 0
        self._x1 = 0
        self._dx2 = 0
        self._x2 = 0
        self._ground = self._arena_h * 2/9

    def move(self):
        self._x = self._dx % self._arena_w  ## First Background
        g2d.draw_image_clip(bckd,(0, 100, self._w, self._h),(self._x - self._arena_w, 0, self._arena_w, self._arena_h))
        if self._x < self._arena_w:
            g2d.draw_image_clip(bckd, (0, 100, self._w, self._h), (self._x, 0, self._arena_w, self._arena_h))
        self._dx -= 1

        self._x1 = self._dx1 % self._arena_w   ## Second Background
        g2d.draw_image_clip(bckd,(0, 385, self._w1, self._h1),(self._x1 - self._arena_w, self._arena_h * 5/9 - 40, self._arena_w, self._arena_h * 5/9))             
        if self._x1 < self._arena_w:
            g2d.draw_image_clip(bckd,(0, 385, self._w1, self._h1), (self._x1, self._arena_h * 5/9 - 40, self._arena_w, self._arena_h * 5/9))                                                       
        self._dx1 -= 3

        self._x2 = self._dx2 % self._arena_w    ## Third Background
        g2d.draw_image_clip(bckd,(0, 513, self._w1, self._h1),(self._x2 - self._arena_w, self._arena_h * 7/9, self._arena_w, self._ground))                                                      
        if self._x2 < self._arena_w:
            g2d.draw_image_clip(bckd, (0, 513, self._w1, self._h1), (self._x2, self._arena_h * 7/9, self._arena_w, self._ground))
        self._dx2 -= 5

class Rover(Actor):

    def __init__(self, arena, pos):
        self._arena = arena
        self._dim = 3/2
        self._x , self._y = pos
        self._speed = 10
        self._w, self._h = 35 * self._dim, 25 * self._dim
        self._dx, self._dy = 0, 0
        self._arena_w, self._arena_h = arena.size()
        self._ground = self._arena_h - self._y
        self._arena.add(self)

    def move(self):
        self._y += self._dy
        if self._y < 0:
            self._y = 0
        elif self._y > self._arena_h - self._ground - self._h:
            self._y = self._arena_h - self._ground - self._h
        else:
            self._dy += 0.4

        self._x += self._dx
        if self._x < 0:
            self._x = 0
        elif self._x > self._arena_w - self._w:
            self._x = self._arena_w - self._w

    def go_up(self):
        if self._y >= self._arena_h - self._ground - self._h :
            self._dy = -self._speed

    def go_right(self):
        self._dx = self._speed

    def go_left(self):
        self._dx = -self._speed

    def stay(self):
        self._dy, self._dx = 0, 0

    def symbol(self):
        return 210, 155, 35, 25

    def position(self):
        return self._x, self._y, self._w, self._h

    def collide(self,other):
        if isinstance(other, Hole):
            self._arena.remove(self)


class Hole(Actor):
    def __init__(self, arena):
        self._arena = arena
        self._arena_w, self._arena_h = arena.size()
        self._w, self._h = 30, 30
        self._dx = 0
        self._x = 0
        self._ground = self._arena_h * 2/9
        self._arena.add(self)

    def move(self):
        self._x = self._dx % self._arena_w    
        self._dx -= 5
        if self._x < 0:
            self._arena.remove(self)

    def symbol(self):
        return 130, 165, self._w, self._h

    def position(self):
        return self._x, self._arena_h - self._ground - 1, self._w, self._h

    def collide(self,other):
        pass     

b = Background(arena)
r = Rover(arena, (150, ARENA_H * 7/9 + 3))

def tick():
    global count
    count += 1
    g2d.clear_canvas()    
    arena.move_all()
    b.move()    
    if count >= 100:
        Hole(arena)
        count = -randint(200,500)

    if g2d.key_pressed("Spacebar"):
        r.go_up()

    if g2d.key_pressed("ArrowRight"):
        r.go_right()

    if g2d.key_pressed("ArrowLeft"):
        r.go_left()

    if (g2d.key_released("ArrowRight") or g2d.key_released("ArrowLeft")):
        r.stay()

    for a in arena.actors():
        if isinstance(a,Hole):
            g2d.draw_image_clip(sprites, a.symbol(), a.position())

        if isinstance(a,Rover):
            g2d.draw_image_clip(sprites, a.symbol(), a.position())


def main():    
    g2d.init_canvas(arena.size())
    g2d.main_loop(tick)
main()



Problems generating random float with values inferior than 1

I need a function for generating floats with values inferior than 1, I have this code:

public float randFloat(float min, float max) {
    float randomNum = rand.nextFloat() * ((max - min) + 1) + min;
    return randomNum;
}

*I'm adding 1 because this function is based in randomInt() and in that function, I add 1 because nextInt is normally exclusive of the top value, so add 1 to make it inclusive.

I call that function with very small values, for example:

minRadius = sh * 0.0001f;
maxRadius = sh * 0.0005f;
radius = Util.getInstance().randFloat(minRadius, maxRadius);

In that case sh is 1080, so:

minRadius = 0.108f;
maxRadius = 0.54f;

Then, that function should return values between 0.108 and 0.54, but instead of that, sometimes is returning values higher than 0.54f, for example, 1.1f, 1.4f, etc...

What is wrong in the function?




Why I keep on get the same result on this randomized game?

I am on my first week learning CS and coding. I tried to make a simple randomized fight betweet A and B. It is supposed to run until either one reach life=0 and the one who dies will be announced through console.log

I have tried to play with all of the variables, but still get the same result.

var lifeA = 500    
var lifeB = 250
var powerA = 2
var powerB = 4
var increasepowerA = Math.floor(Math.random() * 5)
var increasepowerB = Math.floor(Math.random() * 10)
var chanceattack = 0.5
var x = 0


function getx(){
  const z = Math.random()
  if (z <= chanceattack){
     x = 1
  }else{x = 0}
}

getx()

function execute(){
  if(x = 1){attackA()
  }else{attackB()}
}


function attackB(){
  lifeA -= powerB;
  powerB += increasepowerB;
  chanceattack += 0.075;
  if (lifeA <= 0){
    console.log("A has dead")
  }else{getx(); execute()}
}

function attackA(){
  lifeB -= powerA;
  powerA += increasepowerA;
  chanceattack -= 0.075;
  if (lifeB <= 0){
    console.log("B has dead")

  }else{getx(); execute()}
}

execute()

Since this is a randomized game, I expect that everytime I refresh my live server I would get different result either "A has died" or "B has died". However, I constantly get "B has died"




samedi 26 octobre 2019

Matplotlib heatmap is really small

I have created a heatmap that will display the correlation between all of the columns within a dataset of random numbers. The heatmap is created just fine, but the heatmap is very small, mostly in the vertical direction. I attached an image of the heatmap to this post. The dataset is a pandas dataframe from a csv file. The code is shown below:

def colCorrelation():
    xData = []
    yData = []

    fig, ax = plt.subplots(figsize=(5,5)) 
    # calculates the correlation between all columns and all other columns
    for i in range(0,100):
        for e in range(0,100):
            dataFlow = dict(zip([(i,e+1)], 
               [np.corrcoef(dfT[i],dfT[e+1])[0,1]]))
            if list(dataFlow.values())[0] < .9:
                xData.append(list(dataFlow.keys())[0][0])
                yData.append(list(dataFlow.values())[0])

    ## tuple of the two columns being correlated and their correlation
    ## in the dictionary as key value pairs data structure.
    ## Ex: {(19, 17): -0.015262993060948592}

    ## Plot heatmap
    heatmap, xedges, yedges = np.histogram2d(xData,yData,bins=(50))
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

    plt.clf()
    plt.title('Random Data heatmap')
    plt.ylabel('y')
    plt.xlabel('x')
    plt.imshow(heatmap,extent=extent)
    plt.show()

colCorrelation()

The heatmap created by the code above




How can I fix my random generators used to generate factors and messages using function?

I have to write a program to simulate the Education System by dividing the program into functions (requirements are below). I am trying to use rand() to generate random numbers from 0 to 9 and also to generate random messages to display but both are not working. There might be a problem in my switch statement or function definition and prototype or use of rand() and srand(). I can't figure it out please help.

These are the instructions I was given by my instructor:

Step 1: Computers are playing an increasing role in education. Write a program that will help an elementary school student learn multiplication. Use a Random number function to produce two positive one-digit integers. The program should then prompt the user with a question, such as

How much is 6 times 7?

The student then inputs the answer. Next, the program checks the student’s answer. If it is correct, display the message "Very good!" and ask another multiplication question. If the answer is wrong, display the message "No. Please try again." and let the student try the same question repeatedly until the student finally gets it right.

A separate function should be used to generate each new question. This function should be called once when the application begins execution and each time the user answers the question correctly.

Step 2: Modify the program to vary the comments that are displayed for each correct answer and each incorrect answer.

The response to a correct answer should be chosen from: Very good! Excellent! Nice work! Keep up the good work!

The response to an incorrect answer should be chosen from: No. Please try again. Wrong. Try once more. Don't give up! No. Keep trying.

Use random-number generation to choose a number from 1 to 4 that will be used to select an appropriate response to each answer. Use a switch statement to issue the responses.

Step 3: Modify the program to count the number of correct and incorrect responses typed by the student. After the student types 10 answers, your program should calculate the percentage of correct responses.

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

//Function declaration
void getInput(int& userAnswer);
int randomFactors(int a, int b, int randomNumbmer1, int randomNumber2);
int multiply(int correctAnswer, int randomNumber1, int randomNumber2);
int randomRight(int right1, int right2, int randomMessege);
int randomWrong(int wrong1, int wrong2, int randomMessege);

// Main Program
int main()
{
    //Variable declaration
    int correctAnswer = 0,
        userAnswer = 0;
    int randomMessege = 0;
    int right1 = 1,
        right2 = 4;
    int wrong1 = 1,
        wrong2 = 4;
    int cCounter = 0,
        iCounter = 0;

    //While loop counts the number of times user gives an answer
    int count = 0; //control variable for while loop 
    while (count < 10)
    {
        //do while loop for the program to exit when user enters "-1" 
        do
        {
            int a = 0,
                b = 9,
                randomNumber1 = 0,
                randomNumber2 = 0;
            //Function call
            randomFactors(a, b, randomNumber1, randomNumber2);
            multiply(correctAnswer, randomNumber1, randomNumber2);
            getInput(userAnswer);

            /*if else to check if the answer is correct and
            to give another chance if the user is wrong*/
            //icounter and cCounter keep track of the number of correct and incorrect answers

            while(userAnswer != correctAnswer)
            {
                randomWrong(wrong1, wrong2, randomMessege);
                getInput(userAnswer);
                iCounter = iCounter + 1;
            }
            randomRight(right1, right2, randomMessege);
            cCounter = cCounter + 1;
        } while (userAnswer > -1); //end of do while loop

        if (count == 10)
        {
            int percentage = (cCounter / 10) * 100;
            if (percentage >= 75)
            {
                cout << "You have scored " << percentage << "%. Congratulations, you are ready to go to the next level!";
            }
            else
            {
                cout << "You have scored " << percentage << "%. Please ask your instructor for extra help.";
            }
            count, iCounter, cCounter = 0;
        }
        count++;
    }
}

//Function defination
int randomFactors(int a, int b, int randomNumber1, int randomNumber2)
{
    srand(time(0));
    randomNumber1 = rand() % (b + 1) + a;
    randomNumber2 = rand() % (b + 1) + a;
    cout << "How much is " << randomNumber1 << " times " << randomNumber2 << "?\n";
    return randomNumber1, randomNumber2;
}
void getInput(int& userAnswer)
{
    cout << "Enter your answer (-1 to exit):\n";
    cin >> userAnswer;
}
int multiply(int correctAnswer, int randomNumber1, int randomNumber2)
{
    correctAnswer = randomNumber1 * randomNumber2;
    return correctAnswer;
}
int randomRight(int right1, int right2, int randomMessege)
{
    srand(time(0));
    randomMessege = (rand() % (right2 + 1) + right1);
    switch (randomMessege)
    {
    case 1: cout << "Very good!";

    case 2: cout << "Excellent!";

    case 3: cout << "Nice work!";

    case 4: cout << "Keep up the good work!";
    }
    cout << endl << endl;
    return randomMessege;
}
int randomWrong(int wrong1, int wrong2, int randomMessege)
{
    srand(time(0));
    randomMessege = (rand() % (wrong2 + 1) + wrong1);
    switch (randomMessege)
    {
        case 1: cout << "No. Please try again.";

        case 2: cout << "Wrong. Try once more.";

        case 3: cout << "Don't give up!";

        case 4: cout << "No. Keep trying.";
    }
    cout << endl << endl;
    return randomMessege;
}```[![Second picture is of the output I am getting and first is the expected output.[![\]\[1\]][1]][1]][2]


  [1]: https://i.stack.imgur.com/nItE5.png
  [2]: https://i.stack.imgur.com/r6Cv0.png



How to write a program using Numpy to generate and print 5 random number between 0 & 1

How to write a program using Numpy to generate and print 5 random number between 0 and 1




A big store wants you to develop a java application to help drawing winners for three prizes: prize1= $5000, prize2=$2000 and prize3=$1000

A big store wants you to develop a java application to help drawing winners for three prizes: prize1= $5000, prize2=$2000 and prize3=$1000. The winner of each prize should be randomly selected from an array that contains all customer names of that store. A winner cannot get more than one prize, which means if s/he was already selected for a prize, and then s/he was chosen randomly for another one, your program should consider (i.e., draw) another customer for that prize. Write a java application named Winners.java that contains a main method to test another static method named drawWinners that accepts an array of Strings and returns an array containing three randomly selected winners from the received array. In main you should print the winners returned by the method. Use suitable messages in your output. For example, if the following array was passed to drawWinners: String[ ] names = {“Ali AAA”, “Sara SSS”, “Yazan YYY”, “Mahmoud MMM”, “Noor NNN”, “Jana JJJ”, “Safaa SSS”, “Dana DDD”, “Omar OOO”, “Saad SSS”, “Ibraheem III”}; Your output after calling drawWinners(names) should look like: Winner of prize 1: Jana JJJ Winner of prize 2: Omar OOO Winner of prize 3: Dana DDD




Random Number Generation within a range

I am trying to print a random number between 80 and 100. However when I print out this number I am getting numbers over 100?

Random num = new Random();
int percent = 80 + num.nextInt(100);
System.out.println(percent);



vendredi 25 octobre 2019

numpy list of random subsets of specified size

I want to efficiently (time and space) compute a list of random subset of an array, where the ordering in the subsets is random.

For example the array [1,2,3,4,5] with some parameters k=3 and n=5 should produce a matrix

[[4,3,1],
 [1,2,5],
 [2,4,5],
 [3,2,5],
 [2,3,1]]

i.e. we get n=5 lists with k=3 random unique elements from the array.

I would like this to be as fast as possible, without creating a gigantic lookup table of possible combinations, since both time and space are of the essence.

I tried to do this with numpy.random.choice(array,n*k).reshape((n,k)) which almost does, what i want, except for the uniqueness part. I settled on the following

subsets = numpy.zeros(n).reshape((n,1))
subsets = numpy.apply_along_axis(lambda x : numpy.random.choice(array,k,replace=False),1,subsets)

However since this is not purely numpy, this is slow. Too slow for my application. Is there some way to improve on the runtime, and maybe achieve this with pure numpy commands?

Any help would be appreciated. Thanks.




how to Pick random GameObject in Unity

I'm making an endless runner game, and I have 4 types of terrain I want to auto-generate. the auto-generation works, but I want to select a random terrain but I can't figure out how. I have tried this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformManager: MonoBehaviour
{
    [SerializeField]
    private GameObject[] _platformPrefabs;
    [SerializeField]
    private int _zedOffset;


    // Start is called before the first frame update
    void Start()
    {
        randomTerrain();
    }

    public void RecyclePlatform(GameObject Platform)
    {
        Platform.transform.position = new Vector3(0, 0, _zedOffset);
        _zedOffset += 12;

    }

    public void randomTerrain()
    {
        for (int i = 0; i < _platformPrefabs.Length; i++)
        {
            Instantiate(_platformPrefabs[Random.Range(0, 3)], new Vector3(0, 0, i * 12), Quaternion.Euler(0, 90, 0));
            _zedOffset += 12;
        }
    }

}

but it only selects the first game object every time except the first initiation. how can I make it select randomly?

Inspector view of script




c++ Define a set of probability distributions in loop

I would like to create a set of normal distribution with different means. like this:

#include <random>
using namespace std;
std::default_random_engine generator;
std::normal_distribution<double> normal_1(0.0,std_1);
std::normal_distribution<double> normal_2(0.0,std_2);
// and so on until:
std::normal_distribution<double> normal_N(0.0,std_N);

I need to be able to change the total number of distributions so a loop will work better, like this:

for (int i = 1; i<=N; i++){
std::normal_distribution<double> normal_i(0.0,std_i);
}

PD: I'm new to C++, so maybe this is a very basic question.




A method for long datatype similar to nextInt(int bound) of Java Random Class

I need a method similar to nextInt(int bound) of Java Random Class for long data type. Here is my implementation:

   static long randomLong(Random rNumber, long bound)
   {
      long z = rNumber.nextLong();

      return (z % bound);
   }

Where rNumber is initialized from the calling method as,

Random rNumber = new Random();

My question is, does this implementation ensures a pseudorandom, uniformly distributed long value between 0 (inclusive) and the bound (exclusive) ?




Trouble with random initialization

I'm currently working on a java project for a class in uni. One of the methods I must complete asks me to fill an Array with random numbers, but the array type is from a class called Weapon. I can't convert my type to integers so the compiler says that Weapons cannot be converted to integers.

I've tried searching for a solution, even writing a method called nextWeapon(), but as I just started learning programming, it seems to be a bit diffuclt.

    int W;
    Weapon[] weapons = new Weapon[W];

    public Weapon[] createRandomWeapon(){

    Random rand = new Random();
    for(int i = 0; i < weapons.length; i++){
        weapons[i] = rand.nextInt();
    }
    return weapons;
}



Matlab Homework

I am struggling with my Matlab homework: We

Write a script to do the following: 1.Generate a matrix called grades of size 8 x 25 that contains random numbers of type double in the range of 1 to 6. 2.Calculate the mean of matrix rows (-> mrow), the mean of matrix columns (-> mcol), and the overall mean (-> mall) of the matrix grades. 3.Copy the matrix grades to a new variable, in which you replace the elements in the 5th row and 20th to 23rd column with NaN. Compute the overall mean (-> mall_2) of this matrix again, i.e., the mean of the remaining values.

I am done with task 2-5, however, task 1 is not correct. I am not sure what I am doing wrong. I assume that it has something to do with the type of number (double), but I was unable to convert it.

% Generate matrix 'grades' with random numbers in the range 1 to 6

a = 1;
b = 6;
grades = (b-a).*rand(8,25) + a;

% calculate mean values 'mrow', 'mcol', 'mall'
mrow = mean(grades,2)
mcol = mean(grades,1)
mall = mean(grades(:))
% Replace elements with NaN
grades(5,20:23) = NaN
%Calculate mean of elements omitting NaN
mall_2 = mean(grades(:),'omitnan')

I would be thankful for any solution here!




What is the range that the random function can return?

int nextInt(int n) {
    return rand() / static_cast<double>(RAND_MAX) * n;
}

I find someone write the above function(nextInt) and he said nextInt returns a random int in [0, n - 1], but I think nextInt returns a random int in [0, n]. I wonder who is right and why?




Unable to create multiple random numbers in c++

I am creating a game where a player encounters different objects which increase/decrease the health.

I have an array with the obj name and effect which works perfectly

The problem occurs in this loop

while(gHealth >= 0 && gHealth <= 500)
        {
            srand(time(0));

            int hitBy = (rand()%arrayL);  // arrayL = number objects in array

            cout << gName << " encountered " << objName [hitBy] << endl;
            gHealth += objPower[hitBy];
            cout << gName << "has a health of " << gHealth << endl;
        } 

Every time the player encounters same object. (what i mean is if the player encountered apple the first time then for the entire game he encounters apples)

How do i make random output each time it enters loop




jeudi 24 octobre 2019

Inconsistent results with random rolls and some math

I'm working on making a program to roll 4 6 sided dice and do some simple math and logic with them. I was running a very rough draft of the program and started to notice that the number of rolls would be inconsistent. In particular I would sometimes wont get the smallest value or get two

If looked around for a solution online to no avail. I even copied the code from other examples on how to find the smallest value

public class test {
private static int dice(int s){
    int num = 0;
    Random random = new Random();
    num = random.nextInt(s);
    num = num + 1;
    return num;
}

public static void main(String[] args)
{
    List<Integer> rolls = new ArrayList<Integer>();
    for (int i = 0; i!=4 ; i++){
        rolls.add(dice(6));
    }
    for (Integer roll : rolls) {
        System.out.println(roll);
    }
    int min = rolls.get(0);
    int index = 0;
    for(int x = 0; x<rolls.size(); x++){
        if(rolls.get(x) < min){
           min=rolls.get(x);
           index = x;
           System.out.println("Smallest: " + min);
        }
    }

    int sum = 0;
    for (int x : rolls){
        sum += x;
    }
    System.out.println("Sum:" + sum);
}
}

This should generate 4 rolls of 6 sided dice. Then it should find the smallest value print that, then calculate the sum and print it




Get the percentage of bar from bar chart Zipf distribution

I have a dataset which has 20 columns and 10.000 rows. My plan is to replace some data in my dataset to NaN. I have a task of observing the impact of missing values on my dataset.

My plan is using Zipf distribution to generate the percentage of missing of each column then replace some values to NaN based on those percentages.

For instance, here my code:

import matplotlib.pyplot as plt
from scipy import special

import numpy as np
a = 1.01 # parameter
s = np.random.zipf(a, 200000)
count, bins, ignored = plt.hist(s[s<20], 20, density=True)

plt.show()

The bar chart looks like: enter image description here

Is that possible to get the percentage of bar, so I can replace some values in each column based on the percentage of the bar? For instance, first column has 80 % missing, second columns 40 %, third 25%, etc.




How do I take UNIQUE random choice from two lists

I have two lists that defines a card

values  =  ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']
marks   =  ['spade', 'hearts', 'diamond', 'club']

I want to have 12 unique cards, so my output should look like

('9', 'diamond')
('K', 'hearts')
('Q', 'hearts')
('7', 'spade')
('A', 'diamond')
('3', 'diamond')
('Q', 'diamond')
('3', 'hearts')
('7', 'hearts')
('2', 'diamond')
('2', 'hearts')
('5', 'spade')

I have used random choice to get this far, my code is here

count = 0
while count != 12:
    value = random.choice(values)
    mark = random.choice(marks)
    card = Card(value, mark) 
    # I have a class named Card, generate() returns a tuple of mark and value for card
    print(card.generate())
    count += 1

But it does not provide me unique values. Please let me know or through me a resource to learn how to get unique value by random choice from two lists.