lundi 28 février 2022

Return minimum distance among random points in a square [0,1]^2 in Python [closed]

There is n points in the sqaure [0,1]^2, t is the number of iterations, and the points will be moving when t changes from 0 to 1,2,3... x is the a maximal move of a point in one of four random directions: (−1,0),(1,0),(0,−1),(0,1).

import numpy as np
import random

def list_min_distance(n, x, t): 
    """ 
    n is number of points.
    x is a maximal move
    t is the number of iterations
    """
    **Return a list of min distances**: For example, when t = 1,2,3...how is the min distance like.

My project is to to examine and plot the diagram. I am stuck here, can anyone help?




onClick rolling number animations in javascript

im starting to figure out how I can do rolling numbers animation in javascript onClick.

So basically I have:

const button = document.getElementById("generate");

button.onclick = function generate(){

const randomNum = Math.floor((Math.random() * 10000) + 1);

const el = document.getElementById('ranNum');

el.innerHTML = randomNum;
}

And what I would like to do is have numbers from from their current position if the person pressing a button and got 2434 and the next time the press the button the next answer would be like 132, but there would be a rolling up animation to get the next number of 132, and so on..

I seen this on google when I asked for a number generator, and their animation was sick. But sadly no documentation on googles scrolling numbers.

Does anyone have any ideas where I can go try and find documentation?

Thanks!




How can I randomize a video to play after another by pressing a key on Processing?

I'm quite new to Processing.

I'm trying to make Processing randomly play a video after I clear the screen by mouseclick, so I create an array that contain 3 videos and play one at a time.

Holding 'Spacebar' will play a video and release it will stop the video. Mouseclick will clear the screen to an image. The question is how can it ramdomize to another video if I press spacebar again after clear the screen.

I've been searching all over the internet but couldn't find any solution for my coding or if my logic is wrong, please help me.

Here's my code.

int value = 0;
PImage photo;
import processing.video.*;


int n = 3; //number of videos

float vidN = random(0, n+1);
int x = int (vidN);

Movie[] video = new Movie[3];
int rand = 0;

int index = 0;

void setup() {
  size(800, 500);
  frameRate(30);
  
  video = new Movie[3];
  video[0] = new Movie (this, "01.mp4");
  video[1] = new Movie (this, "02.mp4");
  video[2] = new Movie (this, "03.mp4");


  photo = loadImage("1.jpg");
}


void draw() {

}


void movieEvent(Movie video) {
  video.read();
}

void keyPressed() {

  if (key == ' ') {
    image(video[rand], 0, 0);
    video[rand].play();
  }
  
}

void mouseClicked() {
  if (value == 0) {
    video[rand].jump(0);
    video[rand].stop();
    background(0);
    image(photo, 0, 0);
  }
}



Generating random numbers on different servers at the same time and have it be reasonably even

I have a Python script that runs on all of my servers at the same time via cron. I would like to have a fairly even distribution of random numbers across all servers. Clearly, if it is based on timestamp then it probably won't be as evenly distributed as I would like. Server name? IP? PID?

My research has found nothing on this subject.




Will changing the number of threads affect the output?

If you have a code (which is parallelized by OpenMP) that uses some random function inside of a parallel region, is it possible that changing the number of threads changes the outcome?




dimanche 27 février 2022

Make a large list and choose a random one unity [closed]

I want to make a large list of strings (around 2000-3000) and choose a random one in unity how can I do this?




python dictionary is overwriting itself in a for loop which should not be possible

I am having trouble understanding why the python function does not output a dictionary with the appended shuffled lists but instead creates a dictionary of only the last list created. I have rewritten the function many times but continue to run into the same problem.

#simple schedule fitness test run
#imports
from itertools import permutations
import random
import numpy as np

#create teachers with classes and students with classes
brian_classes = ['akstuddies', 'sci_ms', 'sci_ms', 'physics', 'comp_sci', 'conf']
becky_classes = ['akstuddies', 'lit_ms', 'lit_ms', 'lit', 'conf', 'debate']
teachers = [brian_classes, becky_classes]
#creates inital population of n schedules by shuffling the schedule of each teacher n times
def initial_population(teachers_list, population_size):
    schudule_list_population = {}
    for i in range(0, population_size):
        shuffled_teachers = []
        schudule_list_population[i] = [teacher for teacher in teachers_list]
        for teacher in schudule_list_population[i]:
            np.random.shuffle(teacher)
            shuffled_teachers.append(teacher)
            #print(teacher)
        schudule_list_population[i] = shuffled_teachers
        print(schudule_list_population)
    return schudule_list_population

print(initial_population(teachers, 2))

output:

{0: [['akstuddies', 'conf', 'physics', 'sci_ms', 'sci_ms', 'comp_sci'], ['lit_ms', 'lit', 'conf', 'debate', 'lit_ms', 'akstuddies']]}

{0: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']], 1: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']]}

{0: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']], 1: [['sci_ms', 'physics', 'comp_sci', 'akstuddies', 'sci_ms', 'conf'], ['conf', 'lit_ms', 'lit_ms', 'akstuddies', 'debate', 'lit']]}



how to make a random number a multiple of 25

I am working on a snake game where I want the apple to randomize its x and y coordinates, but it doesn't align with my background (a 20x20 grid).

Is there a way to make a random integer a multiple of a preset number?

if it helps, here's a part of the random number generator:

if snake_x == apple_x and snake_y == apple_y:
    apple_x = r.randint (0, 475)
    apple_y = r.randint (0, 475)



Generate double random numbers? C++ [duplicate]

I'm a first semester comp sci student working on an assignment. The assignment is seemingly asking for double random numbers however the professor has only shown how to find integers from a random number generator using rand and srand. Any tips on this? a. Write a function to simulate a single shot. It should use the following declaration:

void shoot(bool &targetAlive, double accuracy);

This would simulate someone shooting at targetAlive with the given accuracy by generating a random number between 0 and 1. If the random number is less than accuracy, then the target is hit and targetAlive should be set to false. You need to generate random numbers.

For example, if Bob is shooting at Charlie, this could be invoked as:

shoot(charlieAlive, 1.0);

Here, charlieAlive is a Boolean variable that indicates if Charlie is alive. Test your function using a driver program before moving on to step b.




How do I make a label disappear after 5 seconds python, Tkinter?

I am making a dice roller, and I wish to make the result of the dice roll disappear after 5 seconds, can anyone help?

from tkinter import *
import random
root=Tk()
root.geometry('700x500')
root.title("Dice roller")
bg = PhotoImage(file = "background.png")
Label1 = Label(root, image = bg)
Label1.place (x = 0, y=0)
l = Label(root, text="Welcome to the dice roller, select the dice you want to roll!",bg = "gold",fg = "goldenrod4", relief = "raised", font=("Arial Bold",12))
l.pack()


def buttonFunction1():
    r1 = random.randint(1, 6)
    L = Label(root, text= r1, bg = "red", relief = "solid", cursor = "target", font = ("Arial Bold", 10)) 
###That was the label I want to make disappear after 5 seconds###
    L.place(relx = 0.8, rely = 0.14, anchor = 'sw') 
b = Button(root, text="cube dice", command= buttonFunction1)
b.pack()



samedi 26 février 2022

How to print elements of a random list next to other elements in order?

Can anyone help me figure out how to print elements of a randomly created list next to chosen numbers in order? The numbers are book names and the numbers that are random are book prices and I need those prices to be returned next to book names after you have chosen what books you are going to buy

Here is my code:

import random

print("Books for sale")

m = 25
price_list = []

for s in range(3, m + 1):
    price_list.append(s)

i = 0
books = 1
n = 10
book_list = []

while i < n:
  prices = random.sample(price_list, 1)
  print(f"{books}: {prices}")
  i += 1
  books += 1

print("Enter, which books are you going to buy (1 - 10) ==>")
numbers = [int(s) for s in input().split()]
print("Chosen books: ")

for el in range(len(numbers)):
    print(f'{numbers[el]}: {price_list.count(el)}')

It returns something like this:

Books for sale
1: [8]
2: [25]
3: [5]
4: [24]
5: [12]
6: [24]
7: [16]
8: [3]
9: [21]
10: [13]
Enter, which books are you going to buy (1 - 10) ==>

2 5 7
Chosen books: 
2: 0
5: 0
7: 0

I would like it to be more like:

Chosen books: 
2: 25
5: 12
7: 16



Can people see other NFT images in the same IPFS folder?

I'm currently creating an RNG NFT that can be bought on my website. However, i don't really know when to mint the NFT. Should it be minted to the buyer's wallet after it is bought or after the whole NFT collection is sold. My concern is if the minting is done right after the user bought the NFT, then the buyer can see the NFT metadata in the contract which means he can see the IPFS folder.

ipfs://{CID}/001.png

If this is the case, it means he can see other NFT images in that folder based on the IPFS base URI, so he can track when to buy the NFT to get the rare one. Is this the right way to store RNG NFT images? or should it be minted after sales so people cannot see the IPFS uri before all of the NFTs are sold? or is there another way to mint this RNG NFTs?




vendredi 25 février 2022

random link on button press keeps concatenating

(sorry if the title sucks i spent like 30 minutes trying to word i physicaly cant like what do you put)

hey guys so i have this code here and the goal is that i can generate a random newgrounds song every time the generate button is clicked. i can get it working without noticeable flaws (unless you click the scroll wheel to make a new tab in which case the illusion will fail) but the problem is that i wanted it to work without needing a refresh. so i made the button create a new tab instead but now it appends the random number and ive ran out of question i can ask google so can someone either help me fix the fact it appends the number to the new link and not the base link or help me make the goal of a random newgrounds link generator in a more efficient way? if anything here looks bad then just know i am a beginner when it comes to html and javascript i spent most of my coding life on scratch. if some of the code looks good then i probably copied it

<!DOCTYPE html>
<html> 

<head> 
<link rel="stylesheet" href="CSS1.css">

<script>
  window.onclick = () => {
    document.querySelectorAll("a").forEach(link =>
     link.setAttribute("href", link.getAttribute("href") + Math.floor(Math.random() * 111392.8) + 1)
    );
  };
</script>

</head>

<title>
Newgrounds Song Generator
</title> 

<body>

<h1>Click the button to visit a random song!</h1>

<a href="https://www.newgrounds.com/audio/listen/" target="_blank">
<button>
Generate
</button>
</a>

</body>

</html>



Why is my if statement returning an unreasonable value?

This is my first post so I hope I'm not doing anything wrong.

I am trying to test the usefulness of a function I wrote that returns a random character in a string. So, if my string is "aeiou", it would ideally, at random, return either "a", "e", "i", "o", or "u", and each string would appear about 20% of the time.

I wrote some more code to go through the function a bunch of times and print out the result. Here it is:

import random

number = 100000

def random_char(chars):
    char = chars[random.randint(0, (len(chars) - 1))]
    return char

a = 0
e = 0
i = 0
o = 0
u = 0

for i in range(0, number):
    new_char = (random_char("aeiou"))
    if new_char == ("a"):
        a = a + 1
    elif new_char == ("e"):
        e = e + 1
    elif new_char == ("i"):
        i = i + 1
    elif new_char == ("o"):
        o = o + 1
    elif new_char == ("u"):
        u = u + 1

list = [a, e, i, o , u]
list_str = ["a", "e", "i", "o", "u"]
i = 0

while i < len(list):
    print("Group " + (list_str[i]) + " has " + str(list[i]) + " tokens.")
    i = i + 1

My output is what I would expect for strings "a", "e", "o", and "u", (about 20,000 tokens each), but for "i" I'm getting around 99,999 each time, which should be impossible. I am confused!

In addition, if there is anything I could be doing better in terms of code/code efficiency, please say so! I'm a beginner.




How fix the error from generating random sample from distribution and how reduce high mean square error (MSE)

I want to generate random sample from the following discrete distribution, so I used the CDF technique i.e F(x)=p So, I

#The CDF of continuous distribution is as follows
cdf.con<- function(q, t, a, lower.tail = TRUE, log.p = FALSE)
{
  stopifnot(t > 0, a > 0)
  p <- t / (t + 1)
  if(lower.tail)
  {
    cdf <- p * pexp(q, rate = t, lower.tail = TRUE) + (1 - p) * pgamma(q, shape = a, rate = t, lower.tail = TRUE)
  }
  else
  {
    cdf <- p * pexp(q,  rate = t, lower.tail = FALSE) + (1 - p) * pgamma(q, shape = a, rate = t, lower.tail = FALSE)
  }
  if(log.p) return(log(cdf)) else return(cdf)
}

#PMF 
#************************
pmf<- function(x, t, a, log = FALSE)
{
  stopifnot(t > 0, a > 0, x >= 0)
  if(!isTRUE(all(x == floor(x)))) stop("'x' must only contain nonnegative integers")
  if(log)
  {
    log(cdf.con(q = x, t, a, lower.tail = FALSE) - cdf.con(q = x + 1, t, a, lower.tail = FALSE))
  }
  else
  {
    cdf.con(q = x, t, a, lower.tail = FALSE) - cdf.con(q = x + 1, t, a, lower.tail = FALSE)
  }
}

#CDF $ (1-CDF) of discrete random variable
#************************************************
cdf.dic<- function(q, t, a, lower.tail = TRUE, log.p = FALSE)
{
  if(lower.tail)
  {
    cdf <- sapply(1 : length(q), function(i) sum(pmf(x = 0 : q[i], t, a, log = FALSE)))
  }
  else
  {
    cdf <- 0.1e1 - sapply(1 : length(q), function(i) sum(x = pmf(0 : q[i], t, a, log = FALSE)))
  }
  if(log.p) return(log(cdf)) else return(cdf)
}



# Generate random sample
#******************************
#Quantile of Cont.
qntf.con<- function(p, t, a, lower.tail = TRUE, log.p = FALSE, L = 1e-4, U = 50)
{
  stopifnot(t > 0, a > 0)
  if(lower.tail)
  {
    fx <- function(p)
    {
      tryCatch(uniroot(function(q) cdf.con(q, t, a, lower.tail = TRUE, log.p = FALSE) - p, lower = L, upper = U)$root, error = function(e) NaN)
    }
    qtf <- sapply(p, fx)
    if(log.p) return(log(qtf)) else return(qtf)
  }
  else
  {
    fx <- function(p)
    {
      tryCatch(uniroot(function(q) cdf.con(q, t, a, lower.tail = FALSE, log.p = FALSE) - p, lower = L, upper = U)$root, error = function(e) NaN)
    }
    qtf <- sapply(p, fx)
    if(log.p) return(log(qtf)) else return(qtf)
  }
}

I generate random sample from discrete distribution by making (floor ) to quantile function of continuous distribution as follows

# Quantiles and random sample generator from discrete r.v
#******************************************************
qntf.dis<- function(p, t, a, lower.tail = TRUE, log.p = FALSE)
{
  stopifnot(t > 0, a > 0)
  if(lower.tail)
  {
    qtf <- floor(qntf.con(p, t, a, lower.tail = TRUE, log.p = FALSE))
  }
  else
  {
    qtf <- floor(qntf.con(p, t, a, lower.tail = FALSE, log.p = FALSE))
  }
  if(log.p) return(log(qtf)) else return(qtf)
}

#generate r.s from discrete distribution as follows
r.s<- function(n, t, a) # For discrete r.v
{
  stopifnot(t > 0, a > 0)
  
  qntf.dis(p = runif(n), t, a, lower.tail = TRUE, log.p = FALSE)
}

#generate random sample from discrete r.v, I got NAN in some values
set.seed(110)
r.s(n=200, t=2, a=0.42) #produce NAN
#For the following set of parameters, I did not get NAN 
set.seed(110)

r.s(n=2000, t=0.5, a=2) # do not produce NAN

can someone tell me why NAN appears ? and how can we fix this?

My Second question is, I got high Mean square error

 myx <- r.s(n, t=theta1[1], a=theta1[2]) # generate sample from discrete distribution
    myx<- myx[!is.na(myx)]
# the log LHF
####################
loglik <- function(param) {
      t <- param[1]
      if(t<=0){return(NaN)}
      a <- param[2]
      if(a<=0){return(NaN)}
      sum(pmf(myx, t=t, a= a, log=TRUE))
      # log likelihood function is sum(ln(probability mass function))
    }# logLikFun
    library(maxLik)
    mle <-  maxLik(loglik, start=c(t= 0.5, a= 2))
    summary( mle )



   #Compute MSE
###########################
        #to compute it first compute the bias
        bias_theta= coef(mle)[1]- 0.5
        bias_alpha= coef(mle)[2]- 2
        MSE= c(vcov(mle)[1] + bias_theta^2, vcov(mle)[4] + bias_alpha^2)
        
    MSE
          t      a 
    1.824092 2.845212 

How can I reduce the MSE of estimator especially for alpha "a" parameter?




jeudi 24 février 2022

Generating a number from an uneven distribution in js

I'm trying to make a number generator, where the ods of getting a number between 1 and 2 are bigger than 2 and 4 etc. However, I can't get my mind over how to do this. I've linked a graph of how the distribution should look like when graphed. Image




Quantile function error and high mean square error (MSE)

I want to generate random sample from the following discrete distribution, so I used the CDF technique i.e F(x)=p So, I

#The CDF of continuous distribution is as follows
cdf.con<- function(q, t, a, lower.tail = TRUE, log.p = FALSE)
{
  stopifnot(t > 0, a > 0)
  p <- t / (t + 1)
  if(lower.tail)
  {
    cdf <- p * pexp(q, rate = t, lower.tail = TRUE) + (1 - p) * pgamma(q, shape = a, rate = t, lower.tail = TRUE)
  }
  else
  {
    cdf <- p * pexp(q,  rate = t, lower.tail = FALSE) + (1 - p) * pgamma(q, shape = a, rate = t, lower.tail = FALSE)
  }
  if(log.p) return(log(cdf)) else return(cdf)
}

#PMF 
#************************
pmf<- function(x, t, a, log = FALSE)
{
  stopifnot(t > 0, a > 0, x >= 0)
  if(!isTRUE(all(x == floor(x)))) stop("'x' must only contain nonnegative integers")
  if(log)
  {
    log(cdf.con(q = x, t, a, lower.tail = FALSE) - cdf.con(q = x + 1, t, a, lower.tail = FALSE))
  }
  else
  {
    cdf.con(q = x, t, a, lower.tail = FALSE) - cdf.con(q = x + 1, t, a, lower.tail = FALSE)
  }
}

#CDF $ (1-CDF) of discrete random variable
#************************************************
cdf.dic<- function(q, t, a, lower.tail = TRUE, log.p = FALSE)
{
  if(lower.tail)
  {
    cdf <- sapply(1 : length(q), function(i) sum(pmf(x = 0 : q[i], t, a, log = FALSE)))
  }
  else
  {
    cdf <- 0.1e1 - sapply(1 : length(q), function(i) sum(x = pmf(0 : q[i], t, a, log = FALSE)))
  }
  if(log.p) return(log(cdf)) else return(cdf)
}



# Generate random sample
#******************************
#Quantile of Cont.
qntf.con<- function(p, t, a, lower.tail = TRUE, log.p = FALSE, L = 1e-4, U = 50)
{
  stopifnot(t > 0, a > 0)
  if(lower.tail)
  {
    fx <- function(p)
    {
      tryCatch(uniroot(function(q) cdf.con(q, t, a, lower.tail = TRUE, log.p = FALSE) - p, lower = L, upper = U)$root, error = function(e) NaN)
    }
    qtf <- sapply(p, fx)
    if(log.p) return(log(qtf)) else return(qtf)
  }
  else
  {
    fx <- function(p)
    {
      tryCatch(uniroot(function(q) cdf.con(q, t, a, lower.tail = FALSE, log.p = FALSE) - p, lower = L, upper = U)$root, error = function(e) NaN)
    }
    qtf <- sapply(p, fx)
    if(log.p) return(log(qtf)) else return(qtf)
  }
}

I generate random sample from discrete distribution by making (floor ) to quantile function of continuous distribution as follows

# Quantiles and random sample generator from discrete r.v
#******************************************************
qntf.dis<- function(p, t, a, lower.tail = TRUE, log.p = FALSE)
{
  stopifnot(t > 0, a > 0)
  if(lower.tail)
  {
    qtf <- floor(qntf.con(p, t, a, lower.tail = TRUE, log.p = FALSE))
  }
  else
  {
    qtf <- floor(qntf.con(p, t, a, lower.tail = FALSE, log.p = FALSE))
  }
  if(log.p) return(log(qtf)) else return(qtf)
}

#generate r.s from discrete distribution as follows
r.s<- function(n, t, a) # For discrete r.v
{
  stopifnot(t > 0, a > 0)
  
  qntf.dis(p = runif(n), t, a, lower.tail = TRUE, log.p = FALSE)
}

#generate random sample from discrete r.v, I got NAN in some values
set.seed(110)
r.s(n=200, t=2, a=0.42) #produce NAN
#For the following set of parameters, I did not get NAN 
set.seed(110)

r.s(n=2000, t=0.5, a=2) # do not produce NAN

can someone tell me why NAN appears ? and how can we fix this?

My Second question is, I got high Mean square error

 myx <- r.s(n, t=theta1[1], a=theta1[2]) # generate sample from discrete distribution
    myx<- myx[!is.na(myx)]
# the log LHF
####################
loglik <- function(param) {
      t <- param[1]
      if(t<=0){return(NaN)}
      a <- param[2]
      if(a<=0){return(NaN)}
      sum(pmf(myx, t=t, a= a, log=TRUE))
      # log likelihood function is sum(ln(probability mass function))
    }# logLikFun
    library(maxLik)
    mle <-  maxLik(loglik, start=c(t= 0.5, a= 2))
    summary( mle )



   #Compute MSE
###########################
        #to compute it first compute the bias
        bias_theta= coef(mle)[1]- 0.5
        bias_alpha= coef(mle)[2]- 2
        MSE= c(vcov(mle)[1] + bias_theta^2, vcov(mle)[4] + bias_alpha^2)
        
    MSE
          t      a 
    1.824092 2.845212 



Generating random result based on previous result

I want to generate random result with weights based on the previous result.

I am generating random results with weights in the following manner

a = [1, 2, 3, 4, 5, 6]
results = random.choices(a, weights=(
    (10, 20, 30, 30, 10, 6)), k=100)

print (results[0:100]

What I want to do is if results[n] = 1, the next result cannot be 6(i.e. it can be between 1 and 5). I am new to this page and python. Any help would be useful




Netlogo - random choice

I am new to programming and I would really appreciate the help. In this model, I want to create a company that can randomly choose btw 2 choices if a certain condition is met. What would be the best way to do it? I tried this but it is not working.

    if profit < 0 [
set color red
let choice random 2 (
  choice = 0 [ move-to min-one-of patches [costs]] 
  choice = 1 [ set price (price + 1) ])
]

Thanks for the help!




mercredi 23 février 2022

Weibull weighted randomization in Python

How to use Weibull function to generate a random number that it follows between a given range? I know there is an inbuilt function weibull_min.rvs(k, loc=0, scale=lam, size=n,random_state=5) that generates n number of points when given shape and scale parameters but I want it to generate random numbers within a range, not the entire dataset.

Note: Range might be integer set like between 2 and 3. Generate random numbers that follow Weibull distribution.




How to implement a thread-safe random

Trying to find and understand the best approach to implement a thread-safe number generator in .NET Core 2.x or higher

First Iv'e found this - https://web.archive.org/web/20160326010328/http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx

After reading through it seems to me like there are couple of "good" ways -

  1. ThreadStatic Random instance, with a global random instance to generate seeds
  2. ThreadStatic Random instance, with a global RNGCryptoServiceProvider to generate seeds

Where basically you choose the latter if a strong cryptographically random is a requirement.

After some additional research I found out that since .NET Core 2.x System.Random class was revised, therefore the default seed generation which is no longer primary dependent on the system timer. (https://blogs.siliconorchid.com/post/coding-inspiration/randomness-in-dotnet)

Questions -

  1. How is this affect the implementation of a thread-safe random class?
  2. Initially having a global static Random instance as a seed generator with a lock resulted with about 16ms timespan of same results per thread due to OS limitation, is this no longer the case? do I even need a global seed generator?
  3. Knowing all of this, when should I use a cryptographic class (RandomNumberGenerator) instead of System.Random ?



What is the correct way to generate a CSPRNG string with specific rules in PHP?

Assume you want to generate a safe, random password with at least 8 characters in PHP, containing at least one uppercase, lowercase, number and special character.

I've read through some answers, basically all of them refer to here, this is why I choose RandomLib.

Unfortunately it doesn't seem to be possible to pass the "rules" to the generator.

My solution now is:

    $factory = new \RandomLib\Factory;
    $generator = $factory->getLowStrengthGenerator();
    $nums = $generator->generateString(random_int(1, 5), '0123456789');
    $capsStr = $generator->generateString(random_int(1, 6 - strlen($nums)), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
    $lowerStr = $generator->generateString(random_int(1, 7 - strlen($nums) - strlen($capsStr)), 'abcdefghijklmnopqrstuvwxyz');
    $special = $generator->generateString(random_int(1, 8 - strlen($nums) - strlen($capsStr) - strlen($lowerStr)), '+-!$%&#*_.;:<>' );
    $password = str_shuffle($nums . $capsStr . $lowerStr . $special);
    var_dump($password);

But I have a feeling this is inefficient and could be done faster. I get a "wallclock" execution time of around 0.025 Seconds on average. Furthermore I'm adding the "unsafe" random_int method, which I tried to prevent by using RandomLib

Is there a safer/faster way to achieve this?




How to add random number of falling balls in pygame?

Here is some code for random falling balls, I am able to generate one falling ball. Having hard time to randomize the number of falling balls, also they need to be some random delays falling from "sky". Could you tell how to do it ?

import pygame
import random

pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
 
robot = pygame.image.load("robot.png")
 
y1 = 0
y2 = 0
speed1 = 1
speed2 = 2
 
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    screen.fill((0, 0, 0))
    robots = []
    screen.blit(robot, (100, y1))

    y1 += speed1

    if y1 >= 640:
        y1 = 0

    pygame.display.flip()

    clock.tick(60)



mardi 22 février 2022

Create unique rows in Excel with limited data to be used in multiple columns

I would appreciate help how to solve this problem i have in Excel.

I would like to create 100 unique rows with 5 columns, where columns should contain unique numbers from a predefined list (1, 2, 3, 4, 5, 6, 7). Same number can only be used once in the row.

How can I do this with a formula? Will need to populate similar unique rows with fewer columns available as well at a lager stage so a generic approach would be appreciated.

Please see attached example image.

Hope this question make sense what I want to accomplish. Thanks in advance for your help!

/Chris

example




Random permutations generation with non-repeating values at each index

There was one problem:

Given a natural number sequence S of size n, [1,2,3,4....n], the task is to generate n random permutations but the catch is that the values shouldn't repeat at any index among all permutations.

For example, given n=3, S=[1,2,3], the possible result can be

1.[3,1,2]

2.[2,3,1]

3.[1,2,3]

Output like below is not acceptable as permutation 1 and 3 have same second value as 1

1.[3,1,2]

2.[2,3,1]

3.[2,1,3]

Another restriction was this needs to be solved with O(n) space complexity.




lundi 21 février 2022

How to generate a random distribution with probability

I tried to use Math.random() for load testing (1M requests in server per minute) and the percentage of requests that generate true is different from the percentage expected. Logic is basically if Math.random() < 0.95 to simulate a random distribution of 95% of the instances being true.




How to randomly remove spaces from a tensor of strings in Tensorflow

There is a Tensor of strings, for each string I want to remove n spaces randomly where n <= the number of the spaces in that string.

import tensorflow as tf

strings_with_spaces = tf.constant([b'A B C D E F', b'1 2 3 4 5 6'])
remove_spaces_randomly = None
T = tf.map_fn(remove_spaces_randomly, strings_with_spaces)

I expect the output to be something like:
['A BC D EF', '1 2 34 5 6']



Would it be possible to select random rows with a little preference for a specific column?

I would like to get a random selection of records from my table but I wonder if it would be possible to give a better chance for items that are newly created. I also have pagination so this is why I'm using setseed

Currently I'm only retrieving items randomly and it works quite well, but I need to give a certain "preference" to newly created items.

Here is what I'm doing for now:

SELECT SETSEED(0.16111981), RANDOM();

I don't know what to do and I can't figure what can be a good solution without being an absolute performance disaster.




dimanche 20 février 2022

Random word generator never prints fourth word in array - Javascript [duplicate]

I have three random word generators on the same page. One prints an adjective, one a verb, and one a noun upon clicking their respective buttons. If two of the arrays have three words, and one array has four words, why wont the fourth word in the third array every print?

<form>
  <div id="displayAdjective"></div>
  <input type="button" value="display adjective" onclick="randomAdjective()" class="wordFormButton">
</form>
<form>
  <div id="displayVerb"></div>
  <input type="button" value="display verb" onclick="randomVerb()" class="wordFormButton">
</form>
<form>
  <div id="displayNoun"></div>
  <input type="button" value="display noun" onclick="randomNoun()" class="wordFormButton">
</form>

I'm unsure why the 4th word in the nouns array never prints.

adjectives = ["adjectiveOne", "adjectiveTwo", "adjectiveThree"];

verbs = ["verbOne", "verbTwo", "verbThree"];

nouns = ["nounOne", "nounTwo", "nounThree", "nounFour"];

function randomAdjectiveAlt() {
  var randomAdjective = Math.floor(Math.random() * adjectives.length);
  document.getElementById('displayAdjective').innerHTML = adjectives[randomAdjective];
}

function randomVerbAlt() {
  var randomVerb = Math.floor(Math.random() * adjectives.length);
  document.getElementById('displayVerb').innerHTML = verbs[randomVerb];
}

function randomNounAlt() {
  var randomNoun = Math.floor(Math.random() * adjectives.length);
  document.getElementById('displayNoun').innerHTML = nouns[randomNoun];
}

Here's a link to the jsfiddle showing the full example.




Forward declaration of class and still Error: Variable has incomplete type

I have defined two classes : (1) class Point_CCS_xy , and (2) random_Point_CCS_xy_generator. I would like to define a function in Point_CCS_xy class which makes use of random_Point_CCS_xy_generator class to generate random points on a cartesian coordinate system within a range Min and Max, both of which have been defined as long double. I have already forward declared class random_Point_CCS_xy_generator, however I get an Variable has incomplete type random_Point_CCS_xy_generator error on this line random_Point_CCS_xy_generator rpg(Min, Max); and also this error Member reference base type 'vector<Point_CCS_xy> (size_t)' (aka 'vector<Point_CCS_xy> (unsigned long long)') is not a structure or union, on this line Point_CCS_xy_vec.push_back(p);.

MWE

#include<iostream>
#include<fstream>
#include<functional>
#include<algorithm>
#include<vector>
#include<deque>
#include<queue>
#include<set>
#include<list>
#include<limits>
#include<string>
#include<memory>

using namespace std;
typedef long double ld;

class random_Point_CCS_xy_generator;

class Point_CCS_xy{
private:
    long double x_coordinate_ {0.0};
    long double y_coordinate_ {0.0};
public:
    Point_CCS_xy () = default;
    Point_CCS_xy(long double x, long double y): x_coordinate_(x), y_coordinate_(y) {}
    ~Point_CCS_xy() = default;

    // copy constructor through construction delegation method
    Point_CCS_xy(const Point_CCS_xy& cpyObj) : Point_CCS_xy(cpyObj.x_coordinate_, cpyObj.y_coordinate_)
    {

    }



 // Copy and Mover Assignment Operators, 
 // also setters and getters, and a few utility functions come here inlcuding:
friend ostream& operator<<(ostream& os, const Point_CCS_xy& pnt);


// Problematic Function -> source of ERRORS
vector<Point_CCS_xy> Random_Point_CCS_xy(long double Min, long double Max, size_t n) {
        random_Point_CCS_xy_generator rpg(Min, Max);
        vector<Point_CCS_xy> Point_CCS_xy_vec(size_t);
        for (size_t i = 0; i < n; ++i){
            Point_CCS_xy p = Point_CCS_xy(rpg());
            Point_CCS_xy_vec.push_back(p);
        }
        return Point_CCS_xy_vec;
    }
};

ostream& operator<<(ostream& os, const Point_CCS_xy& pnt) {
    os << "X: " << setw(10)<< left << pnt.x_coordinate_ << " Y: " << setw(10)<< left << pnt.y_coordinate_;
    return os;
}

class random_Point_CCS_xy_generator {
public:
    random_Point_CCS_xy_generator(long double min, long double max)
            : engine_(std::random_device()()), distribution_(min, max) {}

    Point_CCS_xy operator()() {
        long double x = distribution_(engine_);
        long double y = distribution_(engine_);
        return Point_CCS_xy(x, y);
    }

    std::mt19937 engine_;
    std::uniform_real_distribution<double> distribution_;
};

As I am a newbie in programming, any idea would be highly appreciated.




Randomly generate += or -= javascript

Hi i am trying to assign either += or -= to an object position. Firstly I have random math choosing a number:

var min = 9;
 var max = 11;
 var pos = Math.floor(Math.random() * (max - min + 1)) + min;

I am trying to add the out come of pos to this._target.position.z and this._target.position.x but I want it to be randomly either added or subtracted

so the random out come should be for the Z position should be either:

this._target.position.z += pos;

or

this._target.position.z -= pos;

and then for the X position should be either:

this._target.position.x += pos;

or

this._target.position.x -= pos;

thanks in advance.




How can I sort using a comparator with ties broken randomly?

I'm building a program that simulates a sports league, and, oftentimes, I want to sort teams by points, goal differential, etc. to determine things like which team gets promoted or which team gets preferential seeding in a tournament. But, sometimes, teams will be tied on all the criteria that I want to use, and I would like those ties to be broken randomly. I was previously using teams' ids (which are unique ints) to break ties, but I'd like to make it so that no team gets consistent preferential treatment in this sorting. I know that if I just let Java decide which of the tied teams will be placed in front of the other, it'll be very unpredictable, but I don't trust it to be actually random, and I'm worried that it'd inadvertently give some teams an advantage.

I've been using Collections.sort() with comparators to do my sorting, and I recently just went for it, and switched my comparators to use a random number as the final tiebreaker rather than the team ids. Here is the comparator in question:

public static final Comparator<Team> pointsGDRand = new Comparator<Team>() {
    public int compare(Team a, Team b) {
        int result = b.getStats().getPts() - a.getStats().getPts();
        if (result == 0) {
            result = b.getStats().getGD() - a.getStats().getGD();
            if (result == 0) {
                result = R.boolNum();
            }
        }
        return result;
    }
};

I think the getter functions are self explanatory, but here's that random function:

public static int boolNum() {
    return r.nextBoolean() ? 1 : -1;
}

But, just a bit ago (it look a long time for this error to pop up), I got this error:

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!

I've read a little bit, and I think that the problem is likely that I had some instance where it figured out that A > B and B > C, but also A < C. This sheds some light on why it took so long for this error to pop up (it did maybe 20,000 sorts before it popped up with this error), because 2 teams getting the exact same score on all criteria seems like a pretty rare occurrence to me, much less 3 or more.

I'd rather not write my own custom sort, and I'd also rather not shuffle the list in question before each time I sort it (I feel like that'd be inefficient, but I'm confident it would work).

So, how can I make a comparator that breaks ties randomly (such that there's no risk of a team winning tiebreaks disproportionately) without risking that same error again?




Simulate Nested Logit Errors

I'm trying to simulate data that can be estimated using a nested logit model. If epsilon is distributed nested logit with a nesting structure $B_1, ..., B_K $, and nesting parameters $\lambda_1, ... \lambda_K$ then the CDF of epsilon is

enter image description here

I am looking for a way of simulating random deviates from this distribution in R. The package evd does not allow the user to specify a particular nesting structure. Clearly, the inverse CDF method won't work here, either.

Any advice would be greatly appreciated.




Sort the first k elements of an array in ascending order

The goal of my code is to continuously print the first k elements of my array in ascending order and only stop once it has reached the time limit (int n) in seconds given by the user.

Method shuffleR (t == 6) works fine for me (shuffling the first k elements) while insertionSort (t == 7) is not generating the expected output even if the only thing I changed was the method. My problem is that the generated array is not being passed onto the insertionSort. Not sure what I did wrong so I'm asking here for some help. Thank you in advance!

Here is my shuffleR (t == 6) and insertionSort (t == 7) method:

    public static int[] shuffleR(int [] arr, int n)
    {
        if (n <= 1) // if there is only one number, return n
        {
            return arr;
        }
        
        // swaps the nth element with the element in a randomly selected index
        int index = (int)((n-2)*Math.random());
        
        int temp = arr[n-1];
        arr[n-1] = arr[index];
        arr[index] = temp;
        
        return shuffleR(arr, n-1);
    }
    
    public static int[] insertionSort(int [] arr)
    {
        int temp = 0;
        for(int i = 0; i < arr.length; i++){
            for(int j = i + 1; j < arr.length; j++){ 
                if(arr[i] > arr[j]){
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }         
            }
        }
        return arr;
        
    }

Here is the portion of my code in the main method which is supposed to print the output:

else if (t == 6 || t == 7)
                    {
                        // creates an array with 20000 elements
                        Random rd = new Random(); 
                        int[] arr = new int[20000];
                        
                        for (int i = 0; i < arr.length; i++) 
                        {
                           arr[i] = rd.nextInt(10000); // storing random integers in array 'arr'
                        }
                        
                        if (t == 6) // shuffleR
                        {
                            startLoop = System.nanoTime();
                            System.out.println("\nShuffled numbers:"); // print shuffled numbers 
                            
                            while (elapsedTime < maxTime)
                            {
                                int[] result = shuffleR(arr, k); // call method shuffleR
                                System.out.println("k = " +k);

                                for(int i = 0; i < k; i++)
                                {
                                    System.out.println("Index ["+ i +"] = "+ result[i]);
                                }
                                System.out.println(";");
                                
                                currentTime = System.nanoTime();
                                elapsedTime = (currentTime - startLoop) / 1000000000;
                                k++;
                            }
                            System.out.println("\nLargest k: " + (k-1));
                        }
                        
                        else if (t == 7) // insertionSort
                        {
                            startLoop = System.nanoTime();
                            System.out.println("\nSorted numbers:"); // print sorted numbers 
                            
                            while (elapsedTime < maxTime)
                            {
                                int [] result = insertionSort(arr); // call method insertionSort
                                System.out.println("k = " +k);

                                for(int i = 0; i < k; i++)
                                {
                                    System.out.println("Index ["+ i +"] = "+ result[i]);
                                }
                                System.out.println(";");
                                
                                currentTime = System.nanoTime();
                                elapsedTime = (currentTime - startLoop) / 1000000000;
                                k++;
                            }
                            System.out.println("\nLargest k: " + (k-1));
                        }

Expected Ouput:

k = 1
Index [0] = 933
;
k = 2 
Index [0] = 933
Index [1] = 1001
;
k = 3 
Index [0] = 153
Index [1] = 933
Index [2] = 1001

and so on...

My Output:

k = 1
Index [0] = 0
;
k = 2
Index [0] = 0
Index [1] = 0
;
k = 3
Index [0] = 1
Index [1] = 1
Index [2] = 1
;

and so on...




uuidgen and $RANDOM doesn't change in find -exec argument

I want to get all the instances of a file in my macosx file system and copy them in a single folder of an external hard disk. I wrote a simple line of code in terminal but when I execute it, there is only a file in the target folder that is replaced at every occurrence it finds. It seems that the $RANDOM or $(uuidgen) used in a single command return only one value used for every occurrence {} of the find command. Is there a way to get a new value for every result of the find command? Thank you.

find . -iname test.txt -exec cp {} /Volumes/EXT/$(uuidgen) \;

or

find . -iname test.txt -exec cp {} /Volumes/EXT/$RANDOM \;



How to add random action to python?

First of all, I should say I'm a beginner in programming and I've only been doing this for about a month now, maybe 3 weeks (I don't really Keep track). Anyways as a project I've been coding a VERY basic adventure game in Python myself and through YouTube and stuff I found online, but I want to add a part where basically You gotta get on this boat but a ticket costs $10 (Which you have an option to get earlier).

But say you didn't get the $10 earlier, you have another option to run past the guy who's asking you to pay for it (Which I guess you Could also do even if you have the $10 and just save money). But if you have $10, you just go through, and if you don't, you just restart and it runs sys.exit()

As of writing, the code looks like this:

print("A man offers you a trip to the eastern side of the village via boat")

print( "as a bridge has not been constructed yet, but it will cost $10, do you give him it ($10 Required) or try run past him(Free)")

check_inv = input()

if "$10" not in inv: print("He caught you making a run for it! restart game") sys.exit()

else:

print("Let's see if you have enough...")

print(inv)

print("You have enough and cross the river")

removeFrominventory("$10")

-END OF CODE- (btw the code formatting does NOT look like this, but I don't know how StackOverflow's line spacing system works)

I know how to write a random number generator as it was another beginner project I was advised to work on, but I want to to be that if you type 'Run' you will have a 50/50 chance to be able to outrun him.

Thanks for any help in advance!




How can Deterministic Pseudo Random Number Generator generate 64 byte hash from 32 byte seed using SHA-256 hashing function?

SHA-256 hashing function outputs 32 byte hash always. How can I, using 32 byte seed and SHA-256 hashing function to create an 64 byte hash output ?

I've heard that they use technique like this (pseudocode):

init_hash = SHA256 (seed)
next_hash = SHA256 (init_hash + 1)
next_hash_vol2 = SHA256 (next_hash + 2)
next_hash_vol3 = SHA256 (next_hash_vol2 + 3)
...
next_hash_volA = SHA256 (next_hash_vol9 + A)
...
next_hash_vol10 = SHA256 (next_hash_volF + 10)
...
...
next_hash_vol64 = SHA256 (next_hash_vol63 + 40)

This sounds really nice! But problem is that SHA-256 ALWAYS generates 32 byte output, but I need 64 bytes :(




How can Deterministic Pseudo Randm Number Generator generate 64 byte hash from 32 byte seed using SHA-256 hashing function?

SHA-256 hashing function outputs 32 byte hash always. How can I, using 32 byte seed and SHA-256 hashing function to create an 64 byte hash output ?

I've heard that they use technique like this (pseudocode):

init_hash = SHA256 (seed)
next_hash = SHA256 (init_hash + 1)
next_hash_vol2 = SHA256 (next_hash + 2)
next_hash_vol3 = SHA256 (next_hash_vol2 + 3)
...
next_hash_volA = SHA256 (next_hash_vol9 + A)
...
next_hash_vol10 = SHA256 (next_hash_volF + 10)
...
...
next_hash_vol64 = SHA256 (next_hash_vol63 + 40)

This sounds really nice! But problem is that SHA-256 ALWAYS generates 32 byte output, but I need 64 bytes :(




samedi 19 février 2022

Use logistic regression as a base model in random forest instead of decision tree

How would my result change if I use logistic regression as a base model in random forest instead of decision tree?




C place n elements randomly throughout array map

I am quite new at c, so I am still learning. I am trying to make a colonization type game where there are two teams which have soldiers randomly placed on a map, each soldier fires a missile somewhere on the map randomly. I am having trouble placing the soldiers though. The issue is that instead of displaying the correct amount of soldiers in the right locations, they always end up filling a row instead. For example I would want teams(2,3,4,4) to return something like:

A 0 0 0
0 A B 0
B 0 0 0
0 0 0 B

But instead am getting:

65 65 65 65
0 0 0 0
66 66 66 66
66 66 66 66

I am unsure if I can make this show up as A and B, so 65 and 66 is still ok, but there are too many. Here is some snippets of my code (I am printing the array a lot to see if it messes up somewhere)

Code to populate soldiers:

//declare the arrays
   InArray = calloc(row * col, sizeof(char));
    OutArray;

void teams(int teamAsoldiers, int teamBsoldiers, int mapRows, int mapCols){
   srand(time(0));
   const char teams[2] = {'A', 'B'};
   int maxTeamSoldiers = teamAsoldiers + teamBsoldiers;

   //Place team soldiers
   for(int j = 0; j < 2; j++){
      for(int i = 0; i < maxTeamSoldiers; i++){
         int location = ((rand() % (mapRows * mapCols)) );
        //read the elements from the file into the array
        ReadFromBinFile(sFileName,&OutArray,&nElements);
         //binary file stuff
         if(OutArray[location] == 0){ //if current is empty
            InArray[location] = teams[j];
           //write the array into the file
            WriteToBinFile(sFileName,InArray,mapSize);
            PrintArray(InArray,row,col);
            printf("-------------------\n");
         }else{
            i--;
         }
      }
   }
}

Code for reading/writing to binary file:

//-----------------------------------------
// Write the content of an array into a bin file
//-----------------------------------------
int WriteToBinFile(char * sFileName, char * bArray, int nSize)
{
    FILE * pFile = NULL;
    if ((pFile = fopen(sFileName,"wb+"))==NULL)
    {
        printf("Error in creating the file:%s\n",sFileName);
        return -1;
    }
    else
        {
            fwrite(bArray,sizeof(char),nSize,pFile);

            fclose(pFile);

            return 0;

        }   
}

//-----------------------------------------
// Read the content of a bin file into an array
//-----------------------------------------
int ReadFromBinFile(char * sFileName, char ** bArray, int * nSize)
{
        
        
        FILE * pFile = NULL;
        if ((pFile = fopen(sFileName,"rb+"))==NULL)
        {
                printf("Error in opening the file:%s\n",sFileName);
                return -1;
        }
        else
                {
            //calculate the size of the file
      
            //position the file pointer to the end of the file
            fseek(pFile,0,SEEK_END);
            //get the size of the file in bytes
                *nSize = ftell(pFile);

            //allocate the space for the array
            *bArray = (char *)malloc(*nSize*sizeof(char));
            fseek(pFile,0,SEEK_SET);

            //second solution reading all at once (fast)
                        fread(*bArray,sizeof(char),*nSize,pFile);

                        fclose(pFile);

                        return 0;

                }
}




Can anybody explain why numpy doesn't always include sampling with replacement?

I've been looking for a proper way to random sample a set of integers without replacement, like I would do with ease in R, but I can't find anything.

I've been reading the documentation recommending me to use Generator, but with no luck: https://numpy.org/doc/stable/reference/random/index.html

I can use

np.random.choice([0,1,2,3], size=10, replace=False, p=None

, but I think numpy wants me to write new code with that new Generator. Slightly confused here.




I am having an issue on some sites

Picture of the issue I am facing this issue where I see blurred pink shades on random pictures on the internet . Eg on IMDb

Pls do tell what is the issue , some virus or some issue on my laptop

Ik this is not the platform to ask such a question but this is one of the only trusted places to ask for help .




Python - My while loop not generating random numbers in a function called inside the while loop

I'm trying to get the while loop to randomize a monster stats and its name on a function called inside the loop, it creates it onces but it's not randomieze everytime the while completes a loop.

Everytime I run the Mobs() outside the loop, the mobs are randomize, yet somehow it doesn't work on inside the loop.

import random
import time

mobs = ['rat', 'snake', 'bat', 'spider', 'mole', 'hawk', 'fox', 'vulture', 'beetle']

mobs_names = random.choice(mobs)
mob_hp = random.randint(45, 60)
mob_damage = random.randint(8, 13)
mob_exp = random.randint(20, 23)

class Mobs:
    def __init__(self, hp=mob_hp, damage=mob_damage, name=mobs_names, exp=mob_exp):

        self.hp = hp
        self.damage = damage
        self.name = name
        self.exp = exp

        print("Monster is a " + self.name.title() + ' and it\'s stats are...')
        print('HP: ' + str(self.hp))
        print('Attack Damage: ' + str(self.damage))

gameloop = True

#spawn_mobs = Mobs()
world_level = 0
battlebegun = print("Battle has started")

while gameloop == True:
    while world_level < 10:
        world_level += 1
        print(world_level)
        if world_level <= 10:
            spawn_mobs = Mobs()
            battlebegun
            time.sleep(1)
            continue

    break #gameloop = False


print("Game over")




vendredi 18 février 2022

Random images changing at every frame

The falling object image, which I pick randomly under "necessary enemy values" and assign at "random image" will change every frame or so. I only want it to change when it has come up to Y=0 again. I have no idea why this is happening. Somebody please help!

import pygame, random

#initialise pygame
pygame.init()

#window variables
win = pygame.display.set_mode((384,256))
pygame.display.set_caption("Dungeon Run")

#necessary player values
x = 160
y = 128
width = 16
height = 16
vel = 8

#necessary enemy values
png1 = pygame.image.load("1.png")
png2 = pygame.image.load("2.png")
png3 = pygame.image.load("3.png")
e_types = [png1, png2, png3]
e_y = 0

#game loop (main code here)
run = True
while run:
    pygame.time.delay(64)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    
    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x > 10:
        x -= vel

    if keys[pygame.K_RIGHT] and x < 354:
        x += vel

    #gravity
    e_y = e_y + 8
    if e_y > 256:
        e_y = 0

    #random image
    e_type = random.choice(e_types)
    
    #window stuff
    win.fill((0, 0, 0))
    player = pygame.Rect(pygame.draw.rect(win, (255, 255, 255), (x, y, width, height)))
    win.blit(e_type, (0,e_y))
    pygame.display.update()
            
pygame.quit()



How to get NextDouble from cryptogaphy random RandomNumberGenerator

I want to have a cryptographic random double, since RNGCryptoServiceProvider is obsolete in .NET 6 this question is not relevant How to generate a cryptographically secure Double between 0 and 1?

RandomNumberGenerator is recommended, so does RandomNumberGenerator have any method like Random.NextDouble that will return double equals or great than 0.0 and less than 1.0 ?




Generating a random graph with a given # of edges and nodes

I want to generate a random graph for a given number of nodes + edges. When I run it, it returns an edgelist of all zeroes (e.g. if I run it with five nodes and edges, it returns five pairs of zeroes as the edgelist). Is there something wrong with this part of the code that would be causing that?

public GraphEdgeList(int nNodes, int nEdges) {
    if (nNodes != 0){
        for (int i = 0; i < nEdges; i++){
            int u = (int) Math.random()* nNodes;
            int v = (int) Math.random()* nNodes;
            
            addEdge(u, v);
        }
    }
}



What is a role of seed in (using SHA256) Pseudo Random Generator?

I understand how SHA256 work, and I think I know why we use seed for hash functions (SHA256), but I don't understand this notation:

DPRNG = H(1||seed)||H(2||seed)||...

Do they mean: apply SHA256 algorithm on first bits concatenated with seed, then concatenate it result of SHA256 of second portion of bits concatenated with seed and so on... ?

Thanks in advance :)




How can a randomize games in python

I've created one bit of code that just makes shapes fall from the top to the bottom of the screen continuously, I would like to do the same type of code but replace the shapes possibly with arrows instead and have both of them. And then when the user selects start game it would either be shapes or arrows, I know I need to use random but I cannot seem to figure it out? Would I need to put my program in a class and randomize that? I've included my code for the shapes game and the game loop.

Shapes Code:

import pygame
import os


WHITE = (250, 250, 250)
WIDTH, HEIGHT = 750, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Eye Reaction App !")
FPS = 60
IMAGE_WIDTH, IMAGE_HEIGHT = 60, 50

GOLD_STAR_IMAGE = pygame.image.load(
    os.path.join('Assets', 'gold_star.png'))
GOLD_STAR = pygame.transform.scale(GOLD_STAR_IMAGE, (IMAGE_WIDTH, IMAGE_HEIGHT))

GREEN_TRIANGLE_IMAGE = pygame.image.load(
    os.path.join('Assets', 'green_triangle.png'))
GREEN_TRIANGLE = pygame.transform.scale(GREEN_TRIANGLE_IMAGE, (IMAGE_WIDTH, IMAGE_HEIGHT))

LIGHT_BLUE_RECTANGLE_IMAGE = pygame.image.load(
    os.path.join('Assets', 'light_blue_rectangle.png'))
LIGHT_BLUE_RECTANGLE = pygame.transform.scale(LIGHT_BLUE_RECTANGLE_IMAGE, (IMAGE_WIDTH, IMAGE_HEIGHT))

ORANGE_SQUARE_IMAGE = pygame.image.load(
    os.path.join('Assets', 'orange_square.png'))
ORANGE_SQUARE = pygame.transform.scale(ORANGE_SQUARE_IMAGE, (IMAGE_WIDTH, IMAGE_HEIGHT))

PURPLE_HEXAGON_IMAGE = pygame.image.load(
    os.path.join('Assets', 'purple_hexagon.png'))
PURPLE_HEXAGON = pygame.transform.scale(PURPLE_HEXAGON_IMAGE, (IMAGE_WIDTH, IMAGE_HEIGHT))

RED_CIRCLE_IMAGE = pygame.image.load(
    os.path.join('Assets', 'red_circle.png'))
RED_CIRCLE = pygame.transform.scale(RED_CIRCLE_IMAGE, (IMAGE_WIDTH, IMAGE_HEIGHT))


def draw_window_one(star, triangle, rectangle, square, hexagon, circle):
    WIN.fill(WHITE)
    WIN.blit(GOLD_STAR, (star.x, star.y))
    WIN.blit(GREEN_TRIANGLE, (triangle.x, triangle.y))
    WIN.blit(LIGHT_BLUE_RECTANGLE, (rectangle.x, rectangle.y))
    WIN.blit(ORANGE_SQUARE, (square.x, square.y))
    WIN.blit(PURPLE_HEXAGON, (hexagon.x, hexagon.y))
    WIN.blit(RED_CIRCLE, (circle.x, circle.y))

    pygame.display.update()


def start_one():
    star = pygame.Rect(75, 0, WIDTH, HEIGHT)
    triangle = pygame.Rect(575, 0, WIDTH, HEIGHT)
    rectangle = pygame.Rect(175, 0, WIDTH, HEIGHT)
    square = pygame.Rect(275, 0, WIDTH, HEIGHT)
    hexagon = pygame.Rect(375, 0, WIDTH, HEIGHT)
    circle = pygame.Rect(475, 0, WIDTH, HEIGHT)

    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        if star.y > HEIGHT:
            star.y = -1
        elif triangle.y > HEIGHT:
            triangle.y = -1
        elif rectangle.y > HEIGHT:
            rectangle.y = -1
        elif square.y > HEIGHT:
            square.y = -1
        elif hexagon.y > HEIGHT:
            hexagon.y = -1
        elif circle.y > HEIGHT:
            circle.y = -1
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        star.y += 2
        triangle.y += 2
        rectangle.y += 2
        square.y += 2
        hexagon.y += 2
        circle.y += 2
        draw_window_one(star, triangle, rectangle, square, hexagon, circle)

    pygame.quit()

if __name__ == "__main__":
    start_one()

game loop:

def game_loop(self):
        while self.playing:
            self.check_events()
            if self.START_KEY:
                self.playing= False
                self.display.fill(self.BLACK)
                self.start_one()
            else:
                self.display.fill(self.BLACK)
                self.draw_text('Thanks for Playing', 30, self.DISPLAY_W/2, self.DISPLAY_H/2)
                self.window.blit(self.display, (0,0))
                pygame.display.update()
                self.reset_keys()



When I generate random floats between -1 and 1, they are more often negative than positive. Why is that?

I am using glm::linearRand(-1.0f, 1.0f) to generate random floating point numbers between -1 and 1. Afterwards, I output the percentage of numbers that are positive (0.0f or above).

std::srand(time(0)); // Give glm a new seed

uint32_t samples = 1000000000;
uint32_t positive = 0;
uint32_t negative = 0;

for (uint32_t i = 0; i < samples; i++) {
    float rand = glm::linearRand(-1.0f, 1.0f);

    if (rand >= 0.0f) {
        positive++;
    } else {
        negative++;
    }
}

std::cout << "positive %: " << std::setprecision(6) << ((float)positive / samples) * 100 << std::endl;

The percentage of positive numbers always ends up around 49.6%, no matter how often I run the program (with different seeds!). If I understand floating point numbers correctly, there are equally many between -1.0f and 0.0f as there are between 0.0f and 1.0f.

So why does this program always generate more negative numbers than positive numbers?




Generate random and unique probabilities based on the data in a column rstudio

I have a database with different ages (16-85) what I'm triying to do is to assign a random probability to each age but following the next conditions:

  1. The random probability show be between 20-100
  2. The probability show be higher in the lowest and higest values

For example: I have this dataframe

Age Probability
16 85
18 80
25 70
30 50
35 40
65 60
75 65
85 70

I'd really appreciate if you can help me with this. Tank you so much!




jeudi 17 février 2022

Setting a seed for numpy uniform doesn't result in the same probabilities

Why doesn't the below shown code result in 3 arrays with the same probabilities? How can I generate reproducible probabilities?

import numpy as np
np.random.seed(42)
for i in range(3):
    print(np.random.uniform(size = 10))

[0.37454012 0.95071431 0.73199394 0.59865848 0.15601864 0.15599452
 0.05808361 0.86617615 0.60111501 0.70807258]

[0.02058449 0.96990985 0.83244264 0.21233911 0.18182497 0.18340451
     0.30424224 0.52475643 0.43194502 0.29122914]

[0.61185289 0.13949386 0.29214465 0.36636184 0.45606998 0.78517596
     0.19967378 0.51423444 0.59241457 0.04645041]



OpenCL Pseudo random generator race condition

Using this question as basis I implemented a pseudo-random number generator with a global state:

  __global uint global_random_state;

  void set_random_seed(uint seed){
    global_random_state = seed;
  }

  uint get_random_number(uint range){
    uint seed = global_random_state + get_global_id(0);
    uint t = seed ^ (seed << 11);
    uint result = seed ^ (seed >> 19) ^ (t ^ (t >> 8));
    global_random_state = result; /* race condition? */
    return result % range;
  }

Since these functions will be used from multiple threads, there will be a race condition present when writing to global_random_state.

This might actually help the system to be more unpredictable, so it seems like a good thing, but I'd like to know if there are any consequences to this that might not surface immediately. Are there any side-effects inside the GPU which might cause problems later on when the kernel is run?




mercredi 16 février 2022

I use rand() but my values are same. Why? [duplicate]

I am a begginer in C and I am watching Thenewboston's tutorial. I just watched the tutorial number 38 and learnt about rand(). So there was a challenge in this video. The challenge is:

Make a program which represents a dice game. In the game there are 3 dices that roll. The dices are rolled and the user has to guess if the next roll will be bigger, lower or the same.

My code generally works(says right if the values are bigger smaller or same or even if the input is invalid) but I always get the same exact numbers for the first roll (17) and the second roll (16) (I have putted a printf that prints the value of the second roll. That's how I know)

What is wrong with my code? Have I implemented something wrong in rand()?

Here is my code:

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

// rolls dice 3 times
// ask user if next rolls will be bigger
// print if user was right
int main()
{
    int Diceroll1;
    int First_roll = 0;
    int Diceroll2;
    int Second_roll = 0;
    int i;
    char higher_same_lower;

    for(i = 0; i < 3; i++){
        Diceroll1 = (rand()%6) + 1;
        First_roll += Diceroll1;
    }

    printf("welcome to Dice roll! Let's start the game...\n");

    printf("The sum of the dice roll is %d\n", First_roll);
    printf("Is the next dice roll going to be bigger, lower or the same than this one? Press b, l and s respectively ");

    scanf("%c", &higher_same_lower);

    for(i = 0; i < 3; i++){
        Diceroll2 = (rand()%6) + 1;
        Second_roll += Diceroll2;
    }

    printf("%d ", Second_roll);
    if(isalpha(higher_same_lower)){
            if(higher_same_lower == 'b' && Second_roll > First_roll){
                printf("Congrats you are right!");
            }
            else if(higher_same_lower == 'b' && Second_roll < First_roll){
                printf("We are sorry you are wrong!");
            }
            else if(higher_same_lower == 'l' && Second_roll < First_roll){
                printf("Congrats you are right!");
            }
            else if(higher_same_lower == 'l' && Second_roll > First_roll){
                printf("We are sorry you are wrong!");
            }
            else if(higher_same_lower == 's' && Second_roll == First_roll){
                printf("Congrats you are right!");
            }
            else if(higher_same_lower == 's' && Second_roll != First_roll){
                printf("We are sorry you are wrong!");
            }
            else{
                printf("Invalid input. Please restart the game");
            }

    }
    else{
        printf("Invalid input. Please restart the game");
    }

}

Thanks in advance




Java trying to reset the state of Random() [closed]

Basically my problem arises when I'm trying to run a simulation that uses pseudo-random number generation (using a seed for the Random generation). I want to run a simulation multiple times in a row with the same parameters, however, when doing so, it yields a different result everytime. Is it possible to reset the state of the Random() class everytime I run the simulation? Here's some code to illustrate the problem:

        Simulator test = new Simulator();
        test.runLongSimulation();
        test = new Simulator();
        test.runLongSimulation(); 

After the second call to the method .runLongSimulation(), the result isn't the same.

Edit: For those wondering, I have a "Randomizer" class, where I manage the pseudo random number generator. It isn't nothing special really, and I use it to populate my simulation randomly, with species of varying dimensions.

import java.util.Random;

public class Randomizer
{
    // The default seed for control of randomization.
    private static final int SEED = 1111;
    // A shared Random object, if required.
    private static final Random rand = new Random(SEED);
    // Determine whether a shared random generator is to be provided.
    private static final boolean useShared = true;

    /**
     * Constructor for objects of class Randomizer
     */
    public Randomizer()
    {
    }

    /**
     * Provide a random generator.
     * @return A random object.
     */
    public static Random getRandom()
    {
        if(useShared) {
            return rand;
        }
        else {
            return new Random();
        }
    }
    
    /**
     * Reset the randomization.
     * This will have no effect if randomization is not through
     * a shared Random generator.
     */
    public static void reset()
    {
        if(useShared) {
            rand.setSeed(SEED);
        }
    }
}

Edit 2: To answer further questions, here is the code of the Simulator() class, and I don't think any multi-threding shenanigans are going on.

import java.util.prefs.Preferences;

import java.util.Random;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.Color;

public class Simulator
{
    private Preferences prefs;

    // Constants representing configuration information for the simulation.
    // The default width for the grid.
    private static final int DEFAULT_WIDTH = 120;
    // The default depth of the grid.
    private static final int DEFAULT_DEPTH = 80;
    // The probability that a fox will be created in any given grid position.
    private double FOX_CREATION_PROBABILITY = 0.015;
    // The probability that a rabbit will be created in any given grid position.
    private double RABBIT_CREATION_PROBABILITY = 0.20;  

    private double WOLF_CREATION_PROBABILITY = 0.018;  


    //0.12, 0.20
    // List of animals in the field.
    private List<Animal> animals;
    // The current state of the field.
    private Field field;
    // The current step of the simulation.
    private int step;
    // A graphical view of the simulation.
    private SimulatorView view;

    private boolean isSearching = false;
    
    /**
     * Construct a simulation field with default size.
     */
    public Simulator()
    {
        bootSimulation(DEFAULT_DEPTH, DEFAULT_WIDTH);
    }

    public Simulator(boolean isSearching){
        this.isSearching = true;
        bootSimulation(DEFAULT_DEPTH, DEFAULT_WIDTH);
    }
    
    /**
     * Create a simulation field with the given size.
     * @param depth Depth of the field. Must be greater than zero.
     * @param width Width of the field. Must be greater than zero.
     */
    public Simulator(int depth, int width)
    {
        bootSimulation(depth, width);
    }

    private void bootSimulation(int depth, int width){
        if(width <= 0 || depth <= 0) {
            System.out.println("The dimensions must be greater than zero.");
            System.out.println("Using default values.");
            depth = DEFAULT_DEPTH;
            width = DEFAULT_WIDTH;
        }
        
        animals = new ArrayList<>();
        field = new Field(depth, width);

        // Create a view of the state of each location in the field.
        view = new SimulatorView(depth, width, !isSearching);
        view.setColor(Rabbit.class, Color.ORANGE);
        view.setColor(Fox.class, Color.BLUE);
        view.setColor(Wolf.class, Color.RED);
        
        // Setup a valid starting point.
        reset();
    }
    
    /**
     * Run the simulation from its current state for a reasonably long period,
     * (4000 steps).
     */
    public void runLongSimulation()
    {
        simulate(4000);
    }
    
    /**
     * Run the simulation from its current state for the given number of steps.
     * Stop before the given number of steps if it ceases to be viable.
     * @param numSteps The number of steps to run for.
     */
    public int simulate(int numSteps)
    {
        int count = 0;
        for(int step = 1; step <= numSteps && view.isViable(field); step++) {
            simulateOneStep();
            count++;
            //delay(60);   // uncomment this to run more slowly
        }

        return count;
    }
    
    /**
     * Run the simulation from its current state for a single step.
     * Iterate over the whole field updating the state of each
     * fox and rabbit.
     */
    public void simulateOneStep()
    {
        step++;

        // Provide space for newborn animals.
        List<Animal> newAnimals = new ArrayList<>();        
        // Let all rabbits act.
        for(Iterator<Animal> it = animals.iterator(); it.hasNext(); ) {
            Animal animal = it.next();
            animal.act(newAnimals);
            if(! animal.isAlive()) {
                it.remove();
            }
        }
               
        // Add the newly born foxes and rabbits to the main lists.
        animals.addAll(newAnimals);

        view.showStatus(step, field);
    }
        
    /**
     * Reset the simulation to a starting position.
     */
    public void reset()
    {

        step = 0;
        animals.clear();
        populate();
        
        // Show the starting state in the view.
        view.showStatus(step, field);
    }
    
    /**
     * Randomly populate the field with foxes and rabbits.
     */
    private void populate()
    {
        Random rand = Randomizer.getRandom();
        field.clear();
        for(int row = 0; row < field.getDepth(); row++) {
            for(int col = 0; col < field.getWidth(); col++) {
                if(rand.nextDouble() <= FOX_CREATION_PROBABILITY) {
                    Location location = new Location(row, col);
                    Fox fox = new Fox(field, location);
                    animals.add(fox);
                }
                else if(rand.nextDouble() <= RABBIT_CREATION_PROBABILITY) {
                    Location location = new Location(row, col);
                    Rabbit rabbit = new Rabbit(field, location);
                    animals.add(rabbit);
                }else if(rand.nextDouble() <= WOLF_CREATION_PROBABILITY) {
                    Location location = new Location(row, col);
                    Wolf wolf = new Wolf(field, location);
                    animals.add(wolf);
                }
                // else leave the location empty.
            }
        }
    }
    
    /**
     * Pause for a given time.
     * @param millisec  The time to pause for, in milliseconds
     */
    private void delay(int millisec)
    {
        try {
            Thread.sleep(millisec);
        }
        catch (InterruptedException ie) {
            // wake up
        }
    }
}


Moreover, the Randomizer() class is also used in the Animals' subclasses (the Fox, Rabbit and Wolf ones)

Edit 3: Found the error, wasn't resetting the code properly, thanks to
@Petr Janeček for his response and everyone else that responded!




Create random points on a circle

what is the easiest way to create random points on a circle of specific radius with noise in R? is there a library that does this kind of things?

enter image description here




mardi 15 février 2022

Python random.randint(a,b) not producing random values for a 2d grid

I'm new to coding and making my own MineSweeper game. I'm using PyGame.

When I use the code below I would use the list Tiles to draw a 2d grid with red pixels for the Items and gray pixels for the others. I would get a image similar to this: Image of the result. As you can see the pixels are not arranged in a random manner. Re-seeding the random number generator doesn't help, I just get a different not-random pattern.

import pygame
import random

Height = 30
Length = 40

pygame.init()
win = pygame.display.set_mode((Length * 20 + 40,Height * 20 + 60))

Items = 50
Tiles = []
for i in range(Height * Length):
    Tiles.append(99)


for i in range(Items):
    index = random.randint(1,Height * Length-1)
    if Tiles[index] == 99:
        Tiles[index] = -1    
    else:
        while not Tiles[index] == 99:
            index = random.randint(1,Height * Length-1)
        Tiles[index] = -1

def Render():
    global Tiles
    win.fill((100,100,100))
    
    for x in range(Length):
        for y in range(Height):
            if Tiles[x*4 + y] == 99:
                if (x*3 + y) % 2 == 0:
                    pygame.draw.rect(win, (150,150,150), (x*20+20,y*20+40,20,20))
                else:
                    pygame.draw.rect(win, (130,130,130), (x*20+20,y*20+40,20,20))
            elif Tiles[x*4 + y] == -1:
                if (x*3 + y) % 2 == 0:
                    pygame.draw.rect(win, (255,0,0), (x*20+20,y*20+40,20,20))
                else:
                    pygame.draw.rect(win, (225,0,0), (x*20+20,y*20+40,20,20))


run = True    

while run is True:
    pygame.time.delay(15)
    keys = pygame.key.get_pressed()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    if keys[pygame.K_ESCAPE]:
        run = False
    Render()
    pygame.display.update()
pygame.quit()

Why is random.randint() not giving random values and if they are why are they like this in the image? I have searched other posts saying things like the birthday paradox but surely this can't happen every single time I run it?




Encrypt a Paragraph of Text in Java

I am trying to make a game where a paragraph of text is “encrypted” using a simple substitution cipher, so for example, all A's will be F's and B's will be G's an so on. The idea is that the user/player will need to try to guess the famous quote by trying to decrypt the letters. So the screen shows them a blank space with a letter A and they have to figure out it's really an F that goes in the place within the string. I've not got very far, basically I can manually change each letter using a for loop, but there must be an easier way.

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

public class cryptogram {
    

    public static void main(String[] args) {
        
        char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
        
        for (char i = 0; i <alphabet.length; i++) {
            if (alphabet[i] == 'B') {
                    alphabet[i] = 'Z';
            }
        }
        System.out.println(alphabet);
    }
}



2-D World map generation

Good evening everyone. I am writing a 2-D platform. I have a world map. Here is the function which generates the world map 1000x1000.

 def generate_map_matrix():
    return [[0 for __ in range(1000)] for _ in range(1000)]  # generate the matrix

So. I have patterns they are represented as lakes. Here they are.

The representation of matrix 1      # center 2 2
    [[20 20 20 20]
     [20 20 20 20]
     [20 20 20 20]
     [ 0 20 20  0]]
    ====================
    The representation of matrix 2      # center 1 1
    [[ 0 20  0]
     [20 20 20]
     [ 0 20  0]]
    ====================
    The representation of matrix 3         # center 2 2
    [[ 0 20 20 20  0]
     [20 20 20 20 20]
     [20 20 20 20 20]
     [20 20 20 20 20]
     [ 0 20 20 20  0]]
    ====================
    The representation of matrix 4       # center 1 1
    [[20 20 20]
     [20 20 20]
     [20 20 20]]
    ====================
    The representation of matrix 5    # center 1 1
    [[20 20  0]
     [20 20 20]
     [ 0 20 20]]
    ====================
    The representation of matrix 6   # center 4 3
    [[ 0  0 20 20 20  0  0]
     [ 0  0 20 20 20 20  0]
     [ 0 20 20 20 20 20 20]
     [ 0 20 20 20 20 20 20]
     [20 20 20 20 20 20 20]
     [20 20 20 20 20 20 20]
     [ 0 20 20 20 20 20 20]
     [ 0 20 20 20 20 20  0]
     [ 0  0 20 20 20  0  0]]
    ====================
    The representation of matrix 7    # center 4 3
    [[ 0 20 20 20  0  0  0]
     [ 0 20 20 20 20  0  0]
     [ 0 20 20 20 20 20  0]
     [ 0 20 20 20 20 20  0]
     [20 20 20 20 20 20 20]
     [20 20 20 20 20 20 20]
     [20 20 20 20 20 20 20]
     [ 0  0 20 20 20  0 20]
     [ 0  0 20 20 20  0  0]
     [ 0  0 20 20 20  0  0]
     [ 0  0 20 20 20  0  0]]
    ====================
    

The main goal is to create a unique algorithm which fills the map within these matrix's on the land in order to generate a world. It must be random, but the coverage of the water on the land must be between 30-40%. Can you help meee? Pleeeeeasee!




python adding zeroes and a random digit in floats

Trying to add zeroes and a random digit in floats in Python.

I have a code that just loops through and shows the cumulative frequency at each step and the final sum should be 1 but it isn't working.

Here is the output:

0.11
0.197
0.279
0.35700000000000004
0.43000000000000005
0.502
0.569
0.6299999999999999
0.6829999999999999
0.723
0.761
0.794
0.8240000000000001
0.8520000000000001
0.8790000000000001
0.9040000000000001
0.9270000000000002
0.9470000000000002
0.9630000000000002
0.9770000000000002
0.9870000000000002
0.9961000000000002
1.0005000000000002
1.0032
1.0056
1.0077
1.0077

I think this is being caused by the long row of zeroes in some numbers like 0.35700000000000004 in the 4th one. Also, many values are changing like in the first step it should be 0.11 and not 0.197.

Example code:

for i in AlphabetWeights:
    count = i+count
    print(count)



lundi 14 février 2022

How would I generate a random sequence of numbers without going accidently going over the same numbers?

This is probably a duplicate of something, but oh well. I'm trying to create a random number generator that goes over all 7 digit numbers (0000001 - 9999999) but I'm having issues thinking how I'd code such a mechanism; would anyone know any libraries or functions that may help here?




how to distribute more ones using random function in python

I would like to make a list that contains value of '1's than other random number.

let's say I want 60% of '1's appear out of 10 elements. so 6 elements of 1s and 4 elements with random. here is how I approached.

import numpy as np
import random

# to avoid generating 1s..
list_60 = np.random.randint(2,11, 10) 

array([ 6,  2,  8,  6,  6,  3,  5, 10,  6,  8])


count = 0
percentage = int(len(list_60)*(0.6) + 0.5)
for i in range(0,len(list_60)):
    if count < percentage:
        list_60[i]=0
    count += 1

list_60
array([ 1,  1,  1,  1,  1,  1,  5, 10,  6,  8])


random.shuffle(list_60)
array([ 1,  1,  1,  6,  1,  5,  1,  1,  8, 10])

Precedure STEPS:

  1. create randint from 2 to 10.
  2. loop each element and based on the percentage. and change the element to 1s.
  3. shuffle the list for more variation.

I don't think this is smart way of generating more 1s. Is there fancy/smart way to create weighted randomness?

Any help would be appreciated.




Generate random number in python, such that the likelihood of a number being generated is inversely proportionate to it's value

I want to generate a pseudo random number from 1 to n in python, but the likelihood of a number being generated should be lesser the higher the number is. So, 1 will be the most likely outcome of this random function 2 will be half as likely as 1 3 will be one-third as likely as 1 4 will be one-fourth as likely as 1 ... k will be 1/k as likely as 1.

So if there's a 1/10 chance the outcome will be 1, the chance for 2 will be 1/20, 3: 1/30, k: 1/10k.

I don't want to make a list and choose a random value or any such inaccurate hacks so don't suggest that.




Multiple independent random numbers [closed]

I think I don't have good understanding how Random numbers works. In the following sample I am trying to increment 200 counters with 25% probability. It works fine , I understand this is how it supposed to work, but I don't understand why presence of internal loop doesn't affect a probability for a specific counter. Why probability doesn't decrease?

public void test() {
   int array[] = new int[200];
   for (int i = 0; i < 1_000_000; i++) {
       for (int j = 0; j < 200; j++) {
          int one = ThreadLocalRandom.current().nextInt(100) + 1;
          boolean res = one <= 25;
          if (res) {
              array[j]++;
          }
       }
   }
   System.out.println(Arrays.toString(array));
}



Random numbers generator using unique/specific number in android studio

I am able to create random numbers from 1-10 which are in a range using (max-min)+min formula.

This is the code which is used to make random numbers between 1-10.

            @Override
            public void onClick(View view) {
                Random random = new Random (  );
                int val = random.nextInt (11-1)+1;
                textview_random_number.setText ( Integer.toString ( val ) );

And this is for the 10-99

            @Override
            public void onClick(View view) {
                Random random_two_digits = new Random (  );
                int val_two_digits = random_two_digits.nextInt (100-10)+10;
                textView_two_digits.setText ( Integer.toString ( val_two_digits ) );

But i want to generate random numbers with specific number or unique number.

Below are the specific numbers.

128 137 146 236 245 290 380 470 489 560 678 579

129 138 147 156 237 246 345 390 480 570 679 589

120 139 148 157 238 247 256 346 490 580 670 689

130 149 158 167 239 248 257 347 356 590 680 789

140 159 168 230 249 258 267 348 357 456 690 780

123 150 169 178 240 259 268 349 358 457 367 790

124 160 179 250 269 278 340 359 368 458 467 890

125 134 170 189 260 279 350 369 378 459 567 468

126 135 180 234 270 289 360 379 450 469 478 568

127 136 145 190 235 280 370 479 460 569 389 578

100 119 155 227 335 344 399 588 669

200 110 228 255 336 499 660 688 778

300 166 229 337 355 445 599 779 788

400 112 220 266 338 446 455 699 770

500 113 122 177 339 366 447 799 889

600 114 277 330 448 466 556 880 899

700 115 133 188 223 377




Array random order to unique [closed]

I work with an APi in the form of Array. I do not own this APi and unfortunately cannot change how it is returned to me. The main problem with this API is that the order of the 'sensors' is randomly generated. That is, the content of sensors[0] can sometimes be in sensors[1] and vice versa.

This is a real problem, because if I do sensors[0]['key1'] to find my associated value, it can sometimes work. But other times key1 will be in sensors[1] or sensors[2] etc...

I tried a solution, see this topic: Add array to Value

but in fact I don't like it, because I break the structure of the API, which causes other problems later.

In short, while keeping the structure of the API, how to prevent this random order.

The name of the key is identifiable, but can be found randomly in several places. The values are unique.

<?php
$array1 = array(
    'sensors' => array(
        '0' => array(
                    'key1' => 'value1',
                    'key2' => 'value2',
                    'key3' => 'value3',
        ),
        '1' => array(
                    'key3' => 'value4',
                    'key4' => 'value5',
                    'key5' => 'value9',
        ),
        '2' => array(
                    'key1' => 'value13',
                    'key2' => 'value14',
                    'key3' => 'value15',
                    'key7' => 'value16',
                    'key8' => 'value17',
        ),
        '3' => array(
                    'key1' => 'value19',
                    'key7' => 'value20',
                    'key9' => 'value21',
        )
    )
);



$array2 = array(
    'sensors' => array(
        '0' => array(
                    'key1' => 'value1',
                    'key2' => 'value2',
                    'key3' => 'value3',
        ),
        '1' => array(
                    'key1' => 'value13',
                    'key2' => 'value14',
                    'key3' => 'value15',
                    'key7' => 'value16',
                    'key8' => 'value17',
        ),
        '2' => array(
                    'key1' => 'value19',
                    'key7' => 'value20',
                    'key9' => 'value21',
        ),
        '3' => array(
                    'key3' => 'value4',
                    'key4' => 'value5',
                    'key5' => 'value9',
        ),

    )
);

var_dump($array1['sensors'][0]['key1']); // value1 OK
var_dump($array1['sensors'][1]['key3']); // value4 OK
var_dump($array1['sensors'][3]['key1']); // value19 OK

var_dump($array2['sensors'][0]['key1']); // value1 OK 
var_dump($array2['sensors'][1]['key3']); // value15 OK but not same sensors
var_dump($array2['sensors'][3]['key1']); // WRONG

I think there are no solutions




dimanche 13 février 2022

How to create a random string and use it in jinja in Ansible

I would like to create a random string in Ansible tasks and use it in jinja2.
The string should contain 0-9, a-z, A-Z with a length of 32 characters.

I found out this function but can't use it in a set_fact

lookup('community.general.random_string', length=12)



How do I create the alien appear random in my code? [duplicate]

I have a code here in this link https://github.com/Sarthak2233/Pygame




How to produce a deterministic monochrome pseudo-random organic pattern?

Given an X-Y grid, I'd like to deterministically calculate whether each point was black of white.

The overall effect should be a pseudo-random organic pattern, where a randomly placed line, of length L, should cross approximately L/10 black/white boundaries.




samedi 12 février 2022

what is the value range for crypto.rand.read at golang?

At Goalng, what is maximum value we can get from function crpto.rand.read? here is the code

 
import (
    "crypto/rand"
    "fmt"
)
 
func main() {
    c := 10
    b := make([]byte, c)
    rand.Read(b)
 
    fmt.Println(b) 
} 

I run a lot of times, and I find the maximum value always smaller than 256. I guess this generated value range is from 1 - 256? im not sure im right or not. any infomation about it?




How do I used this random code correctly, this code I have so far doesn't work and I am confused why

So basically i am having trouble with this part of this project I'm working on. I need to create a competitor that has a random amount of viewers, which I have gotten. Then I need to have each viewer watch 1 video on the channel that is between 1 and 5 minutes long (which I made a list 1-5 but idk if I should just do random instead). Then I need Compute the total amount of minutes your competitor’s viewers spent watching their channel. And then figure out which channel had more watch time. Output whether it was your channel, their channel, or a tie! To make sure that you’re correct, output the total time watched for each channel. My code for this part so far:

comp = random.randint(1,100)
    compvidlen = (1,2,3,4,5)
    total_time2 = 0 
    total_time_eachvid2 = {}
    
    
    print("Your competitor has", comp,"subscribers")
    
    if comp >= 0:
        print('Competitors watch time statistics:')
        for i in range(comp):
            choice2 = random.choice(compvidlen)
            if choice in total_time_eachvid2:
                total_time_eachvid2[choice2] += choice2
            else:
                total_time_eachvid2[choice2] = choice2
            print("Subsriber watched for", compvidlen[choice2], "minutes.") 
            total_time2 += choice2
        print('\n')
    print("Total Time spent by all viewers is:", total_time2)
    print("Total time spent on each video", total_time_eachvid2)

another issues I just notices is that I dont need to display time per video like the last step that I already solved, I just need to show total.




Complex random selection conditions

I'm still somewhat of a beginner in python, and my latest project has been a wordle bot, using only basic libraries (random, time). In one specific part of the project, I need to generate a new word based on knowledge known from another word. This is the code I am using right now. Some of the names may be confusing, so feel free to ask me.


while cmet == False:
    n_guess = []
    count = 0 
    for i in ne_guess:
      n_guess.append(i)
    ne_guess = random.choice(words)
    for i in comp_guess:
      if comp_guess[count] == 'green':
        if n_guess[count] == 'green':
          criteria = True
      elif comp_guess[count] == 'yellow':

        if n_guess[count] != 'yellow' and comp_guess[count] in n_guess:
          criteria2 = True
      elif comp_guess[count] == 'gray':
        if n_guess[count] not in comp_guess[count]:
          criteria3 = True
      if criteria == True and criteria2 == True and criteria3 == True:
        cmet = True
        count+=1
        print(n_guess)
        print(c_word)
        time.sleep(2)
      else:
        ne_guess = random.choice(words)

essentially, if a letter is "green" that means it is in that word, and in that spot. if a letter is yellow, it is in the word, but not in the spot. If the letter is gray, that means the word does not contain that letter. Basic wordle stuff. When I run, no matter what I try to change, the code continuously evaluates the same word, instead of changing the word which is evaluated. what i've tried: printing different components to check where im going wrong. output:A new word is generated, but the same word is evaluated. changing the code a billion times. output: error persists no matter the formatting. I would appreciate some help. I am happy to comment full code if anyone needs it.




Need help comparing a random competitor to user input

So basically i am having trouble with this part of this project I'm working on. I need to create a competitor that has a random amount of viewers (between 1 and 100). Compute the amount of viewers for competitor (random, this should vary each time). Each of their viewer watches 1 video on their channel that is between 1 and 5 minutes long (choose this randomly per viewer). Compute the total amount of minutes your competitor’s viewers spent watching their channel. And then figure out which channel had more watch time. Output whether it was your channel, their channel, or a tie! To make sure that you’re correct, output the total time watched for each channel. Can someone help me find the correct way to go about this problem I'm really struggling. I'm assuming I need to repeat some of the process I did for the first channel. This is my code so far:

import random

n = int(input("How many youtube videos do you have on your channel? "))
my_dict = {}


for i in range(n):
    titles=input("What is the title?")
    length=float(input("What is the video's length?"))
    my_dict[titles] = length
print ("You have", n,"videos on your youtube. The names of your youtube videos are:", my_dict)


shortest = min(my_dict.values())
longest = max(my_dict.values())

print("Your shortest video is", shortest,"minutes long.")
print("Your longest video is", longest,"minutes long.")

average = sum(my_dict.values())/ len(my_dict)


print("Your average length is", format(average, ".3f"))


print("Part 3 - Let's talk about subscribers.")

sub = int(input("How many subscribers do you currently have? "))
total_time = 0 
total_time_eachvid = {}


if sub >= 0:
    print('Watch time statistics:')
    for i in range(sub):
        choice = random.choice(list(my_dict))
        if choice in total_time_eachvid:
            total_time_eachvid[choice] += my_dict[choice] 
        else:
            total_time_eachvid[choice] = my_dict[choice] 
        print("Subsriber watched for", my_dict[choice], "minutes.") 
        total_time += my_dict[choice]
    print('\n')
print("Total Time spent by all viewers is:", total_time)
print("Total time spent on each video", total_time_eachvid)

print("Part 4 - Let's compare our channel to our competitor!")

projects due soon so please help!!

print("Let's compare our channel to our competitor!")

comp = random.randint(1,100)
print("Your competitor has", comp,"subscribers")



Random, but with a specific percentage Python

Is it possible to do something random but with a certain percentage in Python? Random, but with a specific percentage




choose random index from array and show it once [duplicate]

hey I have a quiz I made with JavaScript and I have an array for questions I want to randomly show questions from the array but I don't want the questions to repeat themselves so I created another array for used questions and every question that is asked is in the array. and I tried to check if the new question is in the array before it gets printed but it doesn't work how can I randomly show questions from the array without repeating them?

function randomize() {
    let random = Math.floor(Math.random() * questions.length);
    return random;
}
let usedQuestions = [10];

submit.addEventListener("click", function(){
    if(questionNumber == questions.length - 1){
        question.style.display = "none";
        answer.style.display = "none";
        submit.style.display = "none";

        card.style.display = "block";
        score.innerText = "Your score is " + points + "/" + questions.length * 10;
        //stop the function from running
        return;
    }
    let userAnswer = document.getElementById("answer").value;
    if(userAnswer == answers[questionNumber]){
        points +=10;
        console.log("correct");
    }   
    else{
        console.log("incorrect" + " " + "the correct answer is " + answers[questionNumber]);
        //if(points == 10){
            //points = 0;
        //}
    }
    //in the else I check if the user have more than 10 points and if so I decrement the points by 10 but id no then I set the points to 0
    questionNumber++;
    answer.value = "";
    counter++;

    
    usedQuestions[questionNumber] = questions[randomize()];
    function check(){
    for (let i = 0; i < usedQuestions.length; i++) {
        if(usedQuestions[i] == randomize()){
            randomize();
            check();
        }     
    }
    }

check();
    //question.innerText = questions[questionNumber];
    question.innerText = questions[randomize()];
});



I get errors on Inconsistent indentation, what is wrong with my code?

Something is wrong here and i don't know what, this should be very easy to make but i have no idea what i'm doing wrong here.

class Start:
def myfunc():

            first = ["Obama", "Trump", "Biden"]

            second = ["finding", "looking at", "searching for"]

            third = ["Monkey", "Bandits", "Police"]
            
            firstselect = randrange(4)

            secondselect = randrange(4)

            thirdselect = randrange(4)

            print(first[firstselect], second[secondselect], third[thirdselect])

            choice = input("Want to generate again? (Y/N)")

            if choice == "y":
                    myfunc()
            else:
                    exit()