mercredi 31 mars 2021

How to get a random permutation of integers inside range without permuting the whole array in python?

Say I have a very long array, and I want to return a random permutation of a subset of that array... How do I do that without having to permute the whole array?

The way I can think of is

import numpy
N = 10000000 # total number of elements
n = 20 # number of elements that I am interested in getting from the permutation
x = numpy.random.permutation(numpy.arange(N))[:n] # this permutes the whole array

Basically, I need to select n unique integers greater than or equal to 0 and less than N...

I know it is easy to do that explicitly, but is there a numpy way or a function in any module in python that works like randperm(N,n) in MATLAB?

So far, I've only found python examples that are variations of what I described up here.




How to select a good sample size of nodes from a graph

I have a network that has a node attribute labeled as 0 or 1. I want to find how the distance between nodes with the same attribute differs from the distance between nodes with a different attributes. As it is computationally difficult to find the distance between all combinations of nodes, I want to select a sample size of nodes. How will I select a sample size of nodes? I am working on python and networkx




how to Generate a random position of a rectangle but always inside the canvas in javascript?

I have to generate a rectangle inside a canvas of 600 px * 600 px, every time I reload the page it should appear in a different position, but it should always appear in locations that are multiples of 25, for example, it will never appear in (120,130) or (480,15). I had this but it's not working

function randomPosition(min, max) {
  return Math.round(Math.random() * (max - min + 1)) + min;
}

I also used this but sometimes the rectangle doesn't appear inside the canvas

function randomPosition(min, max) {
  return Math.round(Math.random()* 10) * 25;;
}



Take random array in a 2D named Array in Javascript

I'd like to take a random array from a 2D named array but all solution I tried didn't work maybe someone could help

var sites = [];

sites['apple'] = [
'green'
,
'red'
,
'blue'
];

sites['orange'] = [
'yellow'
];

There is more and of course not these names and the number is not fix and I'd like to take one random array. (Not item !)

Is it possible ?




create new object from enum number c#

I have made a enum type (MonsterTypes) with 4 types (Monster1, Monster2 , Monster3, Monster4) which should be possible to extend with more monsters. I want to chose a random type, and create an instances of a random monster, and rather than having if states stating if (System.Random.Next(4) = 1) Monster1.CreateMonster(Image)} which works. In order to automatically extend the random from 4-5 when a new enum is added.
var squadrons = MonsterTypes.GetNames( typeof( Squadron.SquadronType)).Length; in order to get the number of enums.
I encounter a problem when i try to initiate CreateMonster() without an if statement. If i use: ((MonsterTypes) System.Random.Next(4)).CreateMonster(Image) i get the error: "'MonstersTypes' does not contain a definition for 'CreateMonster' and no accessible extension method 'CreateMonster' accepting a first argument of type 'MonsterTypes' could be found (are you missing a using directive or assembly refrence?)

public static  class CreateNextMonster {
    public static IMonster ActiveMonster {get;private set;}
    private static System.Random rand = new System.Random();
    public static void CreateNewMonster (Img MonsterPicture) {
        var monstersTotal = Squadron.SquadronType.GetNames(typeof(Squadron.SquadronType)).Length;
        int nextMonster= rand.Next(monstersTotal);
        ((Monsters) nextMonster).CreateMonster();
    }
}



Loop random amount of times [duplicate]

I've been trying to create a simple program that will generate random numbers a random amount of times within specified range.

I've been able to create the random numbers in the specified range, however not sure how to set the amount of numbers generated to be random within a specified range.

The loop I'm using is

for (int i = 0; i < 10; i++)

which I understand will only make 10 random numbers be generated. Would really appreciate if anyone could show me or explain how I would use random to make the amount of numbers generated for example be between 5 and 20.

Thank you for your time and help in advance




Why can't I seem to mix argv and randint?

So I had my guessing game working and It wouldn't break regardless of input. i understand I can use the int function on the input but if the user decides to enter anything but an integer you get a runtime error so I did it different it was working until I decided I wanted to allow the user to add CLI arguments to define the value range for the integer generation it looks as below but it doesn't work...

from sys import argv
import random
lower, upper = argv
lower = int(lower)
upper = int(upper)
secret_number = random.randint(lower, upper)

Output:

Traceback (most recent call last):
  File "guess.py", line 3, in <module>
    lower, upper = argv
ValueError: too many values to unpack (expected 2)

I ran it with python guess.py 1 100

this is the working version

import random
secret_number = random.randint(1,100) #assigns a random integer to secret_number
count = int(0) #starts the guess counter at 0
#print(f"the secret number is: {secret_number}")
print("Try and guess the number between 1-100")
number = input("please enter your guess: ")
while number != secret_number:
    try:
        count += 1  #same as count = count + 1
        number = int(number)
    except:
        print(f"you entered: {number}")
        number = input("please enter an integer only!: ")
    else:
        if number < secret_number:
            print(f"you entered: {number}")
            number = input("To Small! try again: ")
        elif number > secret_number:
            print(f"you entered: {number}")
            number = input("To big! try again: ")

print(f"you entered: {number}")
print("You Win! Congratulations!")
print(f"You took a total of {count} attempts to guess the number!")



Implementation of Random subclass in Java with a linear congruential generator

I am writing my own Random subclass in java that I want another program to inherit. The subclass should consist of the two constructors Random()which should create a new number generator and Random(long seed) which should create a new random number generator using a single long seed. It should also contain the methods: int next(int bits) which should generate the next pseudo-random number and void setSeed(long seed) which should set the seed of the random number generator.

The seed is retrieved from the user but when I run the program with different types of seeds it outputs the same sequence of numbers despite the change of the seed. I wonder if it might have something to do with my next()method. Could someone see if there is anything I am missing and if so what I should add/remove?

Random() {

  this(System.currentTimeMillis());

}

Random(long seed) {

  
  this.setSeed(seed);

)

//I have defined a, b and m as constants 

int next(int bits) {
  x = ((a * x + b) % m);
  return (int)(x >>> (48 - bits));

}

void setSeed(long seed) {

  x = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);

}



Is there a way in javascript to scramble numbers where the outcome is consistent?

So I need to be able to scramble numbers around but have the outcome always be consistent. Meaning, if I scrambled 1234 and it gave me something like 2143, if I ran the scramble function again it would result in 2143 again.

Is anyone aware of a way to do this?

Below is my inconsistent scrambling method.

function textScrambler(fieldText) {
    var scramWord = '';
    fieldText = fieldText.split('');
    while (fieldText.length > 0) {
        scramWord += fieldText.splice(fieldText.length * Math.random() << 0, 1);
    }
    return scramWord;
}



Is there an algorithm or function that outputs a random number given n number values?

So I have been working on a game that utilizes procedural terrain & structure generation. Right now, I am tackling structure generation - which I used Poisson-Disc sampling, which I plan to implement on chunks in my world. However, my sampling relies on one single seed. Is there a way to accept 3 or more numbers to output a random number somehow related to those numbers?

On another note, the random number doesn't have to be within the possible ranges of the inputs.

If it is not possible, are there any other paradigms to implement Poisson Disc sampling (or alternatives thereof) on an infinite procedurally-generated world to create structures? I am kinda stuck.

Example:

Random x = new Random(138013, 28282, 37920)
x.nextInt() = 38309
Random y = new Random(138012, 28282, 37920)
y.nextInt() = 28323
Random z = new Random(138013, 28282, 37920)
z.nextInt() = 38309
//new Random(a,b,c).nextInt() does not have to be within ranges [a,b], [a,c], [b,c]



How to randomly select an array out of several in JavaScript [duplicate]

I have three arrays with 2 strings each, and would like to randomly select one of the arrays.

array1 = ["hello", "world"];
array2 = ["all", "good"];
array3 = ["bye", "now"];

Something like collecting the three arrays into one, and then math.random? I'm working with JsPsych, in case it is relevant




How to choose the parameters for a linear congruential generator?

I am implementing a linear congruential generator in java for a PRNG where I have to choose appropriate parameters of 'm', 'a', 'c' and the seed. My 'm' further needs to be a prime number and 'a' needs to be a primitive root of 'm'.

Let's say that my 'm' is the prime number: 932537. The smallest primitive root of this number is 3 and the largest primitive root is 932532. How do I make the choice of my 'a' parameter? Do I choose a larger primitive root for 'a' or a smaller root?

Then I also wonder how I should resonate regarding the choice of the parameter 'c' and the choice of the seed which further is supposed to be retrieved by the user.




How to implement a linear congruential generator in Java?

I am implementing my own PRNG where I should use the linear congruential generator. One of my methods should generate the next pseudo random number as seen below. The seed is retrieved from the user earlier.

MyRandom(long seed) {

Random random = new Random();
random.setSeed(seed);

}

This is the method that should generate the next pseudo random number. This is what I tried to write but I don't really know how I could make it work for the next coming numbers. a and b are the chosen constants and m is the chosen prime number.

int next(int bits) {

long seed;
seed = (a * seed) + (b % m);
return (int) (seed >>> (48 - bits));


}



Using Python to select a random date and add values relating to this date to an array?

I am looking for a piece of code that will do the following in Python using Jupyter Notebook;

  1. My excel file has 3 columns - Date (format = day/month/year 00:00), Wind Speed & Coefficient of Performance.
  2. Dates are between 05/May to 31/July.
  3. As there is 12,000+ rows of data, I have decided to take a sample of maybe 200 pieces of data.
  4. I want to use code that will randomly select a row from the 'Date' column and then will put the value of Wind Speed and Coefficient of Performance into separate arrays. I am relatively new to Python so any help will be greatly appreciated.

Many thanks




mardi 30 mars 2021

I'm trying to make a code that randomly generates either 'yes' or 'no' [duplicate]

My current code is

function RNG(){
var y = Math.random();
if(y < 0.5){
x = 1
}
if(y > 0.5){
x = 0
}
console.log(x)
}


RNG()
if(x = 1){
document.writeln('Yes')
}
else{
document.writeln('No')
}

to randomly generate text that says either yes or no, it always comes up with a different number, but always writes yes. (Using purejs)




Generate 50 random numbers between 2million and 20million and make sure they follow the weibull distribution

Aim is to generate numbers following any distribution given maximum and minimum values. In this case, I am trying to make sure 50 numbers generated between 2M and 20M follow the weibull distribution or a gamma distribution.

I have only been able to generate the random numbers so far but unsure how to make them follow a certain distribution.

import random

#generates 50 random numbers between 2M and 20M
r = random.sample(range(2000000, 20000000), 50) 

Can I use weibull_min.rvs() to do this? How is it different from weibull_max.rvs()?




How to create an array from two 2d arrays, based in conditionals and random selection with PYTHON

I´m trying to create an array using two 2d arrays and conditionals. The first array created randomly with numpy is:

A = [[0 0 0 1 0 1 1 0 0 1 0],
     [0 0 1 1 1 1 1 1 0 1 1],
     [0 0 0 1 0 1 1 1 0 0 0],
     [1 1 0 1 0 0 0 1 1 1 0]]

and the second array is:

B = ["a","b","c","d"]

I´m trying to create an array, selecting randomly only "1" value in each column (the row containing "1" doesn´t matter). When I find "1", the position (in selected row) must be linked to array "B", take the value in "B" and finally allocate it in array "C". For example, evaluating column "0", the only possible value is A[0,3]=1, so B=["d"] (the only possible value) and this value must be the 1st value for array "C". Column "3" can take any value from "B".

For example the full array I´m looking for could be the following one:

C= ["d","d","b","a","b","c","a","d","d","a","b"]

I´m trying to create "C" with the following code:

import numpy as np
A=np.random.randint(2, size=(4,11)) 
A=np.array(A)

C=[] 
var=0

B=["a1","b1","c2","d2"]

for i in range(11):
    C.append(var)
    R=np.random.randint(0,4)             
    if A[R,0+i]==1:
        var=B[R]        
    else:
        var=0
print(C)

The result is the following one:

[0, 0, 'a1', 'a1', 'd2', 0, 'd2', 'd2', 'd2', 0, 0]

This code doesn´t complete the work, I can´t find "1" in several columns. I´ve been trying different methods, including: coordinates, loops and generators. But I can´t find one that really works.

I´ll be very grateful if you can help me.

Thank you.




How to separate values from an array into different array based on odd and even in java? [duplicate]

I want to sort my array 'arrSort' auto generated with random value upto 2000 into 2 different arrays, 'arrEven' and 'arrOdd' and then print our the values with the array index number too for the odd and even arrays similar to the print output of the arrSort array.

I've had a look at this question Array even & odd sorting, and it's helpful, but doesn't address sorting an array with randomly generated variables and the 'for' loop used in a way that increasingly considers values in an array since the value are not already predefined.

I've been stuck at this for so long. Plz help.


public class ArraySortingOddEven
{

    public static void main(String[] args)
    {
        Random rand = new Random();
        int upperbound = 2000;

        int n = 0;

        // Create arrays (indexed).
        int arrSort[];
        arrSort = new int[20];

        int arrEven[] = new int[10];

        int arrOdd[] = new int[10];

        {// Assign random numbers.
            for (n = 0; n <= arrSort.length - 1; n++)
            {
                arrSort[n] = rand.nextInt(upperbound);

                System.out.println("random value assigned for arrsort[" + n + "] is " + arrSort[n]);
            }
        }

        System.out.println("");

        for (n = 0; n < arrSort.length; n++)
        {

            if (arrSort[n] % 2 == 0)
            {
                arrSort[n] = arrEven[n];
            } else
            {
                arrSort[n] = arrOdd[n];
            }

            n++;

        }

        for (n = 0; n < arrSort.length-1; n++)
        {
            System.out.println("Numbers in the even array are " + arrEven[n]);
            n++;
        }

        System.out.println("");

        for (n = 0; n < arrSort.length-1; n++)
        {
            System.out.println("Numbers in the odd array are " + arrOdd[n]);
            n++;
        }

    }

}

Here is the console.

random value assigned for arrsort[0] is 679
random value assigned for arrsort[1] is 714
random value assigned for arrsort[2] is 493
random value assigned for arrsort[3] is 1798
random value assigned for arrsort[4] is 5
random value assigned for arrsort[5] is 1350
random value assigned for arrsort[6] is 527
random value assigned for arrsort[7] is 1839
random value assigned for arrsort[8] is 479
random value assigned for arrsort[9] is 886
random value assigned for arrsort[10] is 1554
random value assigned for arrsort[11] is 39
random value assigned for arrsort[12] is 1641
random value assigned for arrsort[13] is 1057
random value assigned for arrsort[14] is 514
random value assigned for arrsort[15] is 382
random value assigned for arrsort[16] is 1058
random value assigned for arrsort[17] is 1132
random value assigned for arrsort[18] is 503
random value assigned for arrsort[19] is 765

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
    at ArraySortingOddEven.main(ArraySortingOddEven.java:37)



How to ensure values produces randomly are unique in Java

When generating a random value, I need to ensure that the generateUserID() method generates a "random and unique" value every time.

private String generateUserID(String prefix, int digitNumber) 
{
    return prefix + String.valueOf(digitNumber < 1 ? 0 : new Random()
            .nextInt((9 * (int) Math.pow(10, digitNumber - 1)) - 1)
            + (int) Math.pow(10, digitNumber - 1));
}    

No output from this method should be the same as another value. Thus, I need to refactor the code, but I cannot use any loop.




The number shown starts at 10 and increases by a random amount until 60 is reached

The number shown starts at 10 and increases by a random amount until 60 is reached. Write an subroutine that will achieve this. E.g 10% off. 24% off. 48% off. 60% off.

That is what the code is supposed to do. This is the code I have written so far. It only prints out 0% insted of the full thing

import random

#subroutine to show discounts

def Percent(total, Num):
    while total != 60:
        total = total + Num
    return total, Num

#main program
Num = random.randint(0,10)
total = 10
print(total,"% off")

ps Im quite new to python so if the fix is really obvious please dont be mean about it :)




random numbers with user-defined continous probability distribution

I would like to simulate something on the subject of photon-photon-interaction. In particular, there is Halpern scattering. Here is the German Wikipedia entry on it Halpern-Streuung. And there the differential cross section has an angular dependence of (3+(cos(theta))^2)^2.

I would like to have a generator of random numbers between 0 and 2Pi, which corresponds to the distribution function ((3+(cos(theta))^2)^2)(1/(99Pi/4)). So the values around 0, Pi and 2Pi should occur a little more often than the values around Pi/2 and 3.

I have already found that there is a function on how to randomly output discrete values with user-defined probability values numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2]). I could work with that in an emergency, should there be nothing else. But actually I already want a continuous probability distribution here.

I know that even if there is such a Python command where you can enter a mathematical distribution function, it basically only produces discrete distributions of values, since no irrational numbers with 1s and 0s can be represented. But still, such a command would be more elegant with a continuous function.




Generating a probability distribution P(y) from another probability distribution P(x) such that highest probability in P(x) is least likely in P(y)

So the problem at hand is that I have some values in a dictionary with counters, let's say

dict = {"cats":0, "dogs":0, "lions":0} 

I want to randomly select the keys from this dictionary and increment the counters as I select the particular keys.

But as I select the keys and increment the counters for those keys, I want the probability of selection to be higher of the keys whose counter values are lesser than the other keys.

I have implemented this idea in my answer below. Kindly let me know if this makes sense and if there are any better ways of doing this?




Create 3D blobs with fixed sizes in a predefined subspace

My question is similar to this post (and possibly also related to this one).

I would like to create random 3D blobs in a predefined subspace. Specifically, my subspace is defined by a binary 3D mask image that 'lives' inside a bigger 3D cube. This mask image again defines the space where the blobs are supposed to 'live' in.

There are a few constraints that should be met:

1.) It should be possible to define the number of blobs.

2.) It should be possible to define the size of each blob as a number of voxels. In other words, each blob should take up a defined fraction of my subspace.

3.) Blobs should not be allowed to touch or overlap (that would violate the first rule because it decreases the defined number of blobs)

4.) Each blob should be a set of connected voxels, i.e. each voxel must be directly connected to another voxel.

I came up with code to obtain a mask_coords array that holds all coordinates defining the subspace. Now I need an algorithm that assigns some of these coordinates to distinct blobs meeting my constraints:

import numpy as np
from nilearn import masking
from nilearn.image.resampling import coord_transform
from nilearn.plotting import plot_roi
from nilearn.image import new_img_like
from nilearn.datasets import fetch_icbm152_brain_gm_mask

# get a grey matter mask image from nilearn. This is a binary 3D image that
# defines our subspace in our bigger 3D cube. 
mask_img = fetch_icbm152_brain_gm_mask()

## Get the x,y,z coordinates of our mask image. ###############################

# get mask data array and affine
mask_data,affine = masking._load_mask_img(mask_img)

# get data indices for all '1' voxels inside mask data array
mask_data_indices = np.asarray(np.nonzero(mask_data)).T.tolist()

# return coordinates for those '1' voxels. This gives us all coordinates that
# correspond to our subspace
mask_coords = np.asarray(list(zip(*mask_data_indices)))

mask_coords = coord_transform(mask_coords[0],
                              mask_coords[1],
                              mask_coords[2],
                              affine)

mask_coords = np.asarray(mask_coords).T

Here's also some code that we can use to come back to a 3D numpy array and that we can use to plot our 3D mask image:

## We can convert the mask coordinates back to data array #####################

mask_indices = coord_transform(mask_coords[:,0],
                               mask_coords[:,1],
                               mask_coords[:,2],
                               np.linalg.inv(affine))

mask_indices = np.asarray(mask_indices,dtype=int).T

empty_array = np.zeros(mask_data.shape)

for indices in mask_indices.tolist():
    empty_array[indices[0],indices[1],indices[2]] = True
    
mask_img_from_indices = new_img_like(mask_img,empty_array)

# show results
plot_roi(mask_img_from_indices,bg_img=None,draw_cross=False)

enter image description here




Filter keys and values from a randomly sorted object in JavaScript

I've got these three objects and I was wondering how I would filter the numeric values and get an output like: RMB = 79.76 (for the first object), RUB = 94.83 (for the first string) and RLB = 64.57 (for the first object).

The main problem is that the keys (Real Lower Band, Real Middle Band and Real Lower Band) are swapped sometimes and their order is random. I suppose this could be done with regex but I'm not very sure how to solve this.

Any help would be greatly appreciated!

Objects:

object1 = {Real Middle Band=79.76, Real Upper Band=94.83, Real Lower Band=64.57}
object2 = {Real Upper Band=96.85, Real Lower Band=62.02, Real Middle Band=84.90}
object3 = {Real Lower Band=42.85, Real Upper Band=65.01, Real Middle Band=55.60}

Desired output

//for each object...
RMB = 79.76
RUB = 94.83
RLB = 64.57



Random, Array and char in java

I need to take a random element from an array of chars

  1. C for hearts
  2. Q for diamonds
  3. F for clubs
  4. P for spades
Random casuale = new Random()

char[] arraySuits = {'c', 'c', 'c', 'q', 'q', 'q', 'f', 'f', 'f', 'p', 'p', 'p',};

location1S=casuale.next(arraySuits.length);
location2S=casuale.next(arraySuits.length);

There are two errors:

  • Type mismatch: cannot convert from int to char
  • The method next(int) from the type Random is not visible

The errors are both at casuale.next(arraySuits.length) but I don't know how to fix it.




Golang crypto/rand internals: How does it generate a secure random?

I started to geek out and I wanted to see how https://golang.org/src/crypto/rand/rand_unix.go works on the inside.

I wanted to see when it generates rands from dev/random (more secure) and when it generates from dev/urandom(less security)

It looks like if rand_batched.go is initialized (this initializes altGetRandom) and GOOS is not plan9 (then r.name = urandomDevice it will return the length of the random array and not the content (which is surprising, why the length?)

see line 57:

if altGetRandom != nil && r.name == urandomDevice && altGetRandom(b) {
        return len(b), nil
    }

else it will simply return the content of the array which will be based on dev/random only if GOOS=plan9.

So why should it ever return len(b)? Also it looks to me that most of the time it will use dev/urandom which is suboptimal... am I wrong (guess so because of docs, but help me understand)?




lundi 29 mars 2021

Random numbers simulating stock market returns

Let me say right from the beginning that I know just a little bit about statistics, but not enough to figure out this problem.

I'm trying to create a list of n random floating point numbers to simulate annual stock market returns. The numbers should range from -30.0 to +30.0 with an average of 7.0. The numbers should be distributed mostly around the average, but they should be well distributed. Basically, it should be a flattened bell curve, so there should be a good chance of having some negative numbers as well as some numbers closer to the upper limit.

I know numpy has functions to create random numbers that are distributed in different ways, but not sure how to specify these parameters.




Select random pixels from image in python [closed]

I have an image of 1000 by 1000 pixels of white color. I would like to randomly select a square of 100 by 100 pixels and change its color it to green. in total, there will be 100 squares each measuring 100 by 100. Since there are 100 squares, I am thinking of looking using a for loop and range (x).e.g:

for i in range(100):

#do something

My challenge is selecting a random cell/square from this image. I was hoping you help figure this out.




Need help to create an array of randomly generated numbers within a range and then displaying the frequency of each number in that range

As the title implies I'm having trouble writing a code that can do as asked. What I have is:

public static void main(String[] args) {
       int[] runs = new int[24];  
       for(int i = 0; i < runs.length; i++) {
          runs[i] = (int)(Math.random()*3 + 1);
          int count = 1;
          for (int j = i+1; j<i;j++) {
              if (runs[i] == runs[j]) {
                  count++;
              }
          }
          System.out.println(runs[i] + " " + count);          
        }   
   }

However, whenever I run my program, it will just list the randomly generated numbers and then a 1 next to them. Any help is appreciated, thank you!




Is there any way that when importing something random a can stop it from picking the same item twice? [duplicate]

Can someone help me and tell me if there is any way I can stop random functions from picking the same item twice?

For example, say this is my code:

import random

numbers = ['1', '2', '3', '4', '5']
for i in range(5):
    print(random.choice(numbers))

Is there any way that I can stop it from picking the same item twice?




MySQL distinct first column, random second column

I need to select distinct values from column A in the database, and then randomise the result associated with column A in column B.

In the below example:

Year    Filename
1973    1.jpg
1973    2.jpg
1973    3.jpg
1973    4.jpg
1975    5.jpg
1975    6.jpg
1975    7.jpg
1975    8.jpg

The result I'm looking for would be to always show the distinct values in Column A, and then randomly select a value associated with that from Column B.

So first page load might produce result:

Year    Filename
1973    1.jpg
1975    5.jpg

But refresh page load might then produce result:

Year    Filename
1973    3.jpg
1975    8.jpg

1973 and 1975 will always each appear once, but what the second field is will vary with every page load.

This is my attempt but it is executing around 1 second:

SELECT DISTINCT year, (SELECT DISTINCT filename from photogallery WHERE year = year ORDER BY rand() LIMIT 1) as filename FROM photogallery GROUP BY year ORDER BY 1



Predict the next numbers using previous numbers as input

I have a set of numbers 0 to 36, colour Black and Red. A random number is generated as output with either Black or Red just like in a roulette. Is there a model which can predict the next outcome by providing the previous outputs as input for the model or Any tips on how to go on about it. I'm completely new to this.




How can I display a random position of a circle but only every each 50px in javascript?

I need to print a circle in a canvas but I need it to be only every 50 numbers. For example a circle that is located in (133,249), in this case it will round to (150,250) I have this method, but it prints anywhere

function getRandomArbitrary(min, max) {
  return Math.round(Math.random() * (max - min + 1)) + min;
}



How to pass the output of a function to itself a number of times in RNG?

I'm trying to pass the output of a function in C to itself a number of times but I'm still getting the same answer each time (I tried to pass it by value and by reference I do not know which is the correct one). I have two functions in my program one that does the calculations and it is called xorshift() and the second function has a for loop; to call the function multiple times and it is called foo(). What I want to do exactly is :

I want to pass (f) to the xorshift function and do the xor and shift operations and then return the output, and this output should go to xorshift function and do the xor and shift operations again and get the output and send it again to xorshift function ..etc I want to do this operation for a number of times.

Any thoughts or suggestions on how to do it?

uint64_t foo (uint64_t* j);
uint64_t xorshift (uint64_t*f);

int main(){

uint64_t z=123456789;
foo(&z);

}

//xorshift function
uint64_t xorshift (uint64_t*f){
  uint64_t q=*f;
    q^=q<<13;
    q^=q>>7;
    q^=q<<17;
return q;
}

//foo function
uint64_t foo (uint64_t* j){
    int k=4;
    for (int i=0; i<k; i++){
        xorshift (&j);
}
return j;
}



How do I plot neighboring data points against each other on MATLAB

I am currently doing an project to improved on the logistic map to create a PRNG. I am trying to prove that the data generated from my code have correlation among one another when plotted against neighboring data point and try to show it on a graph.

This is my code as shown below. It generates different data point for 500 iterations.

    x = rand(1);
    r = 3.99;

    for i = 1:500
    for j = 1:1
    
    X1(i,j) = r*x*(1-x);
    %for next iteration
    x = X1(i,j); 
    
    end
    end

    %output
    disp(X1);
    plot(X1);



generating huge amout of random numbers with python

I want to generate random numbers, uniformly between -1 and 1. I know that using NumPy and generating an array of numbers is much better than generate the one by one in a for loop. On the other hand, I want these numbers to operate with them only once, so there's no reason for storing them in an array. My question is, what is the best solution to this, on one hand using a for loop is not time efficient, but I don't store unnecessary numbers, I generate them one by one and then I throw them. On the other hand, an array is not memory efficient, since if I want to generate 10^10 numbers, I need to create a 10^10 size array, with horrible results. I assume the best choice is to generate small arrays (10^3 or 10^4 elements) one by one, but I want to know if there's a better solution to this problem (maybe a NumPy function that generates the numbers but creates something like an iterable that don't store all them in memory?)




I get an occasional error when I generate a random colour in JS how do I get it to generate rr,gg,bb colour? [duplicate]

I occasionaly get the following error in the console:-

The specified value "#b6aaf" does not conform to the required format. The format is "#rrggbb" where rr, gg, bb are two-digit hexadecimal numbers. randomGradient @ script.js:25

I understand why I am getting the error how do I get it to return colour in the correct format?

var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById("gradient");
var randcol = document.getElementById("randcol");

function setGradient() {
    body.style.background = 
    "linear-gradient(to right, " 
    + color1.value 
    + ", " 
    + color2.value 
    + ")";

    css.textContent = body.style.background + ";";
}

function randomColor() {
        var newColor = '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
        return newColor;
}

function randomGradient() {
    color1.value = randomColor();
    color2.value = randomColor();
    setGradient();
}

randcol.addEventListener("click",randomGradient);

color1.addEventListener("input", setGradient);

color2.addEventListener("input", setGradient);



std::uniform_real_distribution always returns infinity

When I run this code:

double getRandomDouble() {
    static std::mt19937 entropy_ = std::mt19937();
    std::uniform_real_distribution<double> distribution;
    distribution.param(typename decltype(distribution)::param_type(std::numeric_limits<double>::lowest(),
                                                                   std::numeric_limits<double>::max()));
    return distribution(entropy_);
}

It always returns infinity (at least in GCC8.1 & clang 11.0.1. In MSVC 14.16.27023 it asserts)

Here is a working demonstration in GodBolt

I would expect this function to return any random double value, what is happening here?




Scene randomizer issue

I’m developing a casual 2D Game on unity. And I’m a little stuck. I have 2 scripts: one loads when the game starts - (MainMenuScript.cs), one loads when every scene starts - (LevelControlScript.cs)

I need to randomize scenes, but index_scene = UnityEngine.Random.Range(a, b) not quite what I need in my case. But I still need to show scenes in random sequence. I wrote this code where:

MainMenuScript.cs:

  1. Creates a list, where we put played scenes. It should be initialized once on loading.

LevelControlScript.cs:

  1. Chooses the next scene randomly and check it with the values in the list.

  2. If the list includes that scene - choose another random scene, if it’s not in the list - it plays and after that the scene should be added to the list of played scenes.

  3. When all the scenes were played - the list should be cleared.

So, it should rotate until I manually leave the level.

However, I don’t understand why unity shows this error and how to fix it: NullReferenceException: Object reference not set to an instance of an object LevelControlScript.LoadNextLevel () (at Assets/Scripts/LevelControlScript.cs:606)

MainMenuScript:

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

public class MainMenuScript : MonoBehaviour {

    public List<int> remember = new List<int>(); //here

    public void StartLvl()
    {
        SceneManager.LoadScene("Scenes/LVL");
    }

    public void Quit()
    {
        Application.Quit();
    }
}

LevelControlScript:

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

public class LevelControlScript : MonoBehaviour {

    MainMenuScript mainmenu; //here

    // Variable to contain current scene build index
    int currentSceneIndex;
    void Start() {

        mainmenu = GetComponent<MainMenuScript>(); //here
        
        // Getting current scene build index
        currentSceneIndex = SceneManager.GetActiveScene().buildIndex;    
    }

    // Method is invoked when correct answer is given
    public void RightAnswer()
    {
        Code...    
    }

    // Method loads next level
    public void LoadNextLevel()
    {
        int index_scene = UnityEngine.Random.Range(1, 10);
        foreach (int index in mainmenu.remember)
        {
            if (index == index_scene)
            {
                index_scene = UnityEngine.Random.Range(1, 10);
            }
        }
        if (mainmenu.remember.Count == 10)
        {
            mainmenu.remember.Clear();
        }
        mainmenu.remember.Add(index_scene);
        SceneManager.LoadScene(index_scene);
    }
}



python virtual bot random.choices and os.startfile()

so I was making this virtual bot on python using many modules out of which some were (os and random) so in this virtual bot it asks me what I want to do I respond to it and gives me outcomes based on what I asked or told it to do, So, I was trying to add another feature in this code, where, I ask it to play a game it asks me which game and I respond and it opens the game i tell it to

    elif "jarvis play a game" in query or "jarvis play one of my games" in query or "jarvis play my games" in query:
        speak("ok", "I have 6 games", "they are", "breakout arcade game", "car arcade game", "obstrucal course game", "football champs", "path finder", "and", "tic tac toe", "which of these games would you like to play?")
        wgp = takeCommand().lower()
        if wgp == "breakout arcade game":
            speak("ok, opening breakout arcade game, have fun")
            os.startfile("breakout arcade gaming.py")

        elif wgp == "car arcade game":
            speak("ok, opening car arcade game, have fun")
            os.startfile("car arcade gaming.py")

        elif wgp == "obstrucal course game":
            speak("ok, opening obstrucal course game, have fun")
            os.startfile("complete obby game! - ursina.py")

        elif wgp == "football champs":
            speak("ok, opening football champs, have fun")
            os.startfile("football champs.py")

        elif wgp == "path finder":
            speak("ok, opening path finder, have fun")
            os.startfile("path finder.py")

        elif wgp == "tic tac toe":
            speak("ok, opening tic tac toe, have fun")
            os.startfile("tic tac toe2options.py")
        
        elif wgp == "choose a random game":
            speak("ok")
            game = ["tic tac toe2options.py","football champs.py","complete obby game! - ursina.py"]
            choose = random.choices(game)
            os.startfile(choose)
     

this is only a part of the code so the elif statement is not an error, query is the thing that hears and saves what we say. So in this code everything works but the last elif statement where I try making it choose a random game between the given file names that they are saved as, it should choose on of those and i want the os.startfile to start a file that was randomly chosen between the given ones in the list but when i run this code it gives me an error saying

line 24, in <module>
    os.startfile(choose)
TypeError: startfile: filepath should be string, bytes or os.PathLike, not list
[Finished in 0.6s with exit code 1]
[shell_cmd: python -u "C:\Users\Vatsa\OneDrive\Desktop\New folder\all main py files\pyautogui basics 2.py"]
[dir: C:\Users\Vatsa\OneDrive\Desktop\New folder\all main py files]
[path: C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Android;C:\Windows\System32;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\;C:\Users\Vatsa\AppData\Local\Programs\Python\Python36\Scripts\;C:\Users\Vatsa\AppData\Local\Programs\Python\Python36\;C:\Users\Vatsa\AppData\Local\Microsoft\WindowsApps;C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.3\bin;C:\Users\Vatsa\AppData\Local\GitHubDesktop\bin;C:\Users\Vatsa\AppData\Local\atom\bin;C:\Users\Vatsa\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Vatsa\.dotnet\tools]

Can someone help me solve this??

thank you




StatsBase.sample() can't draw with replacement if FrequencyWeights() are provided

I'm trying to sample without replacement using StatsBase.sample() in Julia. Because I have my data in the following form I can use my counts as FrequencyWeights():

using StatsBase

data   = ["red", "blue", "green"]
counts = [2000, 2000, 1]

balls  = StatsBase.sample(data, FrequencyWeights(counts), 1000)

One problem with this is that StatsBase.sample() implicitly sets replace=true so this is possible:

countmap(balls)
Dict("blue"  => 478,
     "green" => 2,  # <= two green balls?
     "red"   => 520)

Explicitly setting replace=false throws an error.

balls  = balls = StatsBase.sample(data, FrequencyWeights(counts), 1000, replace=false)

Cannot draw 3 samples from 1000 samples without replacement.

error(::String)@error.jl:33
var"#sample!#174"(::Bool, ::Bool, ::typeof(StatsBase.sample!), ::Random._GLOBAL_RNG, ::Vector{String}, ::StatsBase.FrequencyWeights{Int64, Int64, Vector{Int64}}, ::Vector{String})@sampling.jl:858
#sample#175@sampling.jl:871[inlined]
#sample#176@sampling.jl:874[inlined]
top-level scope@Local: 2[inlined]

Is my only solution here to reformat my data to a wide form like this? Because that seems very inefficient as my actual data set has a lot of counts.:

wide_data = [fill("red", 2000)..., fill("blue", 2000)..., "green"]
sample(wide_data, 1000, replace=false)



Create a new list enumerating the random integers from another list in Python

I need to simulate a certain scenario.

So I'm defining a variable wich generates a loop of a random number of integers.

I get for example:

list = [2, 35, 4, 8, 56, 10]

Then, I'm generating this random list 50 times through another loop and I store the data into a dictionary to visualize a Pandas Dataframe.

data_dict = {'random_numers': list}
data_dict_pd = pd.DataFrame(data_dict)

So I get for example this:

[1, 16, 6, 6, 1, 10]
[3, 8, 4, 4, 1, 20, 7, 25, 12]
[14, 8, 16, 4, 11, 18, 5, 15, 24, 2, 15, 5]
[7, 24, 1, 14]
[5, 14, 19, 24, 1]
... 50 times. 

Now, I need to create another column enumerating each numerber in each list of elements, to get the following, based on the previous results:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
...50 times. 

Actually, came up with the following but it's wrong:

new_list = []
 for index in enumerate(list)
    new_list.append(index)

Any better idea?




How to make a simualtion in verilog have different results everytime if it has random values?

I wanted to generate a different output of the same code every time i run it as it has random values assigned to some variables is there a way to do that for example seeding using time as in c ? Sample of a code that has the randomization in it

class ABC;

    rand bit [4 : 0] arr []; // dynamic array
    constraint arr_size{

        arr.size() >= 2;
        arr.size() <= 6;

    }


endclass 



module constraint_array_randomization();

ABC test_class;

initial begin 


    test_class = new();
    test_class.randomize();
    $display("The array has the value = %p ", test_class.arr);



end



endmodule











Hey, i have severel problems with my code. The task is to code a number guessing game. Any help would be great :) questions are below

import java.util.Random; 
import java.util.Scanner; 

public class GuessingGame {     

    public static void  main(String[] args)
    { 
        // Scanner Class 
        Scanner sc = new Scanner(System.in); 

        final int num = 10;
        int randomNumber ; // The number user has to guess
                int guess ;        // The guess the user made
                int count = 0 ;    // The count the user has made
        
                Scanner scan = new Scanner(System.in);
                Random generator = new Random();
                
                randomNumber = generator.nextInt(num)+1 ; // generates the Number from 1- 10
                System.out.print("Please guess a random number from 1 -10 ");
                guess = scan.nextInt();                    
                
                while (randomNumber != guess) // Loop until user enters the right number
                {
                    System.out.println("Sorry too high !");
                    if ( guess >randomNumber)   {
                    }    else if  ( guess < randomNumber) {
                                System.out.println("Sorry too low");
                    }            
                                
                    System.out.print("Guess again !");  // User can guess again if the guessed Number was wrong
                    guess = scan.nextInt();
                    count ++;   // if user guessed wrong it counts +1 for every try 
                                }                    
                System.out.println("you guessed the right number !");
                System.out.println("you needed : "+ guess+"tries");  
                }
}
  1. when i enter a number my code tells me : Sorry too high ! Sorry too low! ( it should only tell me if the number is too high or too low)
  2. 1 definded arguments and my code has to check for the input. If the entered number is below argument 1 it has to say : sorry invalid try again. same with argument 2
  3. my code doesnt count how many tries the user needed corretly. 4."Your program takes the input mentioned above, checks for correctness, transforms both arguments in data type intand then generatestheNumber." how do i do this ?



How to convert key of type string to type long?

I am doing a stream cipher program in Java that should take three arguments: a key from a file, the name of an input file and the name of an output file. It should further take the key as a seed to generate a stream of random numbers. I have tried to achieve this first step in the code below, but since the seed needs to be of type long and my array list is of type String it does not work. I am also aware of that storing the key in an array list might be unnecessary. Could someone help me figure out what the best solution is?

public class Streamcipher {

    public static void main(String[] args) throws IOException {

        List<String> inputKey = new ArrayList<String>();


        File key = null;
        if(0 < args.length) {
             key = new File(args[0]);

        }

        BufferedReader br = null;

    try {
        String s="";

     br = new BufferedReader(new FileReader(key));
      while((s=br.readLine())!=null){
        inputKey.add(s);
        
      }

      System.out.println(inputKey);

      randomGenerator(inputKey);
    
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(br != null){
            br.close();
        }
    }

    

}

public static int randomGenerator(long seed) {
    
        Random myRandom = new Random(seed);
        int keyStream = myRandom.nextInt(256);
        System.out.println(keyStream);

    return keyStream;

   

}

}



Cpp random number with rand returns very similar numbers

I'm trying to generate a random number using rand() command, but each time i get very similar numbers. This is my code:

#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    srand(time(0));
    cout << rand();
    return 0;
}

I ran it 5 times and the numbers i got are: 21767 21806 21836 21862 21888

How can i make the numbers be more different?




Random matrices in R eigenvalue plot

enter image description hereThe picture above is from the book Spectra and Pseudospectra of Trefethen and Embree.It illustrates the eigenvalues of N random matrices: They are uniformly distributed in the unit disk. As they state: "Of course, for each finite N this statement cannot be ex­ actly correct. For complex matrices, the probability density function of the eigenvalues is a continuous function that is nonzero throughout the com­ plex plane. For real matrices, not only is the probability density nonzero throughout the plane, but it has a delta function singularity along the real axis, since for any finite N, there is a positive probability that some eigenvalues will be purely reaP In the limit as N goes to infinity, however, these complexities fade away and the distribution converges to the constant $pi^(-1)$ inside the unit disk and zero outside."

my effort in R is this :


n=20
x = matrix(c(rnorm(n*n)),n,n)
plot((eigen(x)$values)/sqrt(n))
plotrix::draw.circle(0, 0, 1, nv = 1000, border = NULL, col = NA, lty = 1, lwd = 1)
norm(x,"2")

But the results are not right.What I am doing wrong? The norm is not 2. And I am not happy with the unit disk plot. Any help?




dimanche 28 mars 2021

If my class has many children, how can I initialize an object that is a random child of my class?

For example.

Parent: Vehicle Children: Car, Train, Horse

I want to do the following

Vehicle randVehicle = new RandomeVehicleChildObject;

I was thinking I could do this:

Vehicle randVehicle;
Random r = new Random();
int x = r.nextInt();

if(x == someInt)
   randVehicle = new Car();
else if(x == otherNum)
   randVehicle = new Train();
else
   randVehicle = new Horse();

However, what if my class has many more children? Like 15 or 20? I feel like writing so many if-else chains or switches would be a pain. Is there a way to just do it in one line?




R large data frame random sub sample based on grid

I have a very large data frame (7000 columns and 14000) observations. They are in fact greyscale observations of each pixel of an image. 7000px observations on the x-axis and 140000px on the y axis. I'm looking for a way to do the following:

  • Divide the data frame into a grid that is 1000 by 1000 pixels (or 1000 cols and 1000 rows). In this case, it will be a grid of 7 by 14
  • Randomly select 1, 2, or more pixels from each grid
  • Store the returned values in a new data frame along with its x and y coordinates and if possible the grid it came from but this means numbering each grid as well.

Any ideas on how I might do this would be greatly appreciated




Why am I getting this weird item when trying to use Java.util.Random? [duplicate]

    Random rand = new Random();
    rand.nextInt((101)+1);
    System.out.println(rand);

What is this?




How to delete randomly inserted characters at specific locations in a string?

I was previously working on a problem of String encryption: How to add randomly generated characters in specific locations in a string? (obfuscation to be more specific).

Now I am working on its second part that is to remove the randomly added characters and digits from the obfuscated String.

My code works for removing one random character and digit from the string (when encryption_str is set to 1) but for removing two, three .. nth .. number of characters (when encryption_str is set to 2, 3 or n), I don't understand how to modify it.

My Code:

import string, random
def decrypt():

    encryption_str = 2 #Doesn't produce correct output when set to any other number except 1

    data = "osqlTqlmAe23h"
    content = data[::-1]
    print("Modified String: ",content)
    
    result = []
    result[:0] = content

    indices = []
    for i in range(0, encryption_str+3): #I don't understand how to change it
       indices.append(i)

    for i in indices:
      del result[i+1]

    message = "".join(result)
    print("Original String: " ,message)

decrypt()

Output for Encryption level 1 (Correct Output)

enter image description here

Output for Encryption level 2 (Incorrect Output)

enter image description here




random video chosen from predetermined youtube playlist

i am using nocode / appguyver to create a simple button app that opens one random video from a predetermined collection created by me specifically located within an easily changeable youtube playlist. how can i randomize this URL opening action? thank you much cheers joy




What is a simple and safe way to choose a random enum value?

I needed to choose a random value from an enum. In some article about Nim I found this solution:

import random

type Animal = enum
  Cat
  Dog
  Cow

echo rand(0..2).Animal

But this doesn't scale well: If some values are added to or removed from the enum, we have to adjust the upper number.

We can even get a runtime error:

import random

type Animal = enum
  Cat
  Dog

randomize(123)

while true:
  echo rand(0..2).Animal
Cat
Cat
Dog
…/example.nim(10) example
…/.choosenim/toolchains/nim-1.4.4/lib/system/fatal.nim(49) sysFatal
Error: unhandled exception: value out of range: 2 notin 0 .. 1 [RangeDefect]

I am looking for a simple way to choose a random value from an enum1 that is safe, meaning that if it compiles, it is guaranteed that there will be no RangeDefect or similar runtime error.

I would also be interested to know if there is a compiler setting that generates at least a warning that in the above example.

The compiler seems to be capable of this in principle:

echo Animal(5)

→ Error: 5 can't be converted to Animal

After reading in https://nim-lang.org/docs/random.html about

I thought that one of the following could work, but they don't compile:

rand(Animal)

→ Error: type mismatch: got <type Animal>
rand(range(Animal))

→ Error: type mismatch: got <type Animal> but expected 'range = range (None)'
rand(range[Animal])

→ Error: expected range
rand(Slice[Animal])

→ Error: type mismatch: got <type Slice[example.Animal]>
rand(Slice(Animal))

→ Error: type mismatch: got <type Animal> but expected 'Slice = CompositeTypeClass'

This does work, but I guess it is unnecessarily inefficient, because it needs to allocate and fill a sequence:

import sequtils

echo sample(Animal.toSeq)

1I'm assuming enums without holes, which I'm aware are another issue.




How to store instances of an integer in an array in a separate variable in C#?

I am trying to make a C# program that picks a random number from 1 to 6 and stores it in an array. How to find the instances of a specific number from 1 to 6?

using System;

namespace DiceProbabilityCalc
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rnd = new Random();
            int[] instanceCount = new int[1000];

            for (int i = 0; i < 999; i++)
            {
                int num = rnd.Next(1, 7);
                instanceCount[i] = num;
            }
        }
    }
}




Python seed (random.seed) is not giving replicable results

I want to create some code that uses both random.sample and numpy.random.randint but in such a way that is completely replicable. How do I properly set the seed for random.sample?

import numpy as np
import pandas as pd
import random

np.random.seed(3)
random.seed(3)

numteam = 3

nameslist = {"Abigail", "Briana", "Charlotte", "Daisy", "Emma", "Florence", "Gail", "Heather", "Imogen", "Jane", "Kelly", "Mara", "Natalie", "Olivia", "Patricia"}
team = random.sample(nameslist, numteam)

df = pd.DataFrame(np.random.randint(0,10,size=(numteam, numteam)), columns = team)
df.index = team

print(df)

I ran this code twice on the same online compiler and get different name selections (the randint is consistent) enter image description here

Interestingly, if I use a different online compiler the seed seems to stick. I need to be able to have others run the code using whatever compiler they like and get the exact same "random" data frame as what I have (each user will have a unique seed so no two people get the same data frame).

I've looked at a lot of examples online, but from what I can tell random.seed is what I am meant to be doing. I am using Pycharm 2020.2 with Python 3.8 locally. The two online compilers I have tried are https://www.tutorialspoint.com/execute_python_online.php and https://pynative.com/online-python-code-editor-to-execute-python-code/




samedi 27 mars 2021

How can I open a random jFrame within my project folder when a button is clicked?

I'm a beginner to Java, and I'm trying to create a simple virtual library with a random book selection feature, which will occur at the click of a button named "Random".

So far in my project, I have a login form, register form, homepage and 3 books contained in their own respective jFrames. In the homepage jFrame, I would like to have a button that will randomly choose one of the 3 book jFrames and open it. However, it shouldn't be able to open any of the other jFrames (login and register). Is there a way that I can achieve this? I am using Netbeans IDE 12.2




Python - Can I color strings that are inside a list?

Fist of all I would like to clarify that at the time of writing this I'm a complete newbie to Python and programming in general, I've only picked up Python yesterday.

I'm learning the language while working on a personal proyect.

My code takes numbers from 1 to 5, runs them through a random.choices Method and weighs them, then returns a random list that would look like this:

[2,1,4,5,2] Let's call this list xs

Each of those numbers has a list of strings asociated to them, let's call them "xsn"

So 1 has xs1 = ['1stringA','1stringB',...,'1stringZ'], same with 2,3,4 and 5

I then run xs through this code

while True:
    for i in range(5):
        if xs[i] == 1:
            xs[i] = (random.choice(xs1))
        if xs[i] == 2:
            xs[i] = (random.choice(xs2))
        if xs[i] == 3:
            xs[i] = (random.choice(xs3))    [Tips on how to improve this code are also accepted and apreciated]
        if xs[i] == 4:
            xs[i] = (random.choice(xs4))
        if xs[i] == 5:
            xs[i] = (random.choice(xs5))
    print(xs)

This will give me a modified xs list that, instead of numbers from 1 to 5, has strings. So if the last list was

[2,1,4,5,2]

The new xs list would be

['2stringA','1stringA','4stringA','5stringA','2stringB']

What I want is for each number to also have it's own asociated color, so '2stringA' and '2stringB' would be Green, '1stringA' would be White and so on.

Any ideas on how to make this happen? Sorry for writing such a long post, as I get better I hope I can sumarise my questions in a more condensed manner.




random array of objects with no repeat

I use splice to show quotes with no repeat but I think I miss something cause q.length is'not change

this is my code:


async function JsonFile(){

    const response = await fetch('/quotes.json');
    const data = await response.json();

    const quotes = data.quotes; 
    getQuotes(quotes)
}

let backupArray =[];

function getQuotes(q){

    const random = Math.floor(Math.random()* q.length);

    name.textContent = q[random].name;
    quote.textContent = q[random].quote;
   const spliceEl = q.splice(random,1);
   console.log(spliceEl);
   backupArray.push(spliceEl);
   console.log(q.length);
   console.log(backupArray)
  

}

button.addEventListener('click' ,JsonFile)





JAVA UUID use only numeric characters to generate random UUID

I want to generate a serial number for one of my classes like xxxxxxxxxx and I want its length to be exactly 10 characters.

how can I generate random UUID by only using "1234567890". is there something I have to pass to constructor or UUID.randomUUID()?

and how can I give it a fixed length?

thanks.




How to add randomly generated characters in specific locations in a string?

I am working on a problem that requires me to read a string from the file and:

  1. Reverse it
  2. An integer encryption strength will be defined. It can be set to any integer value between 0 and 255.
  3. Based on the value of encryption strength, some random letters or digits will be inserted between every letter in the reversed string from step 1.

For example, if the strength was set to 1, the word hello can be encrypted to oxlal9elh.

Another example, if the strength is 2, the word hello can be encrypted to oxil4hlrce6rh.

My code works overall fine, but the problem is I get repeated random characters inserted between the letters of string, every time.

Here's my code, kindly help me identify the error.

Code

def encrypt():
    data = "hello"
    content = data[::-1]

    encryption_str = 2
    
    characters = string.ascii_uppercase +string.ascii_lowercase+ 
    string.digits
    
    
    res = (random.choice(characters).join(content[i:i + encryption_str] for i 
    in range(0, len(content)))) #I am stuck here
    
    print(res)
encrypt()

Output

enter image description here enter image description here




array with random ints but no duplicates and first number showing

This is probably already asked, but I am a little new to Java and it is a little difficult for me to understand. I created a for loop to add random integers into my array, but when the integer is already in the array, restart the loop. But I keep on getting the same integers into the array + when there already is a duplicate, the array size increases. Does anyone know what I'm doing wrong?

Random r = new Random();
        int[] tes = new int[5];
        for (int i = 0; i < tes.length; i++) {
            int q = r.nextInt(10);
            for (int j = 0; j < i; j++) {
                if (q == tes[j]){
                    i=i-1;
                }
            }
            tes[i] = q;
            System.out.println(tes[i]);
        }

and the output:

enter image description here




Build random adjacency matrix with given probability [duplicate]

As a task I need to write a C program that receives a V (vertices) and a P (probability) parameters.

The function will then create a randomly generated graph, generating an edge between two nodes with a specific user inputted probability.

I've made a random adjacency matrix using rand(), but I'm having a hard time implementing the same idea with a given user probability instead of just randomly assigning 1/0.

Completely lost, how can I do that?

Code here:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
int i, j;
float p = 0.3;
int g[5][5] = { 0,0,0,0,0,0,0,0,0,0 };
srand(time(0));
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (rand() / (double)RAND_MAX < p)
        {
            g[i][j] = 1;
        }
    }
}

for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        printf("%d", g[i][j]);
    }
    printf("\n");
    }
}



vendredi 26 mars 2021

How can I generate a random rectangle in a canvas without touching the lines?

How can I make the rectangle in the canvas appear randomly anywhere in the canvas but it will never touch the division lines? the rectangle should always be the one I wrote in the code

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
//
ctx.rect(20, 20, 40, 25);
//

ctx.moveTo(100, 0);
ctx.lineTo(100, 500);
ctx.moveTo(200, 0);
ctx.lineTo(200, 500);
ctx.moveTo(0, 75);
ctx.lineTo(300, 75);
ctx.stroke();

</script> 

</body>
</html>



How to assign random numbers to 2 variables, and then assign new random numbers to those 2 variables when needed?

I need to write a program (using inheritance) that uses a random number generator to produce 2 random numbers, present the two numbers as an addition question, and then when the question is answered, produce a new question that uses new random numbers. So far, I have the following code in 3 separate java files:

public int numberGenerator()
   {
       int num = 0;
       Random ranNum = new Random();
       ArrayList<Integer> list = new ArrayList<Integer>();
       
       for (int i = 1; i < 20; i++)
       {
           num = ranNum.nextInt(10);
           list.add(num);
       }
       
       Collections.shuffle(list);
       for (int i = 0; i<20; i++)
       {
           list.get(num);
       }
       
       return num;
   }
int rand1 = numberGenerator();
int rand2 = numberGenerator();
int sum = rand1 + rand2;
String sumCompare = String.valueOf(sum);

And I have this code to present the question:

while (problem.getSum() < 10)
            {
                problem.setText("What is " + problem.getRand1() + " + " + problem.getRand2()
                + " ?");
                problem.setAnswer(problem.getSumCompare());
                presentQuestion(problem);
            }  

Let's say the random numbers it spits out is 2 and 3. It will ask me, "What is 2+3?" And then I'll answer it correctly, and it asks me another question, but it will again ask me "What is 2+3?" I need the code to ask me a different addition question, and not use the same numbers over and over again. I apologize in advance if I am missing information and please let me know if more needs to be known, I tried to include as much as I could!




How can I plot the eigen values of 10000 random matrices in R?

I have the following function that creates M random normal matrices of size n. But how can I plot all the Eigen values of all these matrices in one plot (histogram )?

M = 10000
n = 6
rmat <- function(n){
  matrix(rnorm(n*n), n, n)
}
out <- replicate(M, rmat(n))



Drawing random numbers from a power law distribution in R

I am using the R package "poweRlaw" to estimate and subsequently draw from discrete power law distributions, however the distribution drawn from the fit does not seem to match the data. To illustrate, consider this example from a guide for this package: https://cran.r-project.org/web/packages/poweRlaw/vignettes/b_powerlaw_examples.pdf. Here we first download an example dataset from the package and then fit a discrete power law.

library("poweRlaw")
data("moby", package = "poweRlaw")

m_pl = displ$new(moby)
est = estimate_xmin(m_pl)
m_pl$setXmin(est)

The fit looks like a good one, as we can't discard the hypothesis that this data is drawn from a power distribution (p-value > 0.05):

bs = bootstrap_p(m_pl, threads = 8)
bs$p

However, when we draw from this distribution using the built in function dist_rand(), the resulting distribution is shifted to the right of the original distribution:

set.seed(1)
randNum = dist_rand(m_pl, n = length(moby))

plot(density(moby), xlim = c(0, 1000), ylim = c(0, 1), xlab = "", ylab = "", main = "")
par(new=TRUE)
plot(density(randNum), xlim = c(0, 1000), ylim = c(0, 1), col = "red", xlab = "x", ylab = "Density", main = "")

Resulting Plot, Red = Distribution Drawn from Fit

I am probably misunderstanding what it means to draw from a power distribution, but does this happen because we only fit the tail of the experimental distribution (so we draw after the parameter Xmin)? If something like this is happening, is there any way I can compensate for this fact so that the fitted distribution resembles the experimental distribution?




Program that creates random numbers from 1 to "n", without repeating, in .NET c# and store them in a array of size [n]

Well, I've been coding this program that has the objective to create random numbers, and then store them in an array (linhas[n]), but I don't want them to repeat. I started by doing a for cicle (int i = 0; i < n; i++) and inside it I wrote that an variable a (int a) was equal to a random number generated from the random function (r). Then I compared if "a" already existed in the array, using "bool b = Array.Exists(linhas, elements => elements == a);", then wrote that if "b" was true it would decrease the "i" value by one, to repeat the same i cicle, doing linhas[i] = a if "b" was false. Then it would write the elements of the array. The problem that I'm getting is that when I oppen the program and write the value of "n" the program just doesn't do nothing, just a black screen. I already checked and if I put the value of "n" = 1, the program generates just one number, number 1. But if I put "n" = 2 it just stops. If anyone understood what I said here and could help me, please just throw some tips!

The code here:

static void Main(string[] args)
    {
        int n;
        Console.Write("Escreva o número de linhas a aparecer: ");
        n = Convert.ToInt32(Console.ReadLine());
        int[] linhas = new int[n];
        var r = new Random();
        for (int i = 0; i < n; i++) 
        {
            int a = r.Next(1, n);
            bool b = Array.Exists(linhas, elements => elements == a);
            if (b == true)
            {
                i--;
            }
            else
            {
                linhas[i] = a;
            }
        }
        Console.WriteLine("");
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine(linhas[i]);
        }
        Console.Read();
    }



Function acts bizarrely

Let's define X as :

enter image description here

and objects releated to it:

enter image description here

I want to calculation value of function following, and plot it on the same graph with eigenvalues of Y.

enter image description here

My work so far

# Define dimensions of X 
N=700;
T=900;
lambda=N/T;

# Randomize X
x=randn(N,T);
# Estimate standard deviation
s=std(x(:));
# Now we estimate y and it's eigenvalues
y=x*x'/T;
l=eig(y);
# Calculating lambda_plus and lambda_minus
lambda_plus=(s^2)*(1+sqrt(lambda))^2;
lambda_minus=(s^2)*(1-sqrt(lambda))^2;
x_lim = linspace(0.1, 3, 10^3)
# Taking into account indicator function
  if (x_lim <= lambda_plus && x_lim>= lambda_minus);
    smth=(1./(2*pi*lambda*x_lim*s^(2))).*sqrt((lambda_plus-x_lim).*(x_lim-lambda_minus));
  else 
    smth = 0
  endif
  # Normalize histogram
  [f, p] = hist(l, nbins = 20)
 hold on;
   bar(p, f / sum(f));
 plot(x_lim, smth)

The problem I have with this function is that the output looks like following:

enter image description here

which doesn't exactly look as should. According to wikipedia these two plots should converge much more significantly. I found somewhere on internet very similar plots and those look like this:

enter image description here

My question is: what I'm doing wrong ? Did I choose a wrong scale ? As I can see on the second plot function takes much less values than mine but I have no idea what is wrong with its calculation. Could you please give me a hand telling what I did incorrectly ?




Random matrices in R

I want to create in R 10000 random normal matrices of size n = 6. The code for one matrix is :

n = 6
H = matrix(rnorm(n*n), n,n)

But how can I create 10000 matrices in one for loop command?




How do I create 4 different lists of random numbers without overlapping them using Python?

I need to create 4 lists of random numbers containing 6 numbers each, these numbers can't overlap. How can I do it? The below only generates 1 list. I need 4.

import random

list_numbers = [random.randint(8,28) for x in range(6)]
print(list_numbers)



Coding the dice and getting the players to move using coordinates and turtle

I am trying to code a snakes and ladders game using the turtle library. The position of each player has been defined using coordinates. Now I have some trouble coding the dice and getting the players to move accordingly.

Here is the bit of code I need help with:

def dice():

    turtle.addshape("bull.gif")

    player1 = turtle.Turtle()
    player1.shape("bull.gif")
    player1.penup()
    player1.goto(-240, -260)


    

    dice1 = random.randint(1, 6)

    #dice2 = random.randint(1, 6)



    player1_dice = input("\nBULL (P1): Please press 'ENTER' to roll the dice ")


    if player1_dice == "":
        print("BULL (P1) rolled a", dice1)

    elif player1_dice != "":
         print("BULL (P1): Please make sure to press 'ENTER' ")



    P1_coor =

    
    P1_pos = 1
    dieValue = dice1
    pos = 0

    for pos in range(dieValue):
        newPos = pos + P1_pos + 1
        player1.goto(newPos)

    P1_pos = newPos


        
dice()



SQL Updating with random subselect everytime, giving me same value for all rows

I have a column with 90% null values, I am trying to use the remaining 10% to pick a value randomly everytime and use it to fill the missing vlues in the exact same table.

this is my table

initial table

I am using this query to do it on PostgreSQL :

UPDATE public."Assure"
SET   "codePostal" = ( 
    SELECT "codePostal" 
      FROM public."Assure"
      WHERE "codePostal" is not NULL
      ORDER BY random() * public."Assure"."CodeAssure_id"
      LIMIT 1 )
WHERE "codePostal" is NULL

result :

this is what i get




How to generate a pseudo-random number using a seed in java for a Stream Cipher?

I am working on a Stream Cipher program in Java which should take three arguments from the shell: a file with a key, a file for input, and a file for output. The key should then serve as the seed which should generate a pseudo-random number which should be "XOR:ed" with the plaintext in the input file.

I have managed to write the code for reading a file but I do not know how I am supposed to write the code for taking the key as the seed and thus generate a pseudo-random number as explained above. Could someone help me?

public static void main(String[] args) throws IOException {
   File key = null;
   File input = null;
   File output = null;
   if (0 < args.length) {
      key = new File(args[0])
      input = new File(args[1]);
      output = new File(args[2]);
}
//more stuff

//a function that takes the seed from the key file and should generate a pseudo-random number

int prng (long seed) {
    Random random = new Random ();
    int bound = 256;
    int number = random.nextInt(bound);

    return number;

    }


      



xpath generate random number

Is there a way to generate a random number with xpath? My input is any well-formed xml, the output should be a random integer of a given length. I usually achieve it with any coding or xslt but I'm struggling to find a working xpath expression.




join depending on the "randomized number," for example, if the randomized < 20, then join

case when (ISNULL(rnd_c03.RANDOM_NUMBER,99) BETWEEN 0 AND 20) then LEFT JOIN [rtdm_main].[RTDM_SCORE] C03
ON res.RUN_ID = C03.RUN_ID AND sdms.SCORECARD_TYPE = 'C03'

Thanks for the answer!




jeudi 25 mars 2021

Printing weird characters in C

I´ve implemented a couple of functions to generate random strings,

char *ran_string(int max, int min){  //random string with max length and min length

    int tam=rand()%max,i=0;
    char *str;
    if(tam<min)
        tam=min;
    str=malloc(sizeof(char)*tam);
    for(i=0;i<tam;i++) {
        if(i==0){
            str[0]=(char)((rand() % 26) + 65); //Upercase ascii
        }
        else{
            str[i]=(char)((rand() % 26) + 97);  //Lowercase ascii
        }

    }
    return str;
}
char *var_ran_string(int num, int max, int min){ //generates num random strings
char *a;
a=malloc(sizeof(char)*num*max);
strcat(a,ran_string(max,min));
for(int i=0;i<num-1;i++){
    strcat(a," ");
    strcat(a,ran_string(max,min));
}
return a;

}

I´ve tested it out, and the second time that i call var_ran_string it always prints weird characters like h�1�Dvdfn�2�|��� Zlbhh���. Tried calling the function thousands of times, but the second time seems the only problem.




rand function is giving me the same result at each run even when I called srand(time(NULL))

I have a problem, I want to use rand() to get a random number between 0 and 6, but it always gives me 4 at each run, even when I call srand(time(NULL))

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

int main(void)
{
    srand(time(NULL));

    int rd = rand() % 7;

    printf("%d\n", rd);
    return (0);
}

output is 4 at each run




How to put breakpoint at random instruction

I have to do this, repeatedly many times:

  1. Start execution of program
  2. Stop at random point during execution
  3. Modify value in register
  4. Continue execution

Until now, I've been using GDB extended with Python and the only struggle is to stop randomly during execution.

Already tried approaches:

  • Retrieve binary file sections and pick random address among executable instructions. ----> Problem: too low probability of hitting set breakpoints, takes too long to obtain valuable results.
  • Break at _start and do stepi {rand_num} to skip {rand_num} instructions, then alter register. ----> Problem: infeasible, programs under test contain too many instructions, too long test execution time.
  • Send signal SIGINT to the inferior process, after waiting a random amount of time. ----> Problem: programs under test execute in less than 30ms, problems with temporization.

How would you do? Which tools would you use?

Thank you in advance! :)




Neo4j: Difference between rand() and rand() in with clause when matching random nodes

I found here that i can select random nodes from neo4j using next queries:

  1. MATCH (a:Person) RETURN a ORDER BY rand() limit 10
  2. MATCH (a:Person) with a, rand() as rnd RETURN a ORDER BY rnd limit 10

Both queries seems to do the same thing but when I try to match random nodes that are in relationship with a given node then I have different results:

The next query will return always the same nodes (nodes are not randomly selected)

MATCH (p:Person{user_id: '1'})-[r:REVIEW]->(m:Movie)
return m order by rand() limit 10

...but when I use rand() in a with clause I get indeed random nodes:

MATCH (p:Person{user_id: '1'})-[r:REVIEW]->(m:Movie)
with m, rand() as rnd
return m order by rnd limit 10

Any idea why rand() behave different in a with clause in the second query but in the first not?




How to generate random unicode strings in rust?

I'm implementing a fuzzer and I'd like to generate random unicode strings. I came up with this solution, however, it's very inefficient and seldomly produces some string. Is there a better way to generate unicode strings?

Thank you.

use rand::{thread_rng, Error, Rng};
use std::convert::TryFrom;

fn main() -> Result<(), Error> {
    let mut rng = thread_rng();
    let mut arr: Vec<u32> = vec![0; 1024];
    rng.try_fill(&mut arr[..])?;

    println!(
        "{:?}",
        arr.iter()
            .map(|u| char::try_from(*u))
            .flatten()
            .collect::<String>()
    );

    Ok(())
}

Rust Playground link




Re-Running a turtle program

I have made a simple python program that creates randomly generated spirals using the turtle module. I am still pretty new at python and i was wondering how i could restart the program after the turtle is pretty far away from the center and the spiral is done. Here is my code:

import turtle
import random

root = turtle.Screen()
turtle = turtle.Turtle()

colors = ["yellow", "gold", "orange", "red", "maroon", "violet", "magenta", "purple", "navy", "blue", "skyblue", "cyan", "turquoise", "lightgreen", "green", "darkgreen", "chocolate", "brown", "gray", "white"]

def spiral():
    endColors = [random.choice(colors), random.choice(colors), random.choice(colors)]
    angle = random.randint(60, 300)
    distance = turtle.distance(0, 0)
    
    print("Colors used are:", endColors)
    print("The turning angle is: ", angle, "deg")
    print("The distance is: ", distance)

    turtle.speed(0)
    turtle.hideturtle()
    root.bgcolor("black")
    for i in range(2000):
        turtle.forward(i)
        turtle.right(angle)
        turtle.color(endColors[i%3])
    root.mainloop()
spiral()

I have tried using the turtle.distance function in an if statement but it dident work.




Is randint function in Python different from % trick?

I appreciate your help in advance.

I wrote a probability calculator with python. Prob I want to calculate is this: What's the prob of winning when you try 6 times of game that has winning chance of 1%. So this following code is what I wrote.

import random as rand

total = 0
count = 0

p = pSum = 0

k = 6
n = 10000
m = 100

def pick(attemptPerIteration):
    global total, count
    for _ in range(attemptPerIteration):
        temp = rand.randint(1, 100)
        if (temp == 1):
            count += 1
            total += 1
            return 0
    return 1

for t in range(m):
    for u in range(n):
        total += pick(k)
    p = count / total
    print(str(t + 1) + ": " + str(p * 100))
    pSum += p
    p = 0
print(pSum / m * 100)

In this code, I used randint function to simulate one in 100 chance. The prob I expected is about 5.8% but this program outputs about 6.3%. But if I use randint(1, 1000) % 6 + 1 insted of just randint(1, 6), program tell the prob is 5.8, which I expected.

What's going on in this randint function exactly? Why the old % trick works but randint doesn't?

Mathematical formula to this problem is this: enter image description here




How do I correctly implement this switch statement to compose a string?

I want to produce a string that is a single letter (A, B or C), followed by two random numbers. I have written the following code:

enum typeOfPerson {CHILD, ELDER, BOOMER};


    public String setNumber(Report.ReportType type) {

        Random rand = new Random();

        String number = String.valueOf(rand.nextInt(10)) + String.valueOf((rand.nextInt(10)));
               
              
        switch (type) {
            case CHILD:
                String prefix = "A";
                break;
            case ELDER:
                prefix = "B";
                break;
            case BOOMER:
                prefix = "C";
                break;
    

                 accountNumber = prefix + number;

        }
        return accountNumber;
    }

When I run the code I just get the two random numbers, without the prefix. I am unclear where the error is, but I am guessing I did something wrong with the switch statement.




RockPaperScissor game not getting expected result - C programming

I was writing c program on rock paper and scissor game but could not get the expected result.

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

int main()
{
    char player[50], choice[10];

    puts("Enter your name: ");
    gets(player);

    int player1 = 0, comp = 0;

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

        printf("%s: ", player);
        scanf("%s", choice);

        int computer = rand()%3;

        if (computer == 0){
            printf("computer: rock\n");
        } else if(computer == 1){
            printf("computer: paper\n");
        }else{
            printf("computer: scissor\n");
        }

        if (computer == 0 && choice == "paper"){
            player1++;
        }else if (computer == 0 && choice == "rock"){
            continue;
        }else if (computer == 0 && choice == "scissor"){
            comp++;
        }else if (computer == 1 && choice == "paper"){
            continue;
        }else if (computer == 1 && choice == "rock"){
            comp++;
        }else if (computer == 1 && choice == "scissor"){
            player1++;
        }else if (computer == 2 && choice == "paper"){
            player1++;
        }else if (computer == 2 && choice == "rock"){
            comp++;
        }else if (computer == 2 && choice == "scissor"){
            continue;
        }else {
            printf("Invalid Entry.");
        }
        printf("\n");
    }

    if (player1 > comp){
        printf("%s wins.", player);
    }else if (player1 == comp) {
        printf("%s and computer draws.", player);
    }else{
        printf("%s loses.", player);
    }
    
    return 0;
}

The program works but I am not getting the expecteed result in all 3 runs of the for loop I get only invalid entry as output due to which I can't count the score and the result as both player and comp variable are idle due to this.

output:

Enter your name:
Sam
Sam: rock
computer: scissor
Invalid Entry.   
Sam: scissor
computer: scissor
Invalid Entry.   
Sam: paper
computer: paper
Invalid Entry.
Sam and computer draws.

I have checked to best my skill and could not find any mistake I don't know why if else-if is acting weirdly, Help me to get correct output and explain me what the problem and where the mistake is.




Flutter Firebase random String

Does anyone know how I can put the String _map before the _chars that there is then a map with a random String like this : AllComments.df8dfd or AllComments.erte84 :

AllComments

    df8dfd : "hello"
    erte84 : "cool"
static const _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
 String _map = 'AllComments.';
  Random _rnd = Random();

  String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
      length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));



Flutter how to generate random strings

Hello does anyone know how I can only generate Strings with letters. Like :

"skdnjfsd" or "bdfvkjnd" ?

my current code :

String _randomString(int length) {
    var rand = new Random();
    var codeUnits = new List.generate(
        length,
            (index){
          return rand.nextInt(33)+89;
        }
    );

    return new String.fromCharCodes(codeUnits);
  }



Multiple random values between specific ranges in R?

I want to pick up 50 samples from (TRUNCATED) Normal Distribution (Gaussian) in a range 15-85 with mean=35, and sd=30. For reproducibility:

num = 50 # number of samples
rng = c(15, 85) # the range to pick the samples from
mu = 35 # mean
std = 30 # standard deviation

The following code gives 50 samples:

rnorm(n = num, mean = mu, sd = std)

However, I want these numbers to be strictly between the range 15-85. How can I achieve this?

UPDATE: Some people made great points in the comment section that this problem can not be solved as this will no longer be Gaussian Distribution. I added the word TRUNCATED to the original post so it makes more sense (Truncated Normal Distribution).




Shuffle two arrays the same way in python [duplicate]

I know that I can do the following

import random
random.shuffle(array)

but I need to shuffle to arrays the same way. something like this:

array1 = [1, 2, 3, 4, 5]
array2 = ["one", "two", "three", "four", "five"]
ramdom.shuffle(array1, array2)
print(array1, array2)
>>>>
[2, 3, 1, 5, 4]
["two", "three", "one", "five", "four"]



How to propagate random seed to child processes

If you try running this code:

from multiprocessing import Pool
from multiprocessing.pool import ThreadPool
import random  

def do_thing(upper):
    print(random.randint(0,99))
        
random.seed(0)

with ThreadPool(1) as pool:
    list(pool.imap(do_thing, [99]))
with ThreadPool(1) as pool:
    list(pool.imap(do_thing, [99]))
with Pool(1) as pool:
    list(pool.imap(do_thing, [99]))
with Pool(1) as pool:
    list(pool.imap(do_thing, [99]))

You will find that the ThreadPools print consistent integers across multiple runs, but the Pools don't. I get from here that we can't guarantee in which order the processes will be created so in many cases it would be impossible to guarantee consistent results. But in my case, there are only so many orders this could happen in, but there are many different outcomes. So I don' think that the linked post is explaining what's happening here.

Note that I want to "propagate" the seed, not reseed with the same number. I don't want the outputs to be all the same.

Also, it looks like this might be possible with a manager, but just wondering if there's an easier "obvious" way that I don't know about.




mercredi 24 mars 2021

find random number between -7 and -12 with javascript [duplicate]

I got this javascript code that returns a random integer number between 1 and 10.

I got a problem making it return a random number between -7 and -12.

You gotta bail me out of this one, please...

const a = Math.floor(Math.random() * (10 - 1)) + 1;
console.log(`Random value between 1 and 10 is ${a}`);



Randomly select fraction of numbers in array, add/subtract some percentage of their original values, and rewrite array

I'm reading in an array of numbers arr from a csv file (1000+ entries). I figured out a way to replace a user-specified fraction of these numbers err_frac with random values drawn from a uniform distribution. For example:

err_frac = 0.2
swap_count = math.floor(err_frac * len(arr))
swap = np.random.uniform(low=np.amin(arr), high=np.amax(arr), size=swap_count)
arr.flat[np.random.choice(len(arr), swap_count, replace=False)] = swap

Now I'd like to take a randomly chosen fraction of these numbers and add or subtract some user-specified percentage of its original value. For example, if both percentages were 20%, the script would:

(a) randomly select 20% of the numbers in the original array

(b) if the chosen number was greater than the mean of the dataset, subtract 20% of its original value

(c) if the chosen number was smaller than the mean of the dataset, add 20% of its original value

(d) rewrite the modified values to a new array

Seems easy enough but I'm running into a mental block here. I tried something like this, but it's failing miserably:

for nz in range(1, len(arr)):
    nzc = nz - 1
    if arr[nzc] > 0.5 * np.amax(arr):
        swap = arr[nzc] - err_frac * arr[nzc]
        arr.flat[np.random.choice(len(arr), math.floor(arr[nzc]), replace=False)] = swap
    elif arr[nzc] < 0.5 * np.amax(arr):
        swap = arr[nzc] + err_frac * arr[nzc]
        arr.flat[np.random.choice(len(arr), math.floor(arr[nzc]), replace=False)] = swap

Ideas?




Randomly select timeframes as tuples from a list of time points

I am writing a program to split a video into a specified number of subclips, so I need a list of tuples [(0,t1),(t1,t2),(t2,t3),...,(tn,T)] where T is the length of the video (in this case the number of subclips is n+1, which should be an input from user).

Assume that I have a list of lists of floating point numbers, like the following:

time_pt_nested_list = 
[[0.0, 6.131, 32.892, 43.424, 46.969, 108.493, 142.69, 197.025, 205.793, 244.582, 248.913, 251.518, 258.798, 264.021, 330.02, 428.965],
 [11.066, 35.73, 64.784, 151.31, 289.03, 306.285, 328.7, 408.274, 413.64],
 [48.447, 229.74, 293.19, 333.343, 404.194, 418.575],
 [66.37, 242.16, 356.96, 424.967],
 [78.711, 358.789, 403.346],
 [84.454, 373.593, 422.384],
 [102.734, 394.58],
 [158.534],
 [210.112],
 [247.61],
 [340.02],
 [365.146],
 [372.153]]

All the returned tuples should only contain the floating point numbers inside the nested list above. The first list in the nested list indicates that I want to assign the highest probability to them to be sampled and appear in the returned tuples, the second list a slightly lower probability, etc. In other words, the probabilities for the elements of time_pt_nested_list[idx] to appear in the returned tuples should decrease when idx increases. The exact details of these probabilities are not important, but it would be nice if the user can input a parameter that controls how fast the probability decays when idx increases.

The returned tuples are timeframes that should exactly cover the entire video and should not overlap. 0 and T may not necessarily appear in time_pt_nested_list (but they may). Are there nice ways to implement this? I would be grateful for any insightful suggestions.

For example if the user inputs 6 as the number of subclips, then this will be an example output:

[(0.0, 32.892), (32.892, 64.784), (64.784, 229.74), (229.74, 306.285), (306.285, 418.575), (418.575, 437.47)]

All numbers appearing in the tuples appeared in time_pt_nested_list, except 0.0 and 437.47. (Well 0.0 does appear here but may not in other cases) Here 437.47 is the length of video which is also given and may not appear in the list.