dimanche 30 avril 2023

How to generate random numbers fast from "An Extremely Big Array" in Python?

Recently, I got stuck searching for a fast way to generate random numbers in Python. Here like the code below, I collect points from an area with more than 10 million points. And I want to sample 8192 points randomly from the area points. However, np.random.choice(np.arange(...)) makes the program so slow since the large index arrays.

So, how to make this procedure faster? With any useful Python package or function? Thanks for your attention!

import numpy as np

area_idx = self.area_idxs[idx]
points = self.area_points[area_idx]  # 14350962 * 3
labels = self.area_labels[area_idx]  # 14350962
npoints = 8192
# np.random.choice(np.arange(...)) makes the program so slow.
selected_point_idxs = np.random.choice(np.arange(len(points)), npoints, replace=False)

Generate random numbers fast from "An Extremely Big Array" in Python.




samedi 29 avril 2023

Random randint def() for storage variables

I'm trying to make a list where each time a random item from the list is chosen it gives the number to the define of r() which will take the number and give a random number between the values defined to the tenths place. The lists im using are for storage variables that i'm using for items for a game, though i feel there's a good chance i may want to modify these variables to tweak the stats of something, and I would like to try and make it easier to find the item and variables by having a short name of a define and the numbers such as r(1,2), instead of having ((random.randint(1x10,2x10)/10) for every item in the list. Although iv found whenever the same item is picked from the list it always gives the same output for the number, as an example if the list picks the item r(1,2) and runs through the define r() it might give a number of 1.3. The second time it picks the same item though instead of giving a different number it only gives the same number of 1.3

import random

def r(start,end):
    answ = (random.randint(start*10,end*10)/10)
    return answ

itemname =        ['name1','name2','name3','name4','name5']
itemvariable =    [r(1,2), r(1,3), r(3,5), r(1,6), r(6,7) ]

print(random.choice(itemname),random.choice(itemvariable))
print(random.choice(itemname),random.choice(itemvariable))
print(random.choice(itemname),random.choice(itemvariable))

example of current output(assuming random.choice() theoretically always picks first item of each list)

name1 1.3

name1 1.3

name1 1.3

example of desired output(assuming random.choice() theoretically always picks first item of each list)

name1 1.7

name1 1.2

name1 1.8

​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​




How to pick a random number for a list in MySQL

I want to pick a random number from a list of integers in a MySQL Stored Procedure. This list is generated from another function using some calculations.

Example:

[41,69,9,31,10,33,13,73,20,62,21,58,22,39]

I tried the RAND() function but they are dependent on constant min, max, and step values it seems. Any help would be great.

Note: This list of numbers is not always constant, so they do not have constant min, max, or step values.




JAX Random generator: random normal numbers, seem to be returned sorted and not completely random

I'm trying to learn jax from 0. I've been trying to do some synthetic linear relationship data, so that

Y = B1*X + B0 + epsilon

My surprise has been that, when using the raw epsilons, the data seems to be ordered, so the points at the extremes get a higher error than the ones at the center. The shuffled version works fine, with errors normally distributed around the linear relationship

import jax.numpy as jnp
from jax import grad, jit, vmap
from jax import random
import matplotlib.pyplot as plt

n = 100
p = 2  # number of parameters including linear bias
key = random.PRNGKey(0)

X = random.uniform(key, (n, p - 1))
X = jnp.concatenate([jnp.ones((n, 1)), X], axis=1)
B = random.randint(key, (p, 1), 0, 10)

epsilon = random.normal(key, (n, 1))*0.3

y = X.dot(B) + epsilon
y_s = X.dot(B) + random.shuffle(key, epsilon)
plt.scatter(X[:,1], y, label='Original order')
plt.scatter(X[:,1], y_s, label='Shuffled')
plt.legend()

enter image description here Why is this happening?




vendredi 28 avril 2023

Realm-java affects random number generator when too many transactions open

This is a question about the inner workings of Realm and the Kotlin Random number generator. When I incorrectly had several Realm transaction instances open on a background thread (as many as 100 by accident), I observed that setting a Realm object field value to kotlin.Random.nextInt() was causing collisions over 20% of the time, which should not happen.

What about Realm (or memory in general) could cause a side effect like this on kotlin.Random? Intuitively, a random number generator should not be affected by the usage of our local database. Would this also affect behavior like UUID.randomUUID()?

Also, I'm aware the Realm should be closed - I'm genuinely curious why this is happening.

open class MyObject: RealmObject {
   var randomField: Int
}

fun test() = scope.launch { // background thread
            var messageDupes = 0
            var r = Realm.getInstance()
            while (idx < 100) {
                r = Realm.getInstance()  // opening of Realm without closing

                val random = Random.nextInt() // Why would this be affected? Has many collisions


                val existing = r.where<MyObject>.equalTo("randomField", random)
                if (existing != null) {
                    collisions++
                }
                
                val obj = MyObject()

                obj.randomField = random //set field to the random value
                r.executeTransaction {
                    it.insert(message)
                }
                idx++
                delay(300L)
            }
            val count = r.where<MyObject>().count()
            log.debug("total objects: $count; collisions=$collisions")
        }



How to Sample without Replacement in Python for Tweets

I have a small business with Twitter API and I need to randomly send tweets. I used to program 20 years ago, and thought I'd try ChatGPT to coach me on this. It did fairly well, when it did make mistakes, I was able to fix it quickly or modify it, but it would randomly pick a tweet and add it back to the list.. I need to remove it from the list until it's gone through all of them, then start over (sampling without replacement). So I ended up with the following program:

import tweepy
import random
import time

# Enter your Twitter API credentials
API_key = "secret"
API_secret = "secret"
Access_token = "secret-token"
Access_token_secret = "secret"

# Authenticate with Twitter
auth = tweepy.OAuthHandler(API_key, API_secret)
auth.set_access_token(Access_token, Access_token_secret)

# Create the API object
api = tweepy.API(auth)

# List of tweets to post
tweets = [
"""This is tweet number 1""",
"""This is tweet number 2""",
"""This is tweet number 3""",
"""This is tweet number 4""",
"""This is tweet number 5""",
]

# Initialize the list of used tweets
used_tweets = []

# Loop through the tweets and post them twice an hour, around the clock, 90 days
for i in range(90):
for j in range(24):
        minute = random.randint(1, 1800)   // randomly in 30 min incriments
        # Sample a random tweet from the list without replacement
        tweet = random.sample(set(tweets) - set(used_tweets), 1)[0]
        # Add the tweet to the list of used tweets
        used_tweets.append(tweet)
        # If all tweets have been used, start over
        if len(used_tweets) == len(tweets):
        used_tweets = []
        print(f"NEXT TO PRINT: {tweet}\n")
        # Schedule the tweet
        api.update_status(status=tweet)
        print(f"TWEETED: {tweet}\n")
        print(f"Minutes to wait: {minute/60}\n")
        # Wait for the random time to pass before tweeting again
        time.sleep(m

This gives me an error message, "Population must be a sequence or set", I assume because of the 'used_tweets' list, but I don't know. Can anyone help me get this simple program to work? MUCH appreciation in advance!




Learner weighted sampling overweighting learners only at the school level

I have a population level data set of 12m learners.

I am trying to sample at the school level as I do not have the compute for 12m learners.

I need to maintain whole schools in order to subsequently calculate school level stats, such as the fraction of female learners in the school.

If I simple random sample, small schools will be over represented at the learner level.

I want the average school size(learner_count), at the learner level, to be within sampling error of the population school size at the learner level. However, my code is returning data where the learner-weighted sampled school-level school size is the same as population learner-level school size but the sample learner-level school size is much much higher than than the population learner-level school size. I have tried creating school size weights (learners at school/all learners) as the weight in the sample function, but that returns the same result.

I am using the following code to sample:

#Create school level data
  unique_schools <- all_learners %>%
    filter(!is.na(school_id),
           !is.na(learner_count))%>% 
    group_by(school_id) %>% 
    summarise(school_id = first(school_id),
              learner_count = first(learner_count)) 
#%>% 
# mutate(learners_tot =  sum(learners_master, na.rm = T),
#     learner_weight = learner_count/learners_tot) %>% 
# select(school_id, learner_weight)

# Randomly select 1000 schools
  selected_schools <- unique_schools %>%
    sample_n(1000, weight = learner_count, replace = FALSE) #or weight = learner_weight

# Create the `sample` column and filter the dataset
  sample <- all_learners %>%
    mutate(sample = if_else(school_id %in% selected_schools$school_id, 1, 0)) %>%
    filter(sample == 1)



jeudi 27 avril 2023

How do I have the random.randint give a different output when its given the same numbers in the list for each time the define is used

I'm trying to make a list where each time a random item from the list is chosen it gives the number to the define of lwr() that makes it a random radiant. I was hoping there would be a way of accomplishing this while still using the define lwr() to give the random radiant. Though I cant get the random radiant to change each time when the same list item is given

import random

def lwr(start,end):
    y = ((random.randint(start,end)))
    return y

list =[lwr(1,10)]

print(random.choice(list))
print(random.choice(list))
print(random.choice(list))

Current Output(example): 4 4 4

Desired Output(example): 6 3 7

​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​




rand() stops working when I try to do stuff with it [duplicate]

I'm trying to understand how the rand() function works. I started out with a simple for loop printing random numbers each time, and that seems to work perfectly, but as soon as I add more code (in this case I'm trying to clamp the random number between 1 and 20, and doing some other stuff to get the probabiliy of two events happening) it stops working and only returns 0s.

Any idea what's happening?

int getRando(int bNumber)
{
    int i, r;
    
    while(r>32760)
    {
        r = rand();
    }
    
    for(i=1;i<=bNumber;i++)
    {
       if (r <= (1638 * i))
       {
            r = i;
            break;
       } 
    }
    
    return r;
}




int main(int argc, char *argv[]) {
    srand(time(NULL));   
    
    int i, r, primaBianca = 0, primaNera = 0;
    
    for(i=0;i<1000;i++)  //this works
    {
        r = rand();
        printf ("%d\n",r);
    }
    
    
    for (i=0; i<1000;i++) 
    {
        r = getRando(20);   //from this point on it only returns zeroes
        
        if  (r<=12)
        {
            r = getRando(20);
            if (r<=12) primaBianca++;
        }
        else  
        {
            r = getRando(19);
            if (r<=12) primaNera++; 
        }
    }
    
    printf ("prima pallina bianca: %d\n",primaBianca);
    printf ("prima pallina nera: %d\n",primaNera);
    return 0;
    
}



Random Numbers in Unity 3D?

What I found was how to create random numbers. Great.

This solution, however, was not working in other functions. To create a random number, I used

enter image description here

inside of a function called enemyWalk(){};

However, this caused an error:

enter image description here

This error does not appear when I take the random integer generator out of the function. Any solutions to fix this problem?

I'm hoping to use this code to make my enemy wander around when not doing anything by randomly choosing an integer that decides which direction he walks (up, left, right, or down), then using a random double generator to determine the distance it walks. However I need a random number generated whenever enemyWalk(){}; is called.




looking for a random matrix of zeros and ones in python with a limited amount of ones

I am generating a matrix of zeros and ones in python as

poblacionCandidata = np.random.randint(0, 2, size=(4, 2))

However, I need for it to be only two ones at most in each row.

I have checked this question, but it is too complex for me.

Can anyone help me with this

The result should be something like

[[1 1 0 0]
 [1 0 0 1]
 [1 0 0 0]
 [0 1 0 0]]

Best regards




mercredi 26 avril 2023

Subsetting sample data with given conditions in python

I need to subset dataset for 100 households from a large DataFrame to prepare input for execution of test cases.

In order to identify a household on data file, A household in datafile can be identified as all members of the household will share the same SERIALNO. All members of each selected household must be included in the subset sample data. There are 50 variables in the DataFrame (dataset) and ten thousands SERIALNO but I needed to subset the dataset based on two variable SERIALNO and Household_member. Each SERIALNO represents one household and also Household_member. I just needed to create a subset of 100 households (SERIALNO) with Household_member included in it with rest of the variables in the dataset.

In the example below, SERIALNO 20161 has household_number 1, 2, 3 and SERIALNO 20162 has 1 household_member and SERIALNO 20164 has household_number 1, 2, 3 and so on and some household_member are up to 15. How do I subset of 100 households with SERIALNO that includes household_members as described below? Please help with the python code to subset this dataset. I am just learning python-pandas. I would greatly appreciate your assistance.

SERIALNO Household_member

20161 1 20161 2 20161 3

20162 1 20164 1 20164 2 20164 3

1 ACCE

I need to subset dataset for 100 households from a large DataFrame to prepare input for execution of test cases.

In order to identify a household on data file, A household in datafile can be identified as all members of the household will share the same SERIALNO. All members of each selected household must be included in the subset sample data. There are 50 variables in the DataFrame (dataset) and ten thousands SERIALNO but I needed to subset the dataset based on two variable SERIALNO and Household_member. Each SERIALNO represents one household and also Household_member. I just needed to create a subset of 100 households (SERIALNO) with Household_member included in it with rest of the variables in the dataset.

In the example below, SERIALNO 20161 has household_number 1, 2, 3 and SERIALNO 20162 has 1 household_member and SERIALNO 20164 has household_number 1, 2, 3 and so on and some household_member are up to 15. How do I subset of 100 households with SERIALNO that includes household_members as described below? Please help with the python code to subset this dataset. I am just learning python-pandas. I would greatly appreciate your assistance.

SERIALNO Household_member

20161 1 20161 2 20161 3

20162 1 20164 1 20164 2 20164 3




ValueError: empty range for randrange() (0, 0, 0) | slider keeps returning 0 as a value Python Tkinter

So, I'm making a mine sweeper as a school project and I struggle through setting a settings window.

My biggest problem right now is that I have a slider which allows the player to change the size of the terrain by changing the number of rows and columns to one same number to then multiply them and have a terrain which is the square of the number received from the slider.

However, the slider does not seem to work in the way it is intended as he keeps sending back the value "0", as if he was never updating the value when moving the slider.

So I end up with the error :

  File "D:\MiniConda\lib\random.py", line 316, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))

ValueError: empty range for randrange() (0, 0, 0)

Here is my entire code, I put a commentary at the line where I believe the problem comes from :


from tkinter import *
from tkinter import ttk as ttk
import random
#module permettant l'importation d'images
from PIL import Image, ImageTk 
#module permettant la création de boutons avec plus de choix esthétiques
import customtkinter
#module permettant de fermer le programme
import sys


#Crée la fenêtre de prévention
def PreventionDemineur():

    preventionfenetre = Tk()    
    
    #Assigne pour titre à la fenêtre "Paramètres du Jeu du Démineur"
    preventionfenetre.title(" ATTENTION ") 

    #Affiche le texte de prévention avec ses caractéristiques
    TextePrevention = Label(preventionfenetre, text="Détails à lire !", font=("helvetica", 25, "bold"))
    
    #Gère la position du message de prévention
    TextePrevention.place(relx=0.5, rely=0.1, anchor=CENTER)

    #Affiche le texte de prévention avec ses caractéristiques
    ContenuPrevention = Label(preventionfenetre, text="- Prenez le temps de changer les paramètres du jeu, sinon \n il démarrera avec ses paramètres par défaut.", font=("helvetica", 10))
    
    #Gère la position du message de prévention
    ContenuPrevention.place(relx=0.5, rely=0.3, anchor=CENTER)
    
    #Change la taille afin que la fenêtre puisse tout afficher
    preventionfenetre.minsize(400, 400)
    preventionfenetre.maxsize(400, 400)
    
    #Place la fenêtre au centre de l'écran
    preventionfenetre.eval('tk::PlaceWindow . center')

    # Attend que la fenêtre se ferme pour continuer le code
    preventionfenetre.wait_window(preventionfenetre)
PreventionDemineur()
    
# Crée la fenêtre des paramètres du démineur
def parDemineur():

    parfenetre = Tk()    
    
    #Assigne pour titre à la fenêtre "Paramètres du Jeu du Démineur"
    parfenetre.title("Paramètres du Jeu du démineur") 
    
    #Image du démineur
    Pardemineursource = ImageTk.PhotoImage(master=parfenetre, file='ParDemineur.png')

    #Affiche l'image
    Pardemineurimg = Label(parfenetre, image = Pardemineursource)
    
    #Gère la position du message de prévention
    Pardemineurimg.pack()

    #Change la taille afin que la fenêtre puisse tout afficher
    parfenetre.minsize(400, 900)
    parfenetre.maxsize(400, 400)

    # Gère la création de la fenêtre avec sa largeur, sa hauteur, son fond)
    canvas = Canvas(parfenetre , width =750, height=500 , background='white')
    canvas.pack()
    
    #Place la fenêtre au centre de l'écran
    parfenetre.eval('tk::PlaceWindow . center')
    
    # Utilise CTkButton à la place du bouton de Tkinter, permettant plus de personnalisation. Le bouton une fois appuyé, permet de fermer la fenêtre des paramètres.
    boutonstart = customtkinter.CTkButton(master=parfenetre, text="Commencer à jouer !", font=("helvetica", 20, "bold"), command=parfenetre.destroy)
    
    #Situe le bouton dans la fenêtre ainsi que sa taille
    boutonstart.place(relx=0.5, rely=0.9,relheight=0.125, relwidth=0.3, anchor=CENTER)

    # Utilise CTkButton à la place du bouton de Tkinter, permettant plus de personnalisation. Le bouton une fois appuyé, permet de fermer la fenêtre des paramètres.
    boutonfermer = customtkinter.CTkButton(parfenetre, text="Quitter",fg_color="red", font=("helvetica", 20, "bold"), command=sys.exit)
    
    #Situe le bouton dans la fenêtre ainsi que sa taille
    boutonfermer.place(relx=0.94, rely=0.08,relheight=0.05, relwidth=0.08, anchor=CENTER)

    #Affiche le texte de prévention avec ses caractéristiques
    ContenuPar = Label(parfenetre, text="Choix de la taille du terrain", font=("helvetica", 10, "bold"))
 
    #Gère la position du message de difficulté
    ContenuPar.place(x=650, y=350, anchor=CENTER)   
    
    #THE PROBLEM STARTS BELOW THIS---------------------------------------------------------
    
 
    #Slider pour la taille du terrain
    # slider valeur actuelle
    valeur_actuelle = IntVar()


    def obtenir_valeur_actuelle():
        valeur = format(valeur_actuelle.get())
        return format(valeur_actuelle.get())


    def changement_slider(event):
        valeur_label.configure(text=obtenir_valeur_actuelle())


    # slider
    slider = ttk.Scale(parfenetre,from_=2,to=10,orient='horizontal',command=changement_slider,variable=valeur_actuelle)
    slider.place(x=650, y=375, anchor=CENTER) 


    # label du texte Valeur Actuelle
    valeur_actuelle_label = ttk.Label(parfenetre,text='Valeur Actuelle:')
    valeur_actuelle_label.place(x=650, y=425, anchor=CENTER) 
    
    # label de la valeur en elle même
    valeur_label = ttk.Label(parfenetre,text=obtenir_valeur_actuelle())
    valeur_label.place(x=700, y=425, anchor=CENTER) 
    valeur = int(obtenir_valeur_actuelle())
    print(valeur)
    
    
    
 
    #importation de l'image de défaite
    imagePerdant=Image.open("Game_Over.png") 

    #importation de l'image de victoire
    imageGagnant=Image.open("Victory.jpg") 

    #le terme miner veut dire creuser
    terrainMines = []   
    nombre_colonne = valeur
    nombre_ligne = valeur
    Blocs_miner =  0
    nombre_tnt = 5
    Blocs_à_miner = nombre_colonne * nombre_ligne - nombre_tnt
    nbr_col_ligne = nombre_colonne * nombre_ligne
 
    #Force la fenêtre à être ouverte en pleine écran
    parfenetre.attributes('-fullscreen', True)

    # Attend que la fenêtre se ferme pour continuer le code
    parfenetre.wait_window(parfenetre)

    #création du terrain miné

    # permet de creer une liste qui pour chaque bloc (rangée et colonne) entre des nombres aleatoires.
    def CreeTerrainMine(nombre_colonne, nombre_ligne): 
        terrainMines = [[0 for colonne in range(nombre_colonne)]for ligne in range(nombre_ligne)]
        TNT=[]
        while len(TNT)<nombre_tnt:
        
        
            # calcul un nombre aleatoire   
            n = random.randint(0,nbr_col_ligne-1) 
            if not n in TNT:
                TNT.append(n)
                ligne=n//nombre_ligne
                colonne=n% nombre_colonne
            
                # positionne la tnt
                terrainMines[ligne][colonne]="TNT" 
            
            #permet de calculer les tnt voisines
            for i in range (nombre_ligne):
                for j in range (nombre_colonne):
            
                    #on regarde les 8 cases voisines et on ajoute 1 car il y a une tnt 
                    if terrainMines[i][j]=="TNT":
                        for ii in range(i-1,i+2):
                     
                            #on ajoute 2 car le 2 est exclus du cadre
                            for jj in range(j-1,j+2): 
                                if 0<=ii<nombre_ligne and 0<jj<nombre_colonne and terrainMines[ii][jj]!="TNT":
                                    terrainMines[ii][jj]=terrainMines[ii][jj]+1
                        for iii in terrainMines:
                            print(iii)
        return terrainMines


    #action du boutton + Affichage des blocs sur l'écran
    def bouton(Cadre, terrainMines): 
        for nombre_Rangee in range(nombre_ligne):
            for nombre_colonnes in range(nombre_colonne):
                bloc = Button(Cadre, text=terrainMines[nombre_Rangee][nombre_colonnes], font=("Courier", 15),height=2, width=5, fg="#008737",bg="#008737", activebackground="#008737",activeforeground="#008737")  
                bloc.grid(row = nombre_Rangee, column = nombre_colonnes ) 
            
                #permet de lier la fonction boutonClic au clic gauche de la souris
                bloc.bind ("<Button-1>", Clic) 
                bloc.bind ("<Button-3>", Drapeau)    
    def Clic(event): 
        bouton = event.widget 
        Explosion(bouton)
    
    
    def Drapeau(event):
        bouton = event.widget
        Pose_Drapeau(bouton)


    
    def Pose_Drapeau(bouton):
        bouton.configure(disabledforeground="#153D3A",bg='#153D3A')
        if (bouton['state'] == "normal"):
            bouton['state'] = "disabled"
        else:
            bouton['state'] = "normal"
            bouton.configure(fg="#008737",bg='#008737')
 
    # avec les valeurs des blocs, cela cherche si le jeu doit continuer ou s'il doit s'arrêter
    def Explosion(bouton): 
    
        # permet de récupérer la valeur du bloc (le texte)
        valeurBouton = bouton.cget("text")  
    
        #affiche la valeur du bloc et une tnt est repéré 
        if (valeurBouton == "TNT"): 
    
            #change la couleur du bloc en rouge
            bouton.configure(fg="white",bg='#78020e')  
        
            # affichage de l'image de défaite
            imagePerdant.show()
            exit(1)
        
        # aucune tnt n'est repéré
        else:
    
            #permet de récupérer la couleur du texte du bloc
            couleurPolice = bouton.cget("fg")
        
            # si la couleur reste la meme cela veut dire que le bloc n'a pas été miné
            if (couleurPolice == '#008737'): 
            
                # l'instruction global informe que la variable qui est utilisée à l'intérieur de la fonction est la même que celle qui est définie à l'extérieur de la fonction
                global Blocs_miner 
             
                # augmente le nombre de clic
                Blocs_miner += 1 
             
                # change la couleur de la police afin de pouvoir voir le chiffre et change le fond du bloc pour montré que le bloc est miné
                bouton.configure(foreground="white",bg='#66370E')  
                # tous les blocs sans tnt sont creusés
                if (Blocs_miner == Blocs_à_miner): 
            
                    # affiche l'image de victoire
                    imageGagnant.show()
                    exit(0)
           
  
    def jouerDemineur():

        fenetre = Tk() 
        fenetre.eval('tk::PlaceWindow . center')
    
        #affiche un titre à la fenêtre
        fenetre.title("Jeu du démineur")  
    
        #Force la fenêtre à être ouverte en pleine écran
        fenetre.attributes('-fullscreen', True)
 
    
        #le widget frame est utile pour le regrouppement et l'organisation d'autres widget
        Cadre = Frame(fenetre, borderwidth=100, bg="#153D3A") 
        Cadre.pack(expand=1)
        terrainMine = CreeTerrainMine(nombre_colonne, nombre_ligne)
        bouton(Cadre,terrainMine)
        Cadre.bind('<Button-3>', Drapeau)
        
        # Utilise CTkButton à la place du bouton de Tkinter, permettant plus de personnalisation. Le bouton une fois appuyé, permet de fermer la fenêtre des paramètres.
        boutonfermer2 = customtkinter.CTkButton(master=fenetre, text="Quitter",fg_color="red", font=("helvetica", 20, "bold"), command=fenetre.destroy)
    
        #Gère la position du message de difficulté
        boutonfermer2.place(relx=0.95, rely=0.05, anchor=CENTER)

    jouerDemineur()

    fenetre.mainloop()

parDemineur()

When I got the error I tried to use print(valeur) to see what was wrong with it since this is the problematic value and that's when I saw that even when putting the slider at 10, it always returned me "0".

I tried searching in the code but I couldn't find anything.

I would be really grateful if someone could help me as I'm clearly no professionnal in python.




mardi 25 avril 2023

How to detect the amount of circles created

I'm trying to make a small game that has to do with being asked to click for a random amount of circles. How can I code this by being able to know how many circles the player has created? I want to be able to print out text asking for a random number of circles. Then the player would be able to click for the correct number and submit it with a button or some sort. Sorry if this might sound confusing!

Right now, I'm just stuck on how to figure out how I'll be able to know the amount of circles the player clicks.




How to generate extremely large numbers?

What is the best way to generate large random numbers (bigger than 10e32)? I have seen a lot of things for better generations (mt19937 instead of rand()) but they are still relatively limited in size.

#include <iostream>
#include <random>
using std::cin;
using std::cout;

int main() {
    long long userImput;
    cin >> userImput;
    std::random_device rd;
    std::mt19937_64 gen(rd());
    std::uniform_int_distribution\<long long\> dist(3, userImput);
    long long randomNum = dist(gen);
    cout << randomNum;
};
//result of large imputs is maxed at around 10e20



Two levels of sampling

I have a bunch of Things.

A Thing is a struct with a field, source, typed as a string.

Currently I get a deterministic sampled selection of Things by simply hashing the Thing.

def is_thing_sampled(t: Thing):
    hashed_thing = my_deterministic_hash(t);
    return hashed_thing % 100 < sample_size_pct;

Now I want to extend this function so that it additionally samples Thing of a specific source. If the source is "foo", I want to do another level of sampling on it.


def is_thing_sampled(t: Thing):
   hashed_thing = my_deterministic_hash(t)
   base = hashed_thing % 100 < sample_size_pct;
   if base and t.source == "foo":
      # try to sample again. How do I do this?? 
      double_hash = my_deterministic_hash(hashed_thing)
      return double_hash % 100 < foo_sample_size_pct

    return base    

Can someone help me understand what's the right approach? I'd love some pointers - I'm a total noob at statistics.




Efficient way to sample from matrix of probabilities n times with binomial distribution

I have a 2-dim matrix of probabilities. I want to sample using a binomial distribution from this matrix n times. What is the most elegant way to do this using numpy / scipy?

import numpy as np

test_mat = np.random.beta(10, 2, size=(10,3))
trials = 5

# this works but only 1 trial
np.random.binomial(1, test_mat)

# this gives error
np.random.binomial(1, test_mat, size = (10, 3, trials))

ValueError: shape mismatch: objects cannot be broadcast to a single shape

Or is my only option to first reshape the test_mat array to be 3 dimensional (in essence slotting in the same values for all 5 columns in the 3rd dimension from a given row and column in the 1st and 2nd dims).




lundi 24 avril 2023

positive random number matrix gives only 0 and negative in c++

I need to make a 100x100 matrix with only odd integer random numbers, but it only gives me zeros and negative numbers. Something like this:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 61 0 0 0 0 0 0 0 0 0 0 0 0 0 0 605810241 32763 0 0 0 0 0 0 0 0 0 0 0 0 -1109404240 -1109404223 46 -1109404000 46 -1109404196 46 -1109404200 46 0 0 0 0 0 1204 0 0 141694856 367 32 3

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

using namespace std;

int main()
{

    int matrix[100][100];

    srand(time(NULL));

    for (int i = 0; i < 100;)
    {
        for (int j = 0; j < 100;)
        {
            int random = 1 + rand() % 100;
            if (random % 2 != 0 && random > 0)
            {
                matrix[i][j] = random;
                i++;
                j++;
            }
        }
    }

    for (int i = 0; i < 100; i++)
    {
        for (int j = 0; j < 100; j++)
        {
            cout << matrix[i][j]
                 << " ";
        }
        cout << "\n";
    }

    return 0;



Pick some combinations of r elements out of all possible combinations of elements from an array of length n

So I have a list of lists, say superlist = [sublist1, sublist2, ...,sublistn] of length n.

I need to randomly pick a large number of combinations of r elements from it, but not necessarily all of them. In my case, n=35, r=8, and the number of combinations needed are 10000.

The problem I am facing while running this on Python 3.9 is that the number of combinations goes to the order of 1e7, and as I am dealing with long lists within each combination, random shuffle is slow and takes up too much memory. So my question is: is there a faster and less memory-intensive way to get a random set of combinations of the format nCr? Ideally, I would want to avoid generating all combinations as well.

What I tried was the following:

import numpy as np
from itertools import combinations as comb
from sklearn.utils import shuffle
largenumber = 10000
all_combs = np.array(list(comb(superlist, r)))
perm = np.arange(all_combs.shape[0])
np.random.shuffle(perm)
if max(perm)<=largenumber:
   required_combs = all_combs[perm]
else:
   required_combs = all_combs[perm][0:largenumber]

The np.random.shuffle and the comb(superlist,r) become extremely slow and consume large amounts of memory. As I was running it on a cluster, the cluster was killing the process due to high memory usage.




Optimized JavaScript Random Strings With Key-Value Pairs/For Loop

var crustType = ["wheat", "hand tossed", "deep dish"];
var crustTypeArr = crustType[Math.floor(Math.random() * crustType.length)];
var sauceType = ["marinara", "tomato", "none"];
var sauceTypeArr = sauceType[Math.floor(Math.random() * sauceType.length)];
var cheeses = ["mozarella", "cheddar", "feta"];
var chessesArr = cheeses[Math.floor(Math.random() * cheeses.length)];
var toppings = ["vegan sausage", "spinach", "onions", "pepperoni", "mushrooms"];
var toppingsArr = toppings[Math.floor(Math.random() * toppings.length)]

function randomPizza(crustType, sauceType,cheeses, toppings) {
    randomPizza.crustType = crustType;
    randomPizza.sauceType = sauceType;
    randomPizza.cheeses = cheeses;
    randomPizza.toppings = toppings;
    
    return randomPizza;
}

var p5 = randomPizza(crustTypeArr, sauceTypeArr, chessesArr, toppingsArr);

console.log(p5);

How would you do this with key value pairs/for loop, or whichever way you think is more optimized if there were like a million variables?

I got the right code, but it is not optimized.




DnD dice rolling game

I apologize if people are seeing this again, but I am being a little stubborn and want to see the way I have my code set up to work even if not most efficient. In case new people see this as well, the purpose of this code is to simulate rolling a handful of dice. I am using an arrayList of objects to accomplish this. The issue I am having is as seen below, my object arrayList is printing out each object. However, each object is only able to print out the most recent number rolled by that type of dice.

CODE:

import java.util.InputMismatchException;
import java.util.Scanner; 
import java.util.ArrayList;

public class Main {

   public static void printArrayList(ArrayList<VarDice> diceRolls) {
      int i;
      for(i = 0; i < diceRolls.size(); ++i) {
         System.out.print("D" + diceRolls.get(i).getNumSides() + ":");
         diceRolls.get(i).printInfo();
         System.out.println();
      }
   }
    
   public static void main(String[] args) {
      
      Scanner scnr = new Scanner(System.in);
         
         //Create a new object of VarDice (VarDice dice = new VarDice();)
         
          //Create boolean play that is true
          Boolean play = true;
         //Create int numSides and int numDice for how many dice are rolled
         int numSides;
         int numDice;
   
         //Create an int variable for results of the rolls (int results = 0;)
         int results = 0;
         
         //Create array list of object VarDice
      ArrayList<VarDice> diceRolls = new ArrayList<VarDice>();

      while (play) {
      //Greet user
      System.out.println("Enter the number of dice and number of sides (enter 0 to exit):");
      
      VarDice dice = new VarDice();
      
      try {
      //Get user input for numSides
      numDice = scnr.nextInt();
      //Get user input for numDice
      numSides = scnr.nextInt();

        if (numDice < 0 || numSides < 0) {
         throw new Exception ("Invalid input, both should be a positive number");
        }
      }
   //Create catch block for a inputmismatch (catch (InputMismatchException excpt)) 
      catch (InputMismatchException excpt) {
         System.out.println("Invalid input.");
         break;
      }
   //Create catch block for all expectations (catch (Exception excpt)
      catch (Exception excpt) {
         System.out.println(excpt.getMessage());
         break;
      }
      
   if (numDice == 0 && numSides == 0) {
    play = false;  
   }
   
   else { 
      //A for loop is made for number of times a die is rolled according to user input 
      
   dice.setNumDice(numDice);
   dice.setNumSides(numSides);
   
   for (int i = 0; i < numDice; ++i) {
      dice.setRoll(dice.Roll());
      dice.printInfo();
      results += dice.getRoll();
   }
   diceRolls.add(dice);
   //System.out.println();
      }
        
    }
   
   System.out.println();
   System.out.println("Results:");
   printArrayList(diceRolls);
   System.out.println("Total: " + results);
   
   }
    
}

//Die.java

import java.util.Random;

public class Die {
   
   protected int numRolled;
   final Random rand = new Random();
   
   public int getNumRolled() {
      return numRolled;
   }
    
   public void roll() {
        numRolled = rand.nextInt(5) + 1;
   }
}

//VarDie.java

 import java.util.Scanner;
 import java.util.ArrayList;
 
public class VarDie extends Die {
    
       //Scanner scnr = new Scanner(System.in);
            int numSides;
            int numDice;
            int rolledNumb;
            
            public void setNumSides(int sides) {
                numSides = sides;
            }
            
           public int getNumSides() {
              return numSides;  
            }
           
           public void setNumDice(int numOfDice) {
            numDice = numOfDice;
           }
            
            public int getNumDice() {
             return numDice;  
            }
            
         
            
            //@Override
            public int Roll() {
            numRolled = rand.nextInt(numSides) + 1;
            return numRolled;
           }
            public void setRoll(int rolledNum) {
            rolledNumb = rolledNum;
            
           }
           
           public int getRoll() {
            return rolledNumb;
            
           }
          
         
           
           public void printInfo() {
         //for (int i = 0; i < numDice; ++i) {
            System.out.print(rolledNumb + ", ");
         //}
           }
   
    }

Example output: Enter the number of dice and number of sides (enter 0 to exit): 12, 3, Enter the number of dice and number of sides (enter 0 to exit): 8, Enter the number of dice and number of sides (enter 0 to exit): 6, 1, 6, Enter the number of dice and number of sides (enter 0 to exit):

Results: D20:3, D10:8, D6:6, Total: 36

My program is properly retrieving the correct amount of rolls, and totaling them up. I just do not know how to give each object all their numbers in my final print. It feels like a simple fix, but I am unsure how to fix this.




pandas fill empty cells from a column with random range number or index number [duplicate]

read a excel file and i take the dataframe. The empty cells from excel now appears with NaN. For a column i try fill each one NaN cells with a random number with range (10000,100000)

import random
all_df.loc[all_df["name"].isnull(),'name'] = random.randrange(10000,100000)

but with this fill NaN cells from this column with one random number all NaN cells

another column with NaN cells i try fill them with index number of row

all_df.loc[all_df["name"].isnull(),'name'] = all_df["name"].index.values

can anyone help me with this problem?




dimanche 23 avril 2023

How to generate random pair less than several pairs in a given list in python

Given an L list with several elements as [n1,n2], I want to generate a random [i,j] pair such that i < n1 or j < n2 for all [n1,n2] in L. (i,j >= 1, but this is a minor detail.)

For instance, L = [[5, 3], [3, 7], [2, 11], [4, 6]], so if you think of this as part of a (max_first_in_L) by (max_second_in_L) "rectangle" (the +s denote the elements in L):

0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 +
0 0 0 0 0 0 +
0 0 0 0 0 +
0 0 +

I want to get the coordinates of a random zero, such as 1 = [2, 4].

My approach was to generate a list of all coordinate-pairs in the L-rectangle, remove all that are to the right and below the elements in L, and choose a random element from the remaining. If the L-rectangle is large - say, 2000 by 2000 -, this would create a 4_000_000 element long list, which is a bit hard on memory. Plus the removal.

I believe the optimal approach would be using indices and not creating large lists, but I haven't figured out how to do that.

Any help is greatly appreciated. (If possible, not using modules, or only basic ones.) In case this has already been asked before (to my knowledge, it hasn't), please point me in the right direction.

(Disclaimer: this is my first time using this platform and I'm a Python beginner. Pardon me for any mistakes I may have made in the posting of this question.)




DnD Dice Game Pt.2

I have made a lot of progress on my DnD game project!, but I am stumped on my outputting process. The purpose of this program is to simulate "rolling a handful of dice". I decided to accomplish this by using an object array list and creating a while loop that creates a new object and adds it to such array list. My main issue however is figuring out how to store each number rolled in each object such as five D20 dice, so object would be the D20, but then printing out number rolled.

My code so far:

// Dice.java
import java.util.Random;

public class Dice {
   
   protected int numRolled;
   final Random rand = new Random();
   
   public int getNumRolled() {
      return numRolled;
   }
    
   public void roll() {
        numRolled = rand.nextInt(5) + 1;
   }
}
   
}

//VarDice.java

import java.util.Scanner;
 
 public class VarDice extends Dice {
    
       //Scanner scnr = new Scanner(System.in);
            int numSides;
            int numDice;
            
            int rolledNum;
            public void setNumSides(int sides) {
                numSides = sides;
            }
            
           public int getNumSides() {
              return numSides;  
            }
           
           public void setNumDice(int numOfDice) {
            numDice = numOfDice;
           }
            
            public int getNumDice() {
             return numDice;  
            }
            
            
            @Override
            public void roll() {
            numRolled = rand.nextInt(numSides) + 1;
           }
           
           public void printInfo() {
            System.out.print(numRolled + ", ");  
           }
   
    }

//Main.java

import java.util.InputMismatchException;
import java.util.Scanner; 
import java.util.ArrayList;

public class Main {

   public static void printArrayList(ArrayList<VarDice> diceRolls) {
      int i;
      for(i = 0; i < diceRolls.size(); ++i) {
         System.out.print("D" + diceRolls.get(i).getNumSides() + ":");
         diceRolls.get(i).printInfo();
         System.out.println();
      }
   }
    
   public static void main(String[] args) {
      
      Scanner scnr = new Scanner(System.in);
         
          //Create boolean play that is true
          Boolean play = true;

         //Create int numSides and int numDice for how many dice are rolled

         int numSides;
         int numDice;
         int numRolled;

         //Create an int variable for results of the rolls (int results = 0;)
         int results = 0;
         
         //Create array list of object VarDice
      
        ArrayList<VarDice> diceRolls = new ArrayList<VarDice>();

      while (play) {
      //Greet user

      System.out.println("Enter the number of dice and number of sides (enter 0 to exit):");
      
      VarDice dice = new VarDice();
      
      try {
      //Get user input for numSides

      numDice = scnr.nextInt();

      //Get user input for numDice

      numSides = scnr.nextInt();

        if (numDice < 0 || numSides < 0) {
         throw new Exception ("Invalid input, both should be a positive number");
        }
      }

   //Create catch block for a inputmismatch 
      catch (InputMismatchException excpt) {
         System.out.println("Invalid input.");
         break;
      }

   //Create catch block for all expectations

      catch (Exception excpt) {
         System.out.println(excpt.getMessage());
         break;
      }
      
   if (numDice == 0 && numSides == 0) {
    play = false;  
   }
   
   else { 
      //A for loop is made for number of times a die is rolled according to user input  
   
   dice.setNumSides(numSides);

   for (int i = 0; i < numDice; ++i) {
      //numRolled = dice.roll();
      //dice.printInfo();
      //results += numRolled;
   }

   diceRolls.add(dice);
      }
        
    }
   
   System.out.println();
   System.out.println("Results:");
   printArrayList(diceRolls);
   System.out.println("Total: " + results);
   
   }
    
}

Side notes: In addition to not knowing how to store/print each number rolled for each type of dice, I am unsure how to give the total score obtained which would be every number rolled added together.




samedi 22 avril 2023

Counting elements and saving to CSV file

I have to write a program that:

  1. Generates 100 random lists with lengths increasing from 10 to 10000. Each list should consist of numbers drawn from the range [0, 1) using the random() function from the random module.
  2. For each list, he performs an experiment consisting in sorting it using four algorithms and write down the comparison numbers. The output of the experiment should be a list [n, lpq, lph, lpi, lpb],where n is the length of the input list and lpq, lph, lpi, lpb are the number of comparisons made through QUICK-SORT, HEAP-SORT, INSERTION-SORT and BUBBLE-SORT in turn. Note: It is important that each list be sorted with four algorithms. For this purpose, it is necessarysort a copy of the list (because sorting changes the list).
  3. Saves the results of experiments in a file in CSV format. Each result should be written on a separate line. You should use the csv module.

I have got a code, that generates 100 lists and I have a codes for four sorting algoritms. But how to combine it into one? Under I post what I have.

import random
num_lists = 100
min_length = 10
max_length = 10000
step = 10
lists=[]
for i in range(num_lists):
    length = random.randrange(min_length, max_length+1, step)
    lists.append([random.random() for _ in range(length)])
for lst in lists:
    print(lists)

# # QIUCK SORT

def partition(a, p, r):
    x = a[r]
    i = p - 1
    comparisons = 0
    for j in range(p, r):
        comparisons += 1
        if a[j] <= x:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i + 1], a[r] = a[r], a[i + 1]
    return i + 1, comparisons

def quick_sort(a, p, r):
    comparisons = 0
    if p < r:
        q, comparisons1 = partition(a, p, r)
        comparisons += comparisons1
        comparisons2 = 0
        comparisons2 += quick_sort(a, p, q - 1)
        comparisons2 += quick_sort(a, q + 1, r)
        comparisons += comparisons2
    return comparisons

# # HEAP SORT

def max_heapify(a, n, i):
    count = 0
    l, r = 2 * i + 1, 2 * i + 2
    largest = i
    if l < n:
        count += 1
        if a[l] > a[largest]:
            largest = l
    if r < n:
        count += 1
        if a[r] > a[largest]:
            largest = r
    if largest != i:
        a[i], a[largest] = a[largest], a[i]
        count += max_heapify(a, n, largest)
    return count

def build_max_heap(a):
    n = len(a)
    count = 0
    for i in range(n // 2, -1, -1):
        count += max_heapify(a, n, i)
    return count

def heap_sort(a):
    count = build_max_heap(a)
    n = len(a)
    for i in range(n - 1, 0, -1):
        a[0], a[i] = a[i], a[0]
        count += max_heapify(a, i, 0)
    return count

# BUBBLE SORT
def bubble_sort(a):
    n = len(a)
    comparisons = 0
    for i in range(n-1):
        zamiany = False
        for j in range(n-i-1):
            comparisons += 1
            if a[j] > a[j+1]:
                a[j], a[j+1] = a[j+1], a[j]
                zamiany = True
        if not zamiany:
            break
    return comparisons

# INSERTION SORT
def insertion_sort(a):
    comparisons = 0
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0 and a[j] > key:
            a[j + 1], a[j] = a[j], a[j + 1]
            j -= 1
            comparisons += 1
        if j >= 0:
            comparisons += 1
        a[j + 1] = key
    return comparisons

All the codes are okey and they are working. I have a problem with combining it into one big code. And maybe you know how to write the output into CSV as in the task?




Generate a 100 lists

Generate 100 lists of length from 10 to 10000. The elements of the list should be in the range [0,1). Python

import random
num_lists = 100
min_length = 10
max_length = 10000
step = 10
lists = []
for i in range(num_lists):
    # losowa długość listy
    length = random.randrange(min_length, max_length+1, step)
    # generowanie losowej listy z wartościami od 0 do 1
    lst = [random(0, 1) for _ in range(length)]
    lists.append(lst)
print(lst)

But the code gives one long list. What should I do? Please help




Using srand with pthread generate the same number in C

I'm trying to run this very simple code which generate a random number between 0 to 99 using multithreading:

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


void * NumGen(void * tid){
    int a = 0;
    a = rand() % 100;
    printf("a: %d\n",a);
};

int main()
{
    srand(time((NULL)));
    pthread_t tid0;
    pthread_t tid1;
    pthread_t tid2;
    pthread_t * pthreads[] = {&tid0,&tid1,&tid2};

    for (int i = 0; i < 3; i++)
        pthread_create(pthreads[i],NULL,NumGen,NULL);

    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}

Although I used srand(time((NULL))), the output I get is:

a: 41
a: 41
a: 41

What is the reason that I don't get different number each time? Thanks




vendredi 21 avril 2023

random walk position generation still generates duplicates even though there is a duplicate checker

As the title says, I created a random walk position generator for our dungeon crawler game. But everytime i generate a room, there is still a duplicate position generated even though there is a duplicate checker (located at posGenerator() while loop). Sometimes it generates good (no duplicate positions) and sometimes it generates duplicates.

Any ideas and opinions are welcomed. Thanks!

Vector2 position logs (duplicate generation)

Vector2 position logs (no duplicate generation)

posGenerator()

public void posGenerator() {
        Vector2 currentPosition = transform.position;
        positionList.Add(currentPosition);
        for(int i = 0; i < roomCount; i++){
            int currentDirection = RandomNumberGenerator();
            currentPosition = directionalPosition(currentPosition, currentDirection);
            while(positionList.Contains(currentPosition)){  // keep generating position until a new position is generated
                currentPosition = generateNewPosition(positionList[i], currentDirection);
            }
            positionList.Add(currentPosition);
            if(i+1 == roomCount){
                for(int j=1;j<positionList.Count;j++){
                    Debug.Log("Position " + j + ": " + positionList[j]);
                    directionList.Add(generateDirectionList(positionList[j-1], positionList[j]));
                }
            }
        }
    }

generateNewPosition()

public Vector2 generateNewPosition(Vector2 position, int direction) {
        int[] excludeDirections;

        switch (direction) {
            case 1: excludeDirections = new int[] { 2, 3, 4 }; break;
            case 2: excludeDirections = new int[] { 1, 3, 4 }; break;
            case 3: excludeDirections = new int[] { 1, 2, 4 }; break;
            default: excludeDirections = new int[] { 1, 2, 3 }; break;
        }

        int randomIndex = Random.Range(0, excludeDirections.Length);
        int newPosition = excludeDirections[randomIndex];
        return directionalPosition(position, newPosition);
    }

I tried changing the structure of while loop, tried using if else and refactoring my code. Still doesnt work. I expect no duplicate positions




Javascript math.random gives too many duplicate values

Using NodeJS 14. I have a script that needs to generate 10,000 unique numbers between 1 and 10000. i have a function that takes 1 as min and 10000 as max. When I run it, only ~7000 are unique the rest are duplicates. I understand that not all 10k would be unique, but 30%? What can I do to get more of then unique?

function is:

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

sorted sample 1856 1871 1873 1879 1879 1885 1895 1903 1911 1911




How to assign weights to numpy random choice based on largest values?

So given a numpy array of numbers, for example:

np.array([9, 4, 50, 6, 7, 19, 30])

I want to write a function that randomly chooses the index of one of the elements in the array. However, I want the indices with larger values (for example indices 2 and 6) to have a bigger probability to be chosen.

I have thought about using numpy.random.choice, however I do not know how I should predefine the weights. The numpy.random.choice function must be given a list of probabilities for each of the entries in the array, and it should sum to 1. But I really struggle with understanding how to calculate such probabilities for my problem. Does someone have some tips? I would really appreciate some help




If confidence intervals overlap in a crossed-effects model, aren't they significant?

I tried Hierarchical age-period-cohort analysis using Stata. Below is the command I used and got the random effects estimate.

Then, I tried to plot the YEAR and COHORT results with 95% CI on the graphs. The images show that both YEAR and COHORT tend to grow, but the confidence intervals overlap.

enter image description here

Because I can see some differences between the first bars and the end bars on both graphs, I doubt whether I cannot say that there are some differences between years and cohorts.

Please help me how can interpret the data in my research.

Thanks.




How to quickly choose a number in a wide range and avoiding prohibited numbers

I am making a snake game and I need to place an apple in the x*y map in each loop, this apple cannot be placed on the body of the snake

My code probably looks like this

// snake_body is a array include all body's coordinate
snake_body := []

// Find coordinates in a loop that are not in the snake_body
function setApple()
    loop
        apple_x := random(map_x)
        apple_x := random(map_y)
        if not apple_x, apple_x in snake_body
            return apple_x, apple_x

This is a poor design that gives quick results when the snake is relatively short, but once you get into the late game and the snake's body takes up most of the coordinates, the loop needs to be executed very many times to find valid coordinates

My current solution is to also create and maintain a coordinate array that is not used by the snake

empty_ground := []

function refresh()
    // Use this method in each loop to update the elements in the empty ground

function setApple()
    return random(empty_ground)

This would require me to maintain a very large coordinate table, and updating it would also require some arithmetic power, and I would like to know if there is any better algorithm that can solve this problem quickly?




jeudi 20 avril 2023

return a series of keys based on value python randomly generated in separate line

I'm trying to return a series of values when randomly generating a number which then corresponds to a certain key.

This is a miniature version of my dictionary (key = word, value = character count) :


import random

myDict = {
"lire": "4",
"l'art": "5",
"écrire": "6",
"écouter": "7",
"compter": "7",
"répéter": "7",
"étudier": "7",
"aller à": "7",
"calculer": "8",
"regarder": "8"}

I tried two options.

1)

def search(myDict, lookup):
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                return key

print(search(myDict, str(random.randint(4,10)))
    print([k for k, v in myDict.items() if v == 'random.randint(4,10)'])
    

    Both options work when the value is "4" and print lire or ['lire'] respectively. However, when the value is 4 (without quotation marks) or random.randint(4,10) or 'random.randint(4,10)', it returns [].

    The value seemingly has to be a string but if I search for the random function in '' then it obviously does not return a key because none of the values are called 'random.randint(4,10)'.

    If someone could find a solution where I can link the two sections (randomly generated number and valid set of keys from random value), that would be great. Thank you.




    Is my approach valid for showing that my algorithm (usage of python's random.sample) is NOT susceptible to the Birthday Problem?

    I tried to prove to myself one way or the other whether the way I was generating these "codes" was susceptible to the Birthday Problem, in which case--I tell myself--collisions should eventually grow with the square of the number of reserved codes, with a large enough number of reserved codes.

    I believe the approximated formula I am recalling was collision_probability = k**2 / 2n, where k is the number of items (or codes which will be reserved) and n is the number of buckets (or possible codes).

    Below, I go on to calculate P(collision) for each level of reserved codes, 0 - 1 million. Then I fit the probabilities at each point to a line of best fit. --- My most important question is, did I assume what was I trying to prove somewhere along the way here? Or otherwise, miss the point of the birthday problem's effect on the probability of putting K items into N buckets?

    
        import itertools
        import sys
        import csv
        import random
        import string
        from functools import partial
        
        
        def calculate_num_collisions(gen_code, iterations, codes=None):
            num_collisions = 0
            for _ in range(iterations):
                code = gen_code()
                if code in codes:
                    num_collisions += 1
        
            # Round to 4 digits, for probability visibility down to e.g. 0.0001,
            # or 0.01% probability, in other words, really 2 digits
            return round(num_collisions / iterations, 4)
        
        
        def generate_code(possible_values, length):
            # Try to use the exact same algorithm as in my codebase, another place
            return "".join(random.sample(possible_values, length))
        
        
        if __name__ == "__main__":
        
            if len(sys.argv) < 2:
                print("Please supply output file.")
                sys.exit(1)
        
            possible_values = string.digits
            length = 6
            iterations_to_check = 40
            # iterations is how many samples to take at each level of codes already assigned. 
        
            _gen_code = partial(generate_code, possible_values, length)
        
            with open(sys.argv[1], "w") as csvfile:
        
                codes = set()
                total_buckets = len(possible_values) ** length
                fieldnames = ["current_buckets", "observed_collision_probability"]
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
        
                # rather than generate codes randomly in this outer loop, create a generator
                # that will produce all possible such codes -- wastes less time
                all_possibilities = itertools.product(possible_values, repeat=length)
                for i in range(total_buckets):
        
                    observed_collision_probability = calculate_num_collisions(
                        gen_code=_gen_code, iterations=iterations_to_check, codes=codes
                    )
                    current_buckets = total_buckets - len(codes)
                    writer.writerow(
                        dict(
                            observed_collision_probability=observed_collision_probability,
                            current_buckets=current_buckets,
                        )
                    )
                    try:
                        codes.add("".join(next(all_possibilities)))
                    except StopIteration:
                        break
    
    

    So, when I take the data generated from this script, and plot it along with a fitted linear equation...

    usage of curve_fit

    I get the following:

    data fitted to a linear model

    The point is, it looks very linear.

    ... Choosing a quadratic objective function instead results in a coefficient of 0 on the quadratic component. (Smaller questions might include whether I used the scipy.optimize.curve_fit function correctly here, as I am new to usage of data science python libraries.)

    Thanks in advance, sorry for openness of question.

    I referred to these questions, but I'm still confused:




    mercredi 19 avril 2023

    PostgreSQL: How to select N random entries per column value

    I have the following code

    with my_table (id, student, category, score)
    as (values 
    (1, 'Alex', 'A', 11),
    (2, 'Alex', 'D', 4),
    (2, 'Alex', 'B', 50),
    (2, 'Alex', 'C', 83),
    (2, 'Alex', 'D', 5),
    (3, 'Bill', 'A', 81),
    (6, 'Carl', 'C', 5),
    (7, 'Carl', 'D', 2),
    (7, 'Carl', 'B', 21),
    (7, 'Carl', 'A', 55),
    (7, 'Carl', 'A', 86),
    (7, 'Carl', 'D', 10)
    )
    
    
    select *,
         row_number() over (partition by student order by random()) as row_sort
    from my_table
    

    I would like to know how I can adjust it to return 2 random entries per student.




    mardi 18 avril 2023

    Why does np.random.choice take so much longer than np.random.randint?

    I've been reading that np.random.choice is faster than np.random.randint, however when comparing the speed difference between

    import numpy as np
    
    for i in range(100000):
        np.random.choice(100)
    

    and

    import numpy as np
    
    for i in range(100000):
        np.random.randint(100)
    

    np.random.randint is appreciably faster. What's the difference between these two?




    Size of seeds for numpy.random

    I want to run some code using numpy.random and keep track of what the seed is so that if the output is interesting, I can recreate and play around with that randomly generated instance. Therefore, I want the setup to involve something like

    import numpy as np
    s = np.random.randint(10000000000)
    print(s)
    np.random.seed(s)
    ### remainder of code
    

    so that the code is still running randomly, but I also have retained the seed s. The value 10000000000 was chosen arbitrarily; what is the appropriate scale for numpy.random's seeding? e.g. are seeds all the same modulo 2^32?




    C++ Big integer, random

    How do I generate a random number in the specified range? The problem is that the range numbers can be very large (2^256).

    Tried to understand, can be through the standard library < random >




    lundi 17 avril 2023

    Repeatedly drawing indices with numpy random choice with weights

    What I am doing at the moment:

    import numpy as np
    
    d = 60000
    n_choice = 1000
    n_samples = 5000
    
    # some probability vector
    p = np.random.randint(d)
    p = p/np.sum(p)
    
    rng = np.default_rng(123)
    samples = np.empty((n_choice, n_samples))
    
    for i in range(n_samples):
        samples[:, i] = rng.choice(d, size=n_choice, replace=False, p=p, shuffle=False)
    

    This is a bit slow for my taste. Is there a way to speed this up? E.g., by replacing the loop with a trick or using some other form of simulation?

    I skimmed through similar questions on stack, but only found this where the weights are uniform and d=n_choice and this where weights are given but only the rows (columns) of the samples array have to be unique.




    Making a random presence/absence matrix in R with row and column constraints

    I am trying to create a randomized matrix in R. It needs to be a presence/absence matrix, such that all values in the matrix are either 0 or 1. But I also need to specify row and column totals, for example, a 5x5 table where the row totals are: r1 = 4, r2, = 2, r3 = 3, r4 = 5, r5 = 3 and the column totals are: c1 = 5, c2 = 1, c3 = 5, c4 = 2, c5 = 4.

    I was hoping to use r2dtable(), but I don't think you can force this function to use only 0's and 1's.

    Are there any ideas?

    Thanks!

    I've tried using r2dtable() but end up with values higher than 1.




    How to generate random number from between max and min

    For instance max = 50 and min = 1 I want to find a random number from 48 to 5 what would the code be?

    I wrote the part on how to find a random number from a smaller no. To a larger one.

    Int r = nextInt(max - min + 1) + min

    But I’m confused as to how to do it the other way around

    I tried substituting and adding the max min around but the result I want did not appear




    dimanche 16 avril 2023

    DnD Dice Roll Simulation

    I am Trying to make a simulated dice rolling game for my friends. I want to utilize two classes Dice and a child class VarDice which will let user choose how many sides. However, I am struggling to get my derived class to work properly.

    This is my parent class :

    import java.util.Random;
    
    public class Dice {
       
       protected int numRolled;
       final Random rand = new Random();
        
        
       public void roll() {
            numRolled = rand.nextInt(5) + 1;
       }
       public int getNumRolled() {
          return numRolled;
       }
       
    }
    

    This is the derived class:

        import java.util.Random;
        
        
        public class VarDice extends Dice {
        
           public static void main(String[] args) {
                Scanner scnr = new Scanner(System.in);
                int numSides;
                
                public void setNumSides(int sides) {
                    numSides = sides;
                }
                
               public int getNumSides() {
                  return numSides;  
                }
                
                @Override
                public void roll() {
                numRolled = rand.nextInt(numSides) + 1;
               }
        
        }
        }
    

    This is finally my main code:

    import java.util.Scanner; 
    
        public class Main {
        
           public static void main(String[] args) {
                Scanner scnr = new Scanner(System.in);
                 int numSides;
    
                 VarDice dice = new VarDice();
    
                 numSides = scar.nextInt();
    
                 dice.setNumSides(numSides);
                 
                 dice.roll();
                 System.out.println("The dice come up " + dice.getNumRolled()); 
            
        
            }
        
        }
    

    I want the user to be able to input how many sides are on their dice and how many dice, but my VarDice class is not overriding the roll method very well and I am a little bit lost on the errors I am getting... I appreciate the help and hope the format is appropriate.




    Python: Why is my randomizer not working?

    I'm new to coding with Python. I'm trying to create 5 variables and assign a random number between 1 and 100 to each one and then adding them all at the end. I typed in the random.randint() command that I've seen online but it is coming back with an error. How do I fix this?

    def main():
        a=random.randint(1,100)
        b=random.randint(1,100)
        c=random.randint(1,100)
        d=random.randint(1,100)
        e=random.randint(1,100)
        result=a+b+c+d+e
        print("Here is the sum of your randomly generated numbers!:\n",result)
    

    This is the error that pops up when I try to run the module

    main()
    Traceback (most recent call last):
      File "<pyshell#27>", line 1, in <module>
        main()
      File "<pyshell#26>", line 2, in main
        a=random.randint(1,100)
    NameError: name 'random' is not defined
    



    How to generate a unique 8 digit number using crypto in node js?

    I want to generate a unique number everytime. I have used crypto module for that.

    const alphanu = crypto.randomBytes(16).toString('hex')
    

    This will generate alphanumeric string of length 32. I want to generate a number of length 8.

    I tried randomInt as well.

    const num = crypto.randomInt(10000000,99999999)
    

    Will it always generate a unique number?

    How do I achieve what I want?




    Random Number Generator as Dice

    Ok I have a question about the Random Number Generator. However, let me explain I know how it works. So there is going to be minimal code. My question is what I call a floating index. This would be used as dice style generator. So I will explain the game example and then a piece of code.

    My father is wanting to create a DnD style game. With Attack and defense. The random number generator is the dice. However with each player will have a +Attack bonus and so forth. Kind of like Risk.

    My question is when the index of say (1,6) with a attack bonus of (3). The random number generator is (1,6). Can I float that index by the players attack damage on the roll.

    So for example one player may have (1,6) and another player could have (1,20). As they level up those numbers will change.

    So can I use an int variable in a random number generator as follows.

    Val X = 0
    Val y = playerAttack.tostring
     
    ....... (X , y)
    

    So basically if a random number generator is (1,6) then player two with (1,20) will throw an out of index.

    So my question is can I float that number to auto change the index based on the player stats.

    Think of the game Dungeon and Dragons. Or would I have to do the generator as (1, 100) and the use of else statements to limit the number in the index.

    I am needing clarification because I am under the assumption that I would need several random number generators with different indexes.

    Any help would be greatly appreciated.




    samedi 15 avril 2023

    How to properly generate multiple random values using random in c++?

    I am writing a program that selects a random string from a 2D vector in C++. This involves generating 2 random values; the first to select a subvector, and the second to select a string from that subvector.

    std::string Mountains::getRandomMountain()
    {
        int randomValue;
        string randomMountain;
    
        std::vector<std::string>currentRange;
    
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<int> dist1(0, rangeNames.size() - 1);
    
        randomValue = dist1(gen);
    
        correctRange = rangeNames[randomValue];
    
        currentRange = allMountains[randomValue];
    
    
        std::uniform_int_distribution<int> dist2(0, currentRange.size() - 1);
        randomValue = dist2(gen);
    
    
        randomMountain = currentRange[randomValue];
    
    
        return randomMountain;
    
    }
    

    This version of the code functions correctly when I debug it in Visual Studio. Still, when I try to Debug Test I am presented with a Debug Assertion Failed error: invalid min and max arguments for uniform_int. This only occurs the second time I try to access uniform_int_distribution, not the first. Any help would be much appreciated.




    С++ Big integer for array and for rand [closed]

    I implemented the cryptography method. But there is one thing. It works right for small values. I have a question, do I have any library so that I can use large integer variables? In addition, I need an array of such numbers and a rand function for large numbers. Maybe there's a library for that, or something like that? Implemented on C++. If there are ideas on how to do this in other languages, then please write. Thank you in advance.

    I tried the InfInt library, but there is no way to make a large random number in it. These failures: https://faheel.github.io/BigInt/ https://github.com/rgroshanrg/bigint




    vendredi 14 avril 2023

    T-SQL function that return random huge Int

    I need to prepare function that will return random quite a huge int. I'm using "huge" adjective to not mix with bigint.

    CREATE FUNCTION fn_RandomHugeInt() 
    RETURNS int 
    AS
    BEGIN 
        RETURN (SELECT ABS(CHECKSUM(NEWID()) % (2147483647 - 2000000000 + 1)) + 2000000000)
    END
    
    SELECT fn_RandomHugeInt()
    

    Unfortunately it seems that that such code doesn't work




    jeudi 13 avril 2023

    Replace NA value with a bunch of randomly generated values in R

    I want to filter my Title column and then replace the NA values in Age column with a bunch of randomly generated values(within min and max age range). I tried the following command

    titanic_df4 <- titanic_df3 %>% filter(titanic_df3$Title=='Mr.') %>% mutate(Age = replace_na(Age, runif(1, min=14, max=57)))

    but it just replace the na value with one specific value within the range. What should I do?

    Tried this

    titanic_df4 <- titanic_df3 %>% filter(titanic_df3$Title=='Mr.') %>% mutate(Age = replace_na(Age, runif(1, min=14, max=57)))
    



    Variables using "random()" change everytime they are called

    void draw() {
    z = float(random(255));
    x = float(random(255));
    c = float(random(255));
    background(z, x, c);
    delay(500);
    background(c, x, z);
    }
    

    I want the z, x, and c variables to not change upon being called into the 2nd background() command, but can't quite figure it out.

    I tried making other variables, using frameRate(1), and moving the delay(500) command past the 2nd background(), but unfortunately the variables change upon being called the 2nd time, and i want them to keep their value until the next void draw() loop.




    mercredi 12 avril 2023

    Is this a valid way of getting the "memory address" of an object in Javascript?

    For my application, I basically need a way to convert a Javascript object to a unique number, such that it can be used as a seed in a deterministic random number generator. That is, given an object as the input to the random number generator, it will always return the same output.

    This would be pretty easy if you could just get the memory address of an object and use that as the seed, but that doesn't seem possible. Another idea would be to use a Map, and then have an auto-incrementing number for each object insertion, but then you would have to somehow keep track of what was added so the map wouldn't balloon to ridiculous memory sizes after a while.

    Then I thought, would a WeakMap work for something like this?

    That is, doing something like this?

    let incrementingID = 1;
    
    function getIncrementingID() {
      incrementingID++;
    
      return incrementingID;
    }
    
    const weak = new WeakMap();
    
    function getSeed(o) {
      const maybeSeed = weak.get(o);
    
      if (maybeSeed === undefined) {
        const newSeed = getIncrementingID();
    
        weak.set(o, newSeed);
    
        return newSeed;
      }
    
      return maybeSeed;
    }
    

    Then, given the same object, it will always produce a unique seed value, and also if the object ever goes out of scope, it should automatically be deleted from the map, right? So there will never be a memory leak?

    This seems to work, but I've never used a WeakMap before and I'm not sure if this is a proper solution, or if there is a better way.




    mardi 11 avril 2023

    how can generate random string in arm

    I can't generate random string in arm

    I have searched on chatgpt and i found this

    `; Initialize the LCG LDR r0, =seed ; Load the seed value into r0 MOV r1, #1103515245 MOV r2, #12345

    ; Generate the random string MOV r3, #0 ; Initialize the string index to 0 loop: LDR r4, =string ; Load the address of the string into r4 ADD r4, r4, r3 ; Add the string index to the address LDR r5, [r4] ; Load the current character from the string ADD r0, r0, r1 ; Update the LCG seed ADD r0, r0, r2 MOV r6, #256 ; Compute 256 (the number of possible characters) UMULL r7, r8, r0, r6 MOV r5, r8 ; Compute the remainder of the division by 256 STRB r5, [r4] ; Store the random character in the string ADD r3, r3, #1 ; Increment the string index CMP r3, #length ; Compare the string index with the desired length BNE loop ; Loop if the index is less than the length ` how can i use this in my template an arm code that can generate random string




    Rust eqivalent to scipy truncnorm

    Trying to generate a random number between 0-200 in Rust using normal distribution. Is this something that I have to implement myself or is there a crate like scipy for rust that has truncnorm?

    I've tried using some combination of .gen_range() and .sample(Standard) but can't seem to get anything to work.




    Limit same Random number JavaScript

    im selecting a statement from a json file, but the one i get is done by a randome number, but i want to avoid getting the same one consecutive times, is there a way to limit this?

    Right now this is the code i have for that part, it gives me a random question beetween the amounth of questions i have

            const json = JSON.parse(fs.readFileSync('quiz.json'));
            const quizNum =  Math.floor(Math.random() * 22);
    

    i was thinking something to avoid getting the same question if it was given in the last 2 or 3 times




    Python loop does not always break

    I have written a loop that samples from an existing pool of images to create a (pseudo-)randomized list. The goal is to have a list where the images appear a specific number of times but without consecutively repeating the same image.

    I have tried the following code:

    import random
    
    number_img1 = number_img2 = 2
    number_img3 = number_img4 = 4
    number_img5 = number_img6 = 6
    
    total_images = number_img1 + number_img2 + \
        number_img3 + number_img4 + number_img5 + number_img6
    
    stimulus_full_random = []
    new_item = 0
    
    while len(stimulus_full_random) < total_images:
        new_item = random.choice(stimulus_full)
        if len(stimulus_full_random) == 0:
            stimulus_full_random.append(new_item)
        elif 0 < len(stimulus_full_random) < total_images:
            if new_item == "img1_full" and stimulus_full_random.count("img1_full") < number_img1:
                if new_item != stimulus_full_random[-1]:
                    stimulus_full_random.append(new_item)
                else:
                    stimulus_full_random[-1] = new_item
            elif new_item == "img2_full" and stimulus_full_random.count("img2_full") < number_img2:
                if new_item != stimulus_full_random[-1]:
                    stimulus_full_random.append(new_item)
                else:
                    stimulus_full_random[-1] = new_item
            elif new_item == "img3_full" and stimulus_full_random.count("img3_full") < number_img3:
                if new_item != stimulus_full_random[-1]:
                    stimulus_full_random.append(new_item)
                else:
                    stimulus_full_random[-1] = new_item
            elif new_item == "img4_full" and stimulus_full_random.count("img4_full") < number_img4:
                if new_item != stimulus_full_random[-1]:
                    stimulus_full_random.append(new_item)
                else:
                    stimulus_full_random[-1] = new_item
            elif new_item == "img5_full" and stimulus_full_random.count("img5_full") < number_img5:
                if new_item != stimulus_full_random[-1]:
                    stimulus_full_random.append(new_item)
                else:
                    stimulus_full_random[-1] = new_item
            elif new_item == "img6_full" and stimulus_full_random.count("img6_full") < number_img6:
                if new_item != stimulus_full_random[-1]:
                    stimulus_full_random.append(new_item)
                else:
                    stimulus_full_random[-1] = new_item
        else:
            break
    
    print(stimulus_full_random)
    

    In some cases, it produces the desired output but sometimes, the loop does not break / the program runs on forever. I have tried several different versions, but always the same result. I am fairly new to programming and I do not understand why (only in some instances) this code does not work. Help is very much appreciated!




    lundi 10 avril 2023

    Random item from PHP array = "access array offset"

    Im trying to get a single random key => value from an array but im getting the following error. Any ideas what im doing wrong?

    $colors = array("Yellow Sun" => "FAE500", "Golden" => "fab600", "Orange Juice" => "FF6D00", "Photo Blue" => "A2E5F4");
    
    
    $shuffled = shuffle($colors);
    print_r($shuffled[0]);
    

    "Warning: Trying to access array offset on value of type bool in"




    How can I generate cryptographically strong random strings with a given length

    I need to generate cryptographically strong random alphanumeric strings with a specified length, only using the following characters.

    • A-Z
    • a-z
    • 0-9

    Is there a way to accomplish this in C#?




    dimanche 9 avril 2023

    Random number generator in C++ using rand_r function [duplicate]

    I have been trying to generate random number in C++ using rand_r, while using multiple threads for parallel implementation in a pretty big code, which utilizes a lot of seeds. Also, I need to run my simulation multiple times. I want a different random number generated for the same seed in a particular node. However, I keep getting the same sequence (which is understandable due to same initialization of the random generator). Any ideas to reset the random generator? I have explained the question using an example below. I cannot use rand() as it is not thread safe, and I am using an older version of c++ (4.4.7). Also, I generate a hell lot of seeds in one simulation, so kindly do not suggest using a different seed in every simulation.

    Example Code:

    #include <stdio.h>
    #include <mpi.h>
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <sstream>
    #include <stdlib.h>
    using namespace std;
    
     int main(int argc, char** argv) {
       int rank;
       MPI_Init(&argc, &argv);
       MPI_Comm_rank(MPI_COMM_WORLD, &rank);
       unsigned int rank2 = rank;
       int random_n = rand_r(&rank2);
       cout << "Random number is: " << random_n << " in node: " << rank << endl;
       return MPI_Finalize();
     }
    
    

    The result generated is:

    Random number is: 1012484 in node: 0
    Random number is: 476707713 in node: 1
    Random number is: 952403967 in node: 2
    Random number is: 1430195325 in node: 3
    

    Upon executing the simulation again, I want different random number in the nodes. However, the result I get is:

    Random number is: 1012484 in node: 0
    Random number is: 476707713 in node: 1
    Random number is: 952403967 in node: 2
    Random number is: 1430195325 in node: 3
    

    Any help on this would be appreciated!!




    samedi 8 avril 2023

    Jmeter_Passing differnet account numbers from parameters file in single request

    How to pass several values in a single request, if I have 20 account numbers, we must pass 5 distinct numbers each time in single iteration, For EX my script (single request) has 5 calls and we need to pass 5 different account numbers each time from single request (post method),

    Accnum:- 2123 5678 9890 6780 8899 9990 7651 8976 Example:-

    call 1: - 2123 call 2: - 9890 call 3: - 5678 so on...

    I tried adding 5 csv files, but it will be time consuming, so I wanted to use formula.




    How do I use an lcg "non-sequentially"

    I want to create a game that is a 2d dungeon, each tile in the dungeon will have the same chance of being a solid or air block, the dungeon will be infinite and every time you spawn a dungeon it will be with a seed, same seed, same dungeon.

    Thinking a bit I came to the conclusion that I should use a rng in a different way, to determine if a box is solid or not, the x and y coordinates of that box are taken and multiplied, then the seed of the dungeon is added and the result is fed into the rng as a seed, which is an lcg. In this way, it is very easy to program.

    The problem here is that the lcgs don't work that way, and if you try to do it like this, in the coordinate line x=0 or y=0, the seed of those cells will always be that of the dungeon, so the same will be generated number. And in the rest of the cells a pattern is generated that is clearly not random. This is because the lcg behaves like a function.

    I have thought that the solution is that when calculating the seed for each box, the formula is more complex, adding randomness to the final seed, but I can't find a good formula.

    In the formula to calculate the seed of each cell, I have tried to use trigonometric functions, but I don't know if it is the best way, it could be that the pattern was more random but that the numbers did not take long to repeat themselves.




    Analysis of pseudo-random sequences by AI

    Are there any papers on studying pseudo-random numbers using AI?

    The first idea would be to train an AI to get a initial segment of a pseudo-random sequence of numbers (a binary sequence will probably do it) and the AI ​​returns a probability distribution for the next number. The pseudo-random sequence can be generated in any way. Theoretically, it could also be completely random. In this case, the AI ​​should recognize this and return the uniform distribution (on {0,1}). The intersting case would be if the pseudo-random sequence is given by some algorithm. Here it would then be intersting which types of algorithms the AI ​​can handle and which not.




    Generate random numbers in R

    In R, how to generate 150 random numbers, using the numbers from 1 to 100 at least once?

    library(tidyverse)
    set.seed(123)
    df <- tibble(Random_number = sample(x = 1:100,
                                        size = 150,
                                        replace = TRUE)) %>% 
      arrange(Random_number) %>% 
      view()
    

    For example, the numbers 1, 2, 3, etc. never appeared. I know that this script is not good enough to make the numbers 1 through 100 always appear at least once, as I expect, but I have no idea how to actually write the script.




    jeudi 6 avril 2023

    python - how to add a random 7 digit number to a random number of a list as a str [duplicate]

    from random import randint
    import random
    
    
    my_list=['169', '170', '149', '150', '171', '168', '136', '137', '138', '545', '505', '636', '164', '165', '172', '623', '506', '519', '154', '155', '567', '173', '159', '160', '604', '274', '275', '295', '637', '292', '492', '289', '677', '294', '493', '279', '280', '288', '284', '285', '638', '291', '640', '293', '675', '282', '283', '286', '287', '296', '297', '290', '400', '401', '404', '405', '397', '398', '399', '647', '502', '584', '402', '403', '392', '393', '395', '396', '386', '387', '503', '444', '551', '447', '561', '445', '718', '083', '446', '448', '552', '543', '442', '443', '051', '052', '053', '058', '055', '617', '057', '618', '059', '060', '061', '062', '544', '056', '571', '593', '667', '348', '586', '338', '339', '343', '344', '346', '337', '554', '469', '537', '345', '470', '341', '342', '483', '484', '557', '418', '416', '417', '412', '413', '592', '612', '613', '406', '407', '421', '598', '419', '385', '420', '528', '213', '214', '205', '206', '498', '568', '711', '217', '218', '221', '582', '483', '625', '576', '578', '227', '208', '209', '225', '577', '712', '215', '216', '626', '627', '579', '713', '499', '222', '219', '220', '500', '501', '623', '497', '223', '689', '487', '226', '224', '386', '211', '212', '628', '202', '203', '531', '288', '261', '273', '630', '264', '518', '631', '258', '259', '570', '265', '268', '269', '653', '517', '569', '267', '262', '263', '593', '266', '693', '271', '272', '694', '270', '516', '333', '334', '691', '323', '322', '595', '395', '641', '596', '336', '335', '496', '337', '324', '325', '394', '330', '332', '331', '687', '422', '423', '599', '600', '688', '424', '425', '426', '550', '697', '384', '377', '378', '558', '385', '646', '375', '376', '372', '373', '379', '380', '383', '674', '381', '382', '676', '722', '542', '312', '313', '317', '310', '311', '302', '303', '583', '321', '382', '304', '305', '536', '605', '308', '309', '306', '307', '319', '313', '314', '606', '320', '698', '298', '299', '535', '315', '316', '318', '607', '608', '508', '538', '728', '509', '438', '439', '580', '590', '559', '588', '431', '432', '037', '038', '702', '240', '241', '670', '648', '252', '678', '253', '649', '513', '546', '671', '246', '247', '654', '548', '547', '655', '248', '249', '253', '514', '665', '673', '228', '229', '230', '679', '256', '257', '244', '245', '681', '723', '236', '237', '683', '656', '250', '251', '515', '242', '243', '238', '239', '657', '255', '684', '700', '642', '457', '456', '458', '459', '460', '530', '520', '358', '359', '682', '703', '364', '365', '371', '701', '720', '366', '367', '704', '361', '362', '369', '370', '635', '668', '533', '705', '699', '669', '725', '597', '611', '525', '181', '527', '585', '685', '663', '192', '193', '174', '175', '183', '184', '481', '706', '194', '195', '185', '186', '182', '199', '200', '198', '662', '190', '191', '692', '189', '707', '526', '187', '188', '729', '730', '196', '197', '661', '680', '643', '562', '572', '074', '644', '072', '073', '069', '070', '521', '573', '522', '724', '076', '077', '650', '574', '078', '079', '081', '084', '651', '086', '087', '089', '090', '553', '091', '092', '093', '094', '097', '098', '096', '105', '106', '063', '067', '068', '075', '591', '082', '635', '524', '468', '465', '461', '462', '467', '632', '555', '633', '629', '466', '696', '721', '064', '065', '523', '652', '719', '716', '085', '088', '563', '529', '353', '349', '350', '355', '609', '351', '352', '354', '732', '357', '532', '610', '356', '556', '658', '001', '002', '003', '004', '005', '006', '007', '008', '011', '020', '025', '015', '043', '666', '489', '044', '045', '048', '049', '490', '491', '695', '659', '031', '032', '664', '717', '041', '042', '471', '472', '454', '581', '449', '450', '616', '534', '455', '451', '726', '634', '453', '727', '452', '145', '146', '731', '690', '601', '504', '163', '714', '715', '566', '166', '167', '161', '162', '686', '603', '619', '118', '127', '128', '129', '620', '621', '549', '564', '575', '113', '114', '122', '540', '660', '120', '512', '510', '511', '119', '115', '112', '110', '111', '125', '126', '565', '121', '116', '117', '541', '622', '124', '108', '109', '123', '428', '427', '507', '158', '615', '152', '153']
    
    def digit(n):
        start=10**(n-1)
        end=(10**n)-1
        return randint(start,end)
    
    first=print(random.choice(my_list))
    second=print(digit(7))
    
    while True:
        print(str(first)+str(second))
    

    I wanted to add a random 7 digit number to a random number from "my_list" but it gives me "NoneNone" I want my output to be for example "1691234567" (169 is a random number from my_list) and (1234567 is a random 7 digit number)




    mercredi 5 avril 2023

    Random password generator + algorithm

    I'm currently developing a CLI password generator and I've been trying to come up with ways of randomizing characters between a defined set of chars. I know the srand(time(NULL)) method but as far as I know, it's a bit incosistent and not so safe to generate random passwords. I also know there is a way of randomizing numbers using the libsodium library for C (according to this topic), but I'm not sure how to use it. Should I install all the dependencies in my project? Is a relative small project to have such a huge library. Although I plan expanding it as time goes by, I don't know if it's worth having a huge library and not use most of its functions. On top of that, are there specific algorithms to generate passwords other than just randomizing characters? Should I also randomize the array within itself following another algorithm for better consistency like the Fisher Yates Shuffle? Thanks in advance!




    Java: trying to get random numbers out of class and read and changed in another [duplicate]

    I am trying to make it so when you click on the buttons where it says "Power" + n or "power" + N it gives random value added to p. I try to make the variables static but it doesn't like it.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import java.awt.*;
    import javax.swing.*;
    
    class DungeonRandomizer {
        
        public static class DungeonRand extends Canvas {
            public void paint(Graphics g) {
                int p = 0;
                int w = 5;
                int c = 0;
                Random rand = new Random();
                int n = rand.nextInt(25);
                int N = rand.nextInt(25);
                System.out.println("N" + N);
                System.out.println("n" + n);
                Color NeonBlue = new Color(64, 46, 255);
                Color Brown = new Color(64, 46, 32);
                g.setFont(g.getFont().deriveFont(20.0f));
                g.setColor(Brown);
                g.fillRect(0, 0, 1000, 100);
                g.setColor(NeonBlue);
                g.drawString("Your Power " + p, 10, 50);
                g.setColor(Brown);
                g.fillRoundRect(150, 400, 200, 200, 25, 25);
                g.fillRoundRect(650, 400, 200, 200, 25, 25);
                g.setColor(NeonBlue);
                g.drawString("Power" +   N, 215, 510);
                g.drawString("Power" + n, 715, 510);
                setBackground(Color.darkGray);
                setVisible(true);
            }
    
            static int l = 0;
            static int x = 0;
            final static  DungeonRand[] m = {new DungeonRand()};
    
            public abstract static class Button extends JFrame implements ActionListener {
                
                public static void main(String[] args) {
                    JButton B = new JButton("Select");
                    JButton b = new JButton("Select");
                    JFrame f = new JFrame("Floor" + l);
                    JFrame F = new JFrame("Floor" + l);
                    Random rand = new Random();
                    f.setSize(1000, 1000);
                    f.setVisible(true);
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.add(b);
                    f.add(B);
                    f.add(m[0]);
                    Color Brown = new Color(64, 46, 32);
                    b.setLocation(150, 525);
                    b.setSize(200, 200);
                    b.setBorderPainted(false);
                    b.setBackground(Brown);
                    Color NeonBlue = new Color(64, 46, 255);
                    b.setForeground(NeonBlue);
                    b.setFont(b.getFont().deriveFont(20.0f));
                    B.setLocation(650, 525);
                    B.setBorderPainted(false);
                    B.setBackground(Brown);
                    B.setForeground(NeonBlue);
                    B.setFont(b.getFont().deriveFont(20.0f));
                    B.setSize(200, 200);
                    b.enableInputMethods(true);
                    ActionListener ButtonListener = new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            p+=n;
                            l+=1;
                            f.dispose();
                            F.setSize(1000, 1000);
                            F.setVisible(true);
                            F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                            F.add(b);
                            F.add(B);
                            F.add(m[0]);
                            Color Brown = new Color(64, 46, 32);
                            b.setLocation(150, 525);
                            b.setSize(200, 200);
                            b.setBorderPainted(false);
                            b.setBackground(Brown);
                            Color NeonBlue = new Color(64, 46, 255);
                            b.setForeground(NeonBlue);
                            b.setFont(b.getFont().deriveFont(20.0f));
                            B.setLocation(650, 525);
                            B.setBorderPainted(false);
                            B.setBackground(Brown);
                            B.setForeground(NeonBlue);
                            B.setFont(b.getFont().deriveFont(20.0f));
                            B.setSize(200, 200);
                            b.enableInputMethods(true);
                            JOptionPane.showMessageDialog(null, "Nice pick");
                        }
                    };
                    ActionListener ButtonListener2 = new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            p+=N;
                            l+=1;
                            f.dispose();
                            F.setSize(1000, 1000);
                            F.setVisible(true);
                            F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                            F.add(b);
                            F.add(B);
                            F.add(m[0]);
                            Color Brown = new Color(64, 46, 32);
                            b.setLocation(150, 525);
                            b.setSize(200, 200);
                            b.setBorderPainted(false);
                            b.setBackground(Brown);
                            Color NeonBlue = new Color(64, 46, 255);
                            b.setForeground(NeonBlue);
                            b.setFont(b.getFont().deriveFont(20.0f));
                            B.setLocation(650, 525);
                            B.setBorderPainted(false);
                            B.setBackground(Brown);
                            B.setForeground(NeonBlue);
                            B.setFont(b.getFont().deriveFont(20.0f));
                            B.setSize(200, 200);
                            b.enableInputMethods(true);
                            JOptionPane.showMessageDialog(null, "Nice pick");
                        }
                    };
                    b.addActionListener(ButtonListener);
                    B.addActionListener(ButtonListener2);
                }
            }
        }
    }
    

    I cant get the variables to be read and changed out side of the local class and I need that to happen. the variables i need to get are p n N. when i click on the buttons (the action listeners) they should take the random value displayed on screen and add to the var p and change on screen.