samedi 30 septembre 2023

Struggling with fixed rand() output [closed]

I am trying to obtain a random integer value from [1,3]. I have done some research on rand() and srand(), but i can't seem to contain the integer to 1,3. Any simple solutions?

There is a lot of code in between that is not interfering, so this is just a snippet. Assume libraries are present. :)

        int seed;
    printf("Before we start, pick a number to determine how random I will be.\n");  //srand
    scanf("%d", &seed);
        srand(seed);
    printf("All set now!\n");

        int computerPick(){
          int p2select;
          p2select = rand()%(3-1) + 1;    // i need this to return from 1-3
          printf("%d",p2select);
          return p2select;
      }





Why is my sprite not changing its direction after hitting the top? [duplicate]

I'm writing a program in pygame to make 'Pong' for a school project. I'm having issues with getting the ball to bounce back after it gets to the top, even though I'm having no problem with sprite collision or it hitting the bottom of the screen. Only the top of the window is where I'm having a problem

This is my code:

import pygame, sys
from pygame.locals import *
import random

COLOR = (255, 100, 98)
SURFACE_COLOR = (255,255,255)
WIDTH = 1000
HEIGHT = 500

class GameSprite(pygame.sprite.Sprite):
    def __init__(self, player_image, player_x, player_y):
        super().__init__()

        self.image = pygame.transform.scale(pygame.image.load(player_image),(55,100))
        self.rect = self.image.get_rect()
        self.rect.x = player_x
        self.rect.y = player_y

class Player1(GameSprite):
    def update(self):
        keys = pygame.key.get_pressed()
        if keys[K_w]:
            self.rect.y -= 8
        if keys[K_s]:
            self.rect.y += 8
        if self.rect.top <= 0:
            self.rect.top = 0
        if self.rect.bottom >= HEIGHT:
            self.rect.bottom = HEIGHT
        

class Player2(GameSprite):
    def update(self):
        keys = pygame.key.get_pressed()
        if keys[K_UP]:
            self.rect.y -= 8
        if keys[K_DOWN]:
            self.rect.y += 8
        if self.rect.top <= 0:
            self.rect.top = 0
        if self.rect.bottom >= HEIGHT:
            self.rect.bottom = HEIGHT


class Ball(pygame.sprite.Sprite):
    def __init__(self, player_image, player_x, player_y):
        super().__init__()
    
        self.image = pygame.transform.scale(pygame.image.load(player_image),(55,55))
        self.rect = self.image.get_rect()
        self.rect.x = player_x
        self.rect.y = player_y

pygame.init()

RED = (255, 0, 0)

size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Creating Sprite")
#bg = pygame.image.load('background.jpg').convert()
#bg = pygame.transform.scale(bg,(WIDTH,HEIGHT))
direction = 1
speed_x = random.randint(4,6)
speed_y = random.randint(4,6)

all_sprites_list = pygame.sprite.Group()

player1 = Player1('racket1.png', 0, HEIGHT/2 - 50)
player2 = Player2('racket2.png', WIDTH-50, HEIGHT/2 - 50)
ball = Ball('tennis_ball.png',WIDTH/2,HEIGHT/2 - 50)



all_sprites_list.add(player1)
all_sprites_list.add(player2)
all_sprites_list.add(ball)

exit = True
clock = pygame.time.Clock()

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


    all_sprites_list.update()
    screen.fill(SURFACE_COLOR)
    all_sprites_list.draw(screen)
    pygame.display.flip()
    clock.tick(60)

    if ball.rect.top <= 0:
        speed_y = random.randint(4,6)*-1

    if ball.rect.bottom >= HEIGHT:
        speed_y = random.randint(4,6)*-1

    if pygame.sprite.collide_rect(player1,ball):
        speed_x = random.randint(4,6)*-1

    if pygame.sprite.collide_rect(player2,ball):
        speed_x = random.randint(4,6)*-1
    
    ball.rect.x += speed_x
    ball.rect.y += speed_y

pygame.quit()

Please tell me about what's wrong with this. I'm sorry if this is a poorly worded question




jeudi 28 septembre 2023

numpy random number generator: I'm using the same seed, but I'm not getting the same sequence of numbers?

I am generating multiple grids with simulated data (elevation), and as part of that, I add or subtract elevation (according to a function of distance from a center point) from select points. I want the sequence of points where I modify the data (center points), to be the same for each grid, but it doesn't matter where they are so I'm just choosing random points from a uniform distribution. HOWEVER, even with a set seed, I keep getting different sequences of the center points? It's gotta be something simple I'm just missing, but I can't see it. So please help?

Example of paired-down code:

import numpy as np

seed = 3;
rn_gen = np.random.default_rng(seed=seed);
size = 10

for grid in [1, 2]:
    center_x = rn_gen.integers(1, high=100, size = size, endpoint = True);
    center_y = rn_gen.integers(1, high=100, size = size, endpoint = True);
    print("x:", center_x, "y:", center_y);

I consistently get the same answer:

x: [82 9 18 24 19 81 87 59 4 10] y: [34 44 63 48 27 16 70 74 4 12]

x: [46 40 89 52 43 44 67 59 18 74] y: [76 96 79 29 32 65 66 70 87 30]

but why aren't the second x and y the same as the first x and y?

[P.S. In reality, this is written within a function which works out the "area" (arrays of grid node IDs), which is passed to a different function that deals with modifying the data in that area), e.g. given below, in case the function is inferring with my problem].

import numpy as np

seed = 3;
rn_gen = np.random.default_rng(seed=seed);
size = 10

def function1(size):
    center_x = rn_gen.integers(1, high=100, size = size, endpoint = True);
    center_y = rn_gen.integers(1, high=100, size = size, endpoint = True);
    
    return (center_x, center_y)
    

for grid in [1, 2]:
    xs_ys = function1(size); 
    print(xs_ys);

output =
(array([82, 9, 18, 24, 19, 81, 87, 59, 4, 10], dtype=int64), array([34, 44, 63, 48, 27, 16, 70, 74, 4, 12], dtype=int64))(array([46, 40, 89, 52, 43, 44, 67, 59, 18, 74], dtype=int64), array([76, 96, 79, 29, 32, 65, 66, 70, 87, 30], dtype=int64))

Thanks!

I am trying to repeatedly generate the same sequence of random numbers using numpy's random number generator (uniform), but it doesn't generate the same sequence of random numbers for some reason, despite the fact I have set a consistent seed, and I'm not sure where I'm going wrong?




Getting syntax error using $RANDOM and if statement in bash [duplicate]

My assignment requires me to use $RANDOM and compare it to users input until it matches. I'm currently using if statement to see if the $RANDOM function works, it does but i'm not sure if im comparing the value to the users input correctly because i keep getting syntax errors.

./rec04C.sh
Enter a number between 1 and 10: 6
8
./rec04C.sh: line 8: [8: command not found
Sorry, you are not correct. Try again!

For this above code the 3rd line is a result of the 6th line in my bash script, and the error comes from the comparison on line 8. But it still produces the output of the else statement

#!/bin/bash
read -p "Enter a number between 1 and 10: " number

rand=$((1 + $RANDOM % 10))

echo $rand

if [$rand -eq $number]; then
        echo "Congratulations, the number is $number"
else
        echo "Sorry, you are not correct. Try again!"
fi



spoof randomly screen resolution at every browser startup (javascript - violentmonkey)

I want to randomly execute a bunch of strings within the same script.

I'd like to run it randomly so that I get a different screen resolution every time I start the browser, instead of being stuck at 1920*1080 for example.

(I'm using violentmonkey by the way) Thanks.

Run it (1920×1080) Object.defineProperty(window.screen, "availWidth", { get: function(){return 1920; }}); Object.defineProperty(window.screen, "width", { get: function(){return 1920; }});

Object.defineProperty(window.screen, "availHeight", { get: function(){return 1080; }}); Object.defineProperty(window.screen, "height", { get: function(){return 1080; }});

Object.defineProperty(window, "innerWidth", { get: function(){return 1920; }}); Object.defineProperty(window, "innerHeight", { get: function(){return 974; }});

Object.defineProperty(window, "outerWidth", { get: function(){return 1920; }}); Object.defineProperty(window, "outerHeight", { get: function(){return 1040; }});

Object.defineProperty(window, "devicePixelRatio", { get: function(){return 1; }});

or this one (could be 2560 x 1440) Object.defineProperty(window.screen, "availWidth", { get: function(){return ; }}); Object.defineProperty(window.screen, "width", { get: function(){return ; }});

Object.defineProperty(window.screen, "availHeight", { get: function(){return ; }}); Object.defineProperty(window.screen, "height", { get: function(){return ; }});

Object.defineProperty(window, "innerWidth", { get: function(){return ; }}); Object.defineProperty(window, "innerHeight", { get: function(){return ; }});

Object.defineProperty(window, "outerWidth", { get: function(){return ; }}); Object.defineProperty(window, "outerHeight", { get: function(){return ; }});

Object.defineProperty(window, "devicePixelRatio", { get: function(){return ; }});

or that one... (could be 1280 x 720) Object.defineProperty(window.screen, "availWidth", { get: function(){return ; }}); Object.defineProperty(window.screen, "width", { get: function(){return ; }});

Object.defineProperty(window.screen, "availHeight", { get: function(){return ; }}); Object.defineProperty(window.screen, "height", { get: function(){return ; }});

Object.defineProperty(window, "innerWidth", { get: function(){return ; }}); Object.defineProperty(window, "innerHeight", { get: function(){return ; }});

Object.defineProperty(window, "outerWidth", { get: function(){return ; }}); Object.defineProperty(window, "outerHeight", { get: function(){return ; }});

Object.defineProperty(window, "devicePixelRatio", { get: function(){return ; }});

I haven't tried anything, even though I've spent hours trying to find a way to do it.




Hi! Does anyone know why my windows doesn't support the mudule "random"?

Like how am i exacly supposed to add a module into my python?or is it just a problem windows 10 has?

I tried other modules and it worked well. Its just the problem with random module, and i want to know if there is a way of adding a module into your python




randomly generate a matrix with fixed number of non zero values using python

I want to generate a random matrix (min value=0, max value=25, steps=5) with N rows and 6 columns, where the number of non-zero values (k) given as input.

Example:

Input: N=2 K=8

Output (result): [[ 5, 0, 20, 0, 15, 25], [ 0, 15, 15, 0, 25, 10]]

I tried to generate the matrix with the code: np.random.choice(np.arange(0,20, 5), size=(2, 6)) but I can't controll the number of non-zero value.




mercredi 27 septembre 2023

Disable automatic re-seeding in OpenSSL random generation

I am using OpenSSL C++ random generation, more specifically the RAND_priv_bytes() function.

My goal is to make sure the random generator used in RAND_priv_bytes() is seeded by my custom function, and that re-seeding also happens at a regular interval, specified by me, still using my seed function. It is also fine if my seed is just used to add entropy to the internally generated seed, and it is also fine if the first time the random generator is seeded by OpenSSL.

My problem is that OpenSSL, as far as I understand, is automatically re-seeding all random generators, which is not acceptable since I need to be in control of what seed is provided.

So, I tried the following:

  • I am using RAND_seed() with a 64 bytes seed to achieve that. Is that correct? I learn that after a certain time interval or random generations, the random generator is automatically re-seeded so I will not be in control of what seed is being generated. Is that true?
  • To overcome this issue of automatic reseeding, I tried to build OpenSSL with "--with-rand-seed=none", and I provide a 64 bytes initial seed using RAND_seed(), and the initial seed is coming from the standard C, rand() function. Unfortunatelly, RAND_status() returns 0 after seeding, so OpenSSL is no longer usable. And RAND_poll() doesn't return 1, suggesting it fails, but that should be expected with no seed. Maybe rand() has not enough entropy as initial seed? Is there any other quick solution to provide an initial valid seed?
  • Ideally, I would let OpenSSL generate the first seed and disable automatic re-seeding after that. Is that possible? I found some functions to specify the re-seeding interval but these are in <openssl/rand_drbg.h>, and I can't find this file in my build.
  • On a different topic, I read that RAND_priv_bytes() generates a new random generator instance per thread, does it affect re-seeding in some way?

In short, I need to ensure that each time the private random generator is re-seeded, my seed generation is taken into account (the first seeding may come from OpenSSL).

Thanks in advance.




Generating an array of random numbers with conditions

I have a list of length 64, such as first_list = [64, 27, 99, 133, 0, 41, ... ]. Numbers in this are some random selection from 0 to 150 (minimum value is 0 and maximum value is 149).

I want to generate several other list of random number with the same minimum and maximum condition (between 0 to 150), and also in the new list (let's call it new_list), new_list[0] != first_list[0], new_list[1] != first_list[1], new_list[2] != first_list[2] , ...

Is there any fast way of implementing this?




Speeding up by removing col and row for-loops (Randomization with condition)

For a financial application using bootstrapped resampling, I would like to speed up (vectorize) this function without the need of for-loops.

The set up. I have a data with multiple gvkeys (ids), returns and dates (large T, large N). Additionally SB_dates with bootstrapped random dates (in blocks) and newBL a boolean array matrix which is true each new Block. SB_dates and newBL have the same size (in the example 20 x 6).

For each, each new block select 5 (n) random stocks from data and calculate the average return on that date. If it is not a new block, keep the same random stocks that were selected previously, and calculate the average return on that date.

So far, this is what I got. But I am having struggle in speeding things up mainly due to the loops. Any ideas?

@jit
def calculate_average_returns(data, SB_dates, newBL, n=5):
    n_rows, n_columns = np.shape(SB_dates)
    df_sb = pd.DataFrame()

    for col in range(n_columns):
        date_column = SB_dates[:, col]
        newBL_column = newBL[:, col]
        average_returns_col = []

        for i in range(n_rows):
            if newBL_column[i]:
                selected_stocks = data[data['yyyymm1'] == date_column.iloc[i]]
                random_stock_ids = np.random.choice(selected_stocks['gvkey'], n, replace=False)
                selected_stocks_df = data[(data['yyyymm1'] == date_column.iloc[i]) & (data['gvkey'].isin(random_stock_ids))]
                ret_mean = selected_stocks_df['ret_w'].mean()
                average_returns_col.append(ret_mean)
            else:
                selected_stocks_df = data[(data['yyyymm1'] == date_column.iloc[i]) & (data['gvkey'].isin(random_stock_ids))]
                ret_mean = selected_stocks_df['ret_w'].mean()
                average_returns_col.append(ret_mean)

        df_sb[col] = average_returns_col
    return df_sb

The data. Generates data

import pandas as pd
import numpy as np
import random
from datetime import datetime, timedelta

n_rows = 1000
start_date = datetime(2000, 1, 1)
end_date = datetime(2023, 12, 31)

# Generate random dates within a range
dates = [start_date + timedelta(days=random.randint(0, (end_date - start_date).days)) for _ in range(n_rows)]

# Generate random returns between -1 and 1
returns = np.random.uniform(-0.01, 0.01, n_rows)

# Generate random gvkey values
gvkey = [random.randint(1000, 9999) for _ in range(n_rows)]

# Create a DataFrame
data = pd.DataFrame({'yyyymm1': dates, 'ret_w': returns, 'gvkey': gvkey})

and for the SB_dates

           0          1          2          3          4          5   \
0  2015-01-31 2015-02-28 2014-09-30 2017-10-31 2010-12-31 2018-05-31   
1  2015-02-28 2015-03-31 2010-06-30 2017-11-30 2011-01-31 2018-06-30   
2  2015-03-31 2015-04-30 2010-07-31 2017-12-31 2011-02-28 2018-07-31   
3  2015-04-30 2015-05-31 2010-08-31 2018-01-31 2011-03-31 2018-08-31   
4  2015-05-31 2015-06-30 2010-09-30 2018-02-28 2011-04-30 2018-09-30   
5  2015-06-30 2015-07-31 2010-10-31 2018-03-31 2011-05-31 2018-10-31   
6  2010-05-31 2015-08-31 2013-10-31 2015-07-31 2011-06-30 2018-11-30   
7  2014-08-31 2015-09-30 2013-11-30 2015-08-31 2011-07-31 2018-12-31   
8  2010-11-30 2015-10-31 2013-12-31 2015-09-30 2011-08-31 2019-01-31   
9  2010-12-31 2015-11-30 2014-01-31 2015-10-31 2011-09-30 2019-02-28   
10 2011-01-31 2015-12-31 2014-02-28 2015-11-30 2011-10-31 2019-03-31   
11 2010-05-31 2016-01-31 2011-11-30 2015-12-31 2011-11-30 2019-04-30   
12 2010-06-30 2016-02-29 2011-12-31 2016-01-31 2011-12-31 2019-05-31   
13 2010-07-31 2016-03-31 2007-07-31 2016-02-29 2012-01-31 2019-06-30   
14 2008-11-30 2016-04-30 2007-08-31 2016-03-31 2012-07-31 2019-07-31   
15 2008-12-31 2016-05-31 2007-09-30 2016-04-30 2012-08-31 2017-04-30   
16 2009-01-31 2016-06-30 2007-10-31 2016-05-31 2018-11-30 2017-05-31   
17 2017-07-31 2016-07-31 2007-11-30 2016-06-30 2018-12-31 2017-06-30   
18 2017-08-31 2016-08-31 2007-12-31 2016-07-31 2019-01-31 2017-07-31   
19 2017-09-30 2016-09-30 2008-01-31 2016-08-31 2019-02-28 2017-08-31   

and for the newBL

        0      1      2      3      4      5
0    True   True   True   True   True   True
1   False  False   True  False  False  False
2   False  False  False  False  False  False
3   False  False  False  False  False  False
4   False  False  False  False  False  False
5   False  False  False  False  False  False
6    True  False   True   True  False  False
7    True  False  False  False  False  False
8    True  False  False  False  False  False
9   False  False  False  False  False  False
10  False  False  False  False  False  False
11   True  False   True  False  False  False
12  False  False  False  False  False  False
13  False  False   True  False  False  False
14   True  False  False  False   True  False
15  False  False  False  False  False   True
16  False  False  False  False   True  False
17   True  False  False  False  False  False
18  False  False  False  False  False  False
19  False  False  False  False  False  False 

For example in row 6 of the first column, there is a new Block which is marked as true in newBL. The first rows start always with a new BL.

Sorry for the long data example. But the last two are generated from another function.




mardi 26 septembre 2023

How to generate uniform random numbers in Python close to the true mean and standard deviation?

I am trying to generate uniform random numbers as much as possible close to its theoretical definition, particularly in Python. (i.e., I am familiar with the concept of Pesudo-Random Generators (PRGs) in programming languages.)

I am using the following code for this matter (a widely known solution):

import random
import numpy as np

rands = []
rng = random.Random(5)

for i in range(10000):
  rands.append(rng.uniform(0,1))


print(f"mean: {np.mean(rands)}")
print(f"std: {np.std(rands)}")

The result is:

mean: 0.501672056714862
std: 0.2880418652775188

By changing the initial seed, we can observe that we will get approximately the same values.

On the other hand, from the theoretical aspect, we know that the mean and standard deviation (std) of a uniform random variable between [0, 1] are equal to 0.5 and 1/12 (~ 0.08333), respectively.

As we can observe, the std of generated random numbers is more than 1/4 (3 times more than the theoretical one).

Hence, a plausible question is "how should I adjust this implementation to get a closer std to the theoretical one?"

I understand that the rationale behind this difference originated in the core implementation of the PRG used in the random function. But, I am looking for any other method to resolve this issue.




how do i change this to be able to generate a random item from my list? [duplicate]

my list containing fruits

i'd like for the code to pick (At random) a fruit from my list and then display it.

the code works currently but doesn't have the random function i'd like for it to have. This is a school project so any help is appreciated




Generating random dataframes (5 rows 9 cols) with each rowsum should be 9

I'm trying to create 10 or more of pseudo dataframes. The data frame dim should be 9 columns with 5 rows(Mon, Tue,Wed, Thur, Fri), and each rowsum should be 9. like below.

        Factor1 Factor2 Factor3 Factor4 Factor5 Factor6 Factor7 Factor8 Factor9
Mon       2       1       0       2       0       0       1       1       2
Tue       1       1       1       1       0       0       2       1       2
Wed       2       1       0       2       1       1       1       1       0
Thu       0       0       1       1       3       0       2       2       0
Fri       1       0       0       1       1       0       2       2       2

How can I generate multiple dataframes that meet the condition, please?




lundi 25 septembre 2023

Encryption With Randomization Decryptor

A friend of mine wanted to create encryption using randomization, and I told him that was a bad idea. I wanted to create a file to prove him wrong, however, I noticed that the product that I came up with wasn't always accurate. For example:

I would input hello, and the algorithm would output:

hcllo

My program multiplies the order of the characters by a random number (1-10000) and then runs it through to see which random number works to get a simple ascii character. I have no idea why it is working.

My code:

import random
import time
def PairValueKey(key):
    end = ''
    for x in range(len(key)):
        val = ord(key[x])
        val = int(val) * random.randint(0,10000)
        end = str(end) + '\\' + str(val)
    end = end + '\\'
    return(end)

def FindInput(key):
    sec = ''
    inpu = ''
    for x in range(len(key)):
        if key[x] == '\\':
            if not sec == '':
                for y in range(10000):
                    if y > 0:
                        trynum = int(sec) / int(y)
                        trynum = str(trynum).replace('.0', '')
                        tmp = list(trynum)
                        if not '.' in tmp:
                            if int(trynum) > 122:
                                pass
                            else:
                                inpu = inpu + str(chr(int(trynum)))
                                sec = ''
                                break
        else:
            sec = sec + str(key[x])
    return inpu
                        
            

print('''
       * * * * * * * * * * * * * * * * *
      *  Why random numbers should NOT  *
      *    be used for cryptography     *
       * * * * * * * * * * * * * * * * *
      ''')
print('''Enter a password. This password will then be paired
to a set of random numbers (1-10000), and then will be
decrypted by the software after.
      
Keep in mind that the decryption software isn't accurate,
but it can still retrieve some of your password,
which could be fed into a data collection service afterwards.
      ''')

key = PairValueKey(input("Password: "))
print('This is your unique key containing your password:')
print(key)
time.sleep(2)
print('Seems secure, right?')
time.sleep(2)
print('Think again.')
time.sleep(2)
print('Calculating...\n')
inpu = FindInput(key)
print('The algorithm calculated: ')
print(inpu)



Wordcloud centralize and reduce overlap in randomly positioned words inside a plot

import plotly
import random
import plotly.graph_objects as go
from plotly.subplots import make_subplots    

words = ['potato','hello','juvi']
colors = [plotly.colors.DEFAULT_PLOTLY_COLORS[random.randrange(1, 10)] for i in range(20)]
weights = [110,80,20]

data = go.Scatter(x=[random.random() for i in range(20)],
             y=[random.random() for i in range(20)],
             mode='text',
             text=words,
             marker={'opacity': 0.3},
             textfont={'size': weights,
                       'color': colors})

layout = go.Layout({'xaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False},
                'yaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False}})
fig = go.Figure(data=[data], layout=layout)

fig.show()

I have the following sample code which generates a wordcloud in plotly, the thing is as you can see the words tend to get out of the given square in the plot any ideas on how I could keep the words inside the blueish square. Or at least more to the center of it

enter image description here




samedi 23 septembre 2023

generate random number non repeating with threading [closed]

import random,time
from threading import Thread
usleep = lambda x: time.sleep(x/1000000.0)


def getcode(numbers):
 data = '{"code":"'+ str(numbers) +'}'
 print(data)
 
 
 
inputNumbers =range(1,10)
randomize = random.sample(inputNumbers, 9)
THREAD_COUNT = 2
for numbers in randomize:
 for _ in range(THREAD_COUNT):               
  proc = Thread(target=getcode, args=[numbers])
  usleep(10000)
  proc.start()

i need to generate non repeating number from 1 to 10 with multithreading them . but it alwayes gives multiple same values duo to threading .




Generate Random String Flutterflow

I'm new in Flutterflow and I'm a little confused on using 'Custom Code'. I want to create something that will generate random string. I don't know if this is in a category of Widget, Action, or Function. I tried to follow the steps in Youtube but it's not working. I'm stuck and still can't find similar situation

Here's my current code. I copied it here

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/widgets/index.dart'; // Imports other custom widgets
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:random_string/random_string.dart';
import 'dart:math' show Random;

class GenStringRandom extends StatefulWidget {
  const GenStringRandom({
    Key? key,
    this.width,
    this.height,
  }) : super(key: key);

  final double? width;
  final double? height;

  @override
  _GenStringRandomState createState() => _GenStringRandomState();
}

class _GenStringRandomState extends State<GenStringRandom> {
  main() {
  print(randomBetween(10, 20)); // some integer between 10 and 20
  print(randomNumeric(4)); // sequence of 4 random numbers i.e. 3259
  print(randomString(10)); // random sequence of 10 characters i.e. e~f93(4l-
  print(randomAlpha(5)); // random sequence of 5 alpha characters i.e. aRztC
  print(randomAlphaNumeric(
      10)); // random sequence of 10 alpha numeric i.e. aRztC1y32B

  var r = Random.secure();
  print(randomBetween(10, 20,
      provider:
          CoreRandomProvider.from(r))); // You can use a provider from Random.
  print(randomBetween(10, 20,
      provider: _Provider())); // Or you can implement your own.
}

class _Provider with AbstractRandomProvider {
  _Provider();
  double nextDouble() => 0.5;
}

Here's the error message image error

I hope someone can help me fix it and explain in a simple way and what Custom Code to use here. Thank you in advance. :)




vendredi 22 septembre 2023

a fast way to generate true-false matrix based on random sampling with a matrix of probability values

I have a n × n matrix in which values are between [0,1] and each column has the same values.

These values represent probabilities for each element of the matrix to take the value TRUE or FALSE.

I am searching for a fast way to transform the matrix with the probabilities to a matrix with TRUE/FALSE values based on an independent random sample for each element.

Currently, this code generates what I want (the tf_matrix):

n <- 10
p_true <- runif(n,0,1)

p_matrix <- matrix(p_true,n,n, byrow=T)
tf_matrix <- matrix(F, n,n)

for(i in 1:nrow(tf_matrix)) {
    
    for(j in 1:ncol(tf_matrix)) {
        
        tf_matrix[i,j] <- sample(c(T,F), size = 1, prob = c(p_matrix[i,j], 1-p_matrix[i,j]))
        
    }
}

However, this is likely very slow, as it uses two for-loops and I need to do this over and over for a large matrix.

Is there a way to make this more efficient (i.e., as fast as possible)?




this assignment question, im a beginner in R so basic commands to solve it plz [closed]

Create a data frame named “student_data” with three columns: “Name,” “Age (in years ranging randomly 18 to 25),” and “Grade.” Populate the data frame with information for at least 10 students (using Rstudio)

i'm not sure whether we assign 'Name' to random names, the same goes for grades and dont get what was meant by " at least 10 student" however this is what i did (using Rstudio)

Name <- paste("Student", 1:10)

Age <- sample(18:25,10,replace = T)

Grade <- sample(1:100,10,replace = T)

student_data <- data.frame(Name,Age,Grade)

we didn't study the paste() and sample() command yet so idk how to solve this problem in another way




How to implement a random natural motion for a single particle?

I have a Drone class implemented as a Thread that is called from a Map class and every X milliseconds the movement() function of the Drone class is called to update the position and show it on the map.

Currently the movement() function looks as follows.

    public void moveDrone() {
        double increment = 0.000007;
//      Straight line movement
        if(this.mode == true)
            p.setX(this.p.getX() + increment);
        if(this.mode == false)
            p.setX(p.getX() - increment);
        if(p.getX()>38.88602||p.getX()<38.88453)
            this.mode = !this.mode;

Which creates a movement in a straight line that looks pretty simple.

I would like to simulate a random motion that looks kind of natural. I've been reading about different implementations like brownian motion and boids but I couldn't find how to implement them for a single particle (drone in this case) that moves randomly inside a bounding box.

Any link or pseudocode will help.




jeudi 21 septembre 2023

Terraform: Help understanding reading a value from random provide with a r keepers resource

The Terraform docs for random have this example:

resource "random_id" "server" {
  keepers = {
    # Generate a new id each time we switch to a new AMI id
    ami_id = var.ami_id
  }

  byte_length = 8
}

resource "aws_instance" "server" {
  tags = {
    Name = "web-server ${random_id.server.hex}"
  }

  # Read the AMI id "through" the random_id resource to ensure that
  # both will change together.
  ami = random_id.server.keepers.ami_id

  # ... (other aws_instance arguments) ...
}

What is the different in behavior between reading random_id.server.hex and random_id.server.keepers.ami_id?

What does the comment mean by reading a value "through" the random_id resource? Is ami = random_id.server.keepers.ami_id different to ami = var.ami?




How does HD wallet generates the ENT?

i've been searching for a while but i didn't get a decent answer, I'm working on a persona project and i would like to ricreare as precise as i can a real HD wallet

does anyone know how are ENT generated in wallet like trust or exodus?




mercredi 20 septembre 2023

Getting a random position fixed distance from a point

I am trying to develop a solar system simulation.

To initialise the display, I need the planets to be randomly placed in their orbitals (fixed orbital radius) from the Sun. How do I get the random position?

I am using pygame for the display.

I tried some code from ChatGPT, but it didn't seem to work correctly and I couldn't understand it at all.




mardi 19 septembre 2023

Random number between two numbers with "gaps"

I am trying to generate random numbers between two values. I am using, vba for this, so that, the way to do It would be:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

But because of the particular situation I am in, I need to exclude numbers from the middle of the sequence, so for example I need numbers between 50 and 100 and I need to exclude 80, 50, and 77, for example

So to do this, I wrap the random number generator in a Do While loop, and check if the number is one of the excluded numbers, and if it is, I keep generating numbers.

This brute-force seems to me inefficient and I am not sure about the statistical properties of the sequence if I do this,

are there more elegant algorithms to accomplish this task?

thanks in advance




How do I create random numbers using the same variable constantly with a class?

I am trying to make a 2d game using Ursina. All has gone well until I made terrain. The looping of terrain works well but when i try to make the types of chunks random the radiant function only works once. How do I fix this? By The Way I am new to python so this would be a great help.

I have tried update methods while true methods and the method for I in range. The radiant method only worked once so when I printed the variable for debugging it just reads all 1s or 2s. What can I do?




lundi 18 septembre 2023

How do I create a random number generator, that each time it is called upon, returns a different value?

I've been trying to do this so I can create a maths problem game, with all random numbers so the game can continue for aslong as the user would like to. However I am currently using this:

Dim rand As New Random()
Dim approval As Integer = rand.Next(0, 9)

which every time it is called upon, returns the exact same digit.

I was hoping that this would return a different number each time, but after printing it a few times in the same run, I realised that it doesn't and returns the same number.




How can I use random string in cypress test

How can I use random string in my cypress test so that whenever my gitlab-runner runs the code, the system will use difference strings like the Email and Phone number majorly.

I have my class created which i do call in my script.

here is the class that i created .

export class SignupPage{
   
 enterFirstname(firstname){
        cy.get('.grid-cols-2 > :nth-child(1) > .relative > .w-full').type (firstname)
    }
    enterlastname(lastname){
        cy.get('.grid-cols-2 > :nth-child(2) > .relative > .w-full').type(lastname)
        }
    
    enterEmail(email){
        cy.get('.space-y-3 > :nth-child(2) > .relative > .w-full').type(email)
      }
        enterBusinessName(businessName){
        cy.get(':nth-child(3) > .relative > .w-full').type(businessName)
        }
    enterBusinessType(){
    cy.get('#headlessui-listbox-button-1').click()
cy.get('#headlessui-listbox-option-4 > .font-normal').click()
}
    enterPhoneNumber(phoneNumber){
        cy.get(':nth-child(5) > .relative > .w-full').type(phoneNumber)
    }
    enterPassword(password){
        cy.get(':nth-child(6) > :nth-child(1) > .relative > .w-full').type(password)
  }
  clickAgreementBox(){
    cy.get('.h-4').click()

  }
        clickContinue(){
            cy.contains('Continue').click()
     
        }
        }

here is my test script

import { SignupPage } from "./pages/signup_page"


    const signupPage = new SignupPage()

describe('Registration', () => {
    it ('SoftPay registration page', () =>{
        cy.viewport(1280, 720)

        function makeid(length) {
            var result           = '';
            var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var charactersLength = characters.length;
            for ( var i = 0; i < length; i++ ) {
               result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            return result;
         }

        cy.visit('softpayfront.softalliance.com/')
        cy.contains('Create Account').click()

        signupPage.enterFirstname('Adunola')
        signupPage.enterlastname('Adunola')
        signupPage.enterEmail(makeid(6) + "@mailsac.com")
        signupPage.enterBusinessName('SoftPay TESTING')
        signupPage.enterBusinessType()
        signupPage.enterPhoneNumber(makeid(8)+ "82090808070")
        signupPage.enterPassword('Password#1')
        signupPage.clickAgreementBox()
        signupPage.clickContinue()
        cy.end()
      })
      

})

this only work for the random email but not for the phone number

 function makeid(length) {
            var result           = '';
            var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            var charactersLength = characters.length;
            for ( var i = 0; i < length; i++ ) {
               result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            return result;
         }



dimanche 17 septembre 2023

2 number command line lottery returning a win every time [duplicate]

I'm creating a code that accepts two numbers as command line arguments. these numbers are then compared against two randomly generated integers and inform the user if they have matched the numbers that were generated. while I succeeded in the printing of the numbers and my programs runs, it returns to the user that they have always matched one of the numbers regardless of if they did or did not.

my current code is:

    import sys
    import random 
    Pick1 = int(sys.argv[1])
    Pick2 = int(sys.argv[2])
    Lot1 = random.randint(1, 10)
    Lot2 = random.randint(1, 10)
    print("The lottery numbers were " + str(Lot1) + " and " + str(Lot2) + ".")
    print("Your picks were " + str(Pick1) + " and " + str(Pick2) + ".")
    if (Pick1 == Lot1 or Lot2):
        print("You matched one number! You win $100!!")
    elif (Pick1 == Lot1 or Lot2) and (Pick2 == Lot1 or Lot2):
        print("You matched both numbers! Congratulations! You win $1000!!")
    else:
        print("Sorry, no match.")
 

i have tried adjusting the conditionals but no matter what i do it returns that they have always matched one of the lottery numbers.




Compare a random generated list (list 2) with another list (list 1) and print the value from list 2 and the corresponding index in list 1

l) Use a for loop and a random integer generator to generate 5 random integers in the range specified by the user in step a. Check if each number is in the combined list. • If the number is in the combined list, print the number and print the index of the first element that matches. • NOTE: There is a list method for finding an element value which return the index and you should use that function. Do NOT use a for loop or you will lose some points. • If the element is found, after printing the index, the element should be deleted or removed from the list. • NOTE: There is both a function and a list method that can delete or remove an element from a list. You should use either the function or the list method. Do NOT use a for loop or you will lose some points. • If the number is not in the combined list, print the number followed by "not found in list".

^These are the instructions for the problem

```def main():
entries = int(input('Step a: How many numbers in each list? '))
lower_bound = int(input('Step b: \nWhat is the lower bound for the random numbers? '))
upper_bound = int(input('What is the upper bound for the random numbers? '))
list_one = []
for i in range(entries):
    list_one.append(random.randint(lower_bound, upper_bound))
print(f'Step c: First list: {list_one}')
list_two = create_second_list(entries, lower_bound, upper_bound)
print(f'Step d: Second list: {list_two}')
print('Step e:')
for i in range(entries):
    print(list_one[i], list_two[i])
list_combined = list_one + list_two
print(f'Step f: Combined list:', list_combined)
list_combined.sort()
print(f'Step g: Sorted list:', list_combined)
print(f'Step h: \nFirst three elements: {list_combined[0:3]}\n'
      f'Last three elements: {list_combined[-3:]}')
sum_elements(list_combined)
min_elements(list_combined)
max_elements(list_combined)
print('Step l:')
delete_list = []
for x in range(5):
    delete_list.append(random.randint(lower_bound, upper_bound))
    if delete_list ```

I've tried making an if statement but instead of printing the delete_list it printed 0-4 and the corresponding index in my combined_list




samedi 16 septembre 2023

Select with random ORDER in MySQL Within 1 row

I Have this Level 1 table enter image description here I want to make query, when the query is execute the order of J1,J2.. J5 is in random order

I have this query

SELECT j1,j2,j3,j4,j5 FROM `level_1` ORDER BY RAND()

but it only randomize the index row, not the inside image result

I want to make this result with random column order, but cant figure it out yet I hope this result




How to randomly change order of an array on click in React

I am trying to write a simple dice game in React, which randomizes the order of players before play begins.

I am trying to use a function for shuffling arrays which has worked in a vanilla javascript version of the game I wrote:

export default function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
    return array;
  }
}

(I took this code from [here](https://javascript.info/array-methods#shuffle-an-array originally and added the 'return array' out of desparation though it wasn't needed in my plain javascript version).

I have tried two ways of achieving what I want to do in React, first with a function called on click:

function shufflePlayers () {
    const shuffledPlayers=shuffle([...players]);
    setPlayers(shuffledPlayers);
  }

Which is then passed as a prop to the "Play!" button:

{play === false && players.length > 0 && <PlayButton togglePlay={togglePlay} shufflePlayers={shufflePlayers}/>}`

And then used like this:

import React from 'react'

export default function PlayButton(props) {
   function handleClick () {
     props.shufflePlayers();
     props.togglePlay();
   }
    return (
    <>
    <button onClick={handleClick}>Play!</button>
    </>
  )
}

Before being rendered like this:

import React from 'react'

export default function PlayButton(props) {
    function handleClick () {
      // props.shufflePlayers();
      props.togglePlay();
    }
    return (
    <>
    <button onClick={handleClick}>Play!</button>
    </>
  )
}

This does not crash, but it does not change the order of the players on screen.

The other way I have tried is with useEffect:

useEffect(()=> {
    const shuffledPlayers=shuffle([...players]);
    setPlayers(shuffledPlayers);
  },[play])

Note that play is a boolean which is false when setting up the game (adding/removing players) and false when playing the game.

And following error messages:

useEffect(()=> {
    const shuffledPlayers=shuffle([...players]);
    setPlayers(shuffledPlayers);
  },[players])

Note that players is an array of player objects.

But these either throw errors or appear to get stuck in an infinite loop as nothing renders.

I tried all of the above, and also consulted the following Stack Exchange threads:

https://stackoverflow.com/questions/63540873/react-hooks-shuffle-array-immediately-on-load-and-onclick https://stackoverflow.com/questions/65027008/unable-to-shuffle-array-correctly-in-react

From these I got the idea of spreading the array before sending it to my function.

So my question is,** how can I reliably re-order the players when the user clicks the "Play" button, and changes the play state variable from false to true? **(I don't mind at this stage if it means the order of players will be randomized again when the player returns to the start after a game is reset).




Cannot find solution to a randomly generated equation

im fairly new to python. trying to create a math quiz game as an assignment. i tried saving random int to a variable but that would return same value. i switched to creating a function, now im able to print a random equation but i cant know what i printed so i cant solve it to compare user answer.

This is my current code

import random

score = 0
symbol = ['+', '-', '*', '/', '^']
def num():
    print(int(random.randint(1, 25)), end = '')
def sym():
    print(random.choice(symbol), end = '')
def eq():
    (num(), sym(), num())
eq()
def sol():
    #???

edit: using return value now, dont know what the error is

import random

score = 0
symbol = ['+', '-', '*', '/', '^']
def num():
    print(int(random.randint(1, 25)), end = '')
    return(random.randint)
def sym():
    print(random.choice(symbol), end = '')
def eq():
    ques = (num(), sym(), num())
    return ques
equation = eq()
print(equation)



vendredi 15 septembre 2023

How to loop on array or objects then getting a random value

If my set up is like this:

const arr = [
    { name: "hi", value: "hello", rarity: "50%" }
    { name: "hello", value: "40%"}
]

How can I loop through it and get a random value based on their rarities?

I tried possible things I know. Didn't work out somehow.




Is xoshiro128** pseudorandom number generator reversible?

This answer mentions the xoshiro128** algorithm and provides a JavaScript implementation.

Question: Is it possible to derive the seed if you know the first random number produced by this generator?




mercredi 13 septembre 2023

Generate a random point within a circle (non-uniformly)

I have a one-dimensional function I(r) defined as:

I(r) = A * exp( -2 * ( r / w ) ^ b )

where A is arbitrary, w and b are variables that adjust the width and "rectangularity" of the function. I'm plotting this function with A = 1.0, w = 1.0, and different b's for your reference:

Plots of I(r) with different b's

I want to be able to draw random points in polar coordinates in a circle (or a disk) of radius R according to this function I(r), where r would be the radius in the interval [0, R]. The angle would be chosen uniformly in the interval [0, 2 * pi[.

However, if I sample r's straight away from I(r) I get an accumulation of points close to the origin. How shall I properly sample my radii so that the radial distribution ends up being I(r)?

At first, I didn't know how to draw samples from an arbitrary function such as I(r). Luckily, someone pointed me to this Python article, where Harry45 describes how draw samples from any distribution by subclassing the rv_continuous class of scipy.stats. Then, I generated a number of radii using the rvs(...) method of rv_continuous, and the same number of angles with numpy.random.rand in the interval [0, 2 * pi[. Finally, I transformed to Cartesian coordinates and plotted the results in a scatter plot. I had a feeling that too many points were clustered around the origin. I used a value b of 1000, which is close to a uniform distribution (see my plot above). As it turns out, the circle wasn't uniformly filled, and more points were clustered around the origin. This is an issue that was addressed on Stackoverflow before at this link. Based on this link, I did the following to sample one point:

  • Get a radius r from I_norm(r) = A * exp ( -2 * r ^ b )
  • Take the square root of r
  • Multiply r by w
  • Get an angle from the uniform interval [0, 2 * pi[
  • Transform to Cartesian coordinates

At first, it seemed to work, but when I gave it more thought I realized. When I sample I_norm(r) and b is like 2, 4, or 8, there's a substantial chance to get a radius above 1. If the radius is above 1, taking the square root makes it even smaller and does the opposite of what we want (that is increase the number of points at larger radii to conserve the same denisty of points along the circle at that radius).

Moreover, with rv_continuous.rvs(...), I'm not sure how to limit myself to an interval [0, R]. Naturally, the greater r is the less likely it is to be sampled, but still, I think it remains an issue.

Long story short, I'm pretty sure what I'm doing currently is mathematically wrong, although I struggle to explain why. I'd appreciate if someone could shine some light on how to generate random points in a circle of radius R with a radial distribution that follows I(r).

Thank you in advance, and take care,

David




lundi 11 septembre 2023

AutoHotkey Code for Randomly generating number not working anymore

The following code presses the cursor every few seconds. When I first made it, it just pressed the cursor every 5 seconds, but the game realised what I was doing. So I changed the code, with the help of ChatGPT and made the following. The code has been working for about 6 months, but no longer works. Chat says the code is fine, and we went through it all, doing various tests. But I still can't find out why the 'Random' procedure won't work.

Does anyone have any ideas.

I use it to press the curser on an silly online game when I'm out.

SetBatchLines -1  ; Improve script performance

Loop
{
    Random, ClickInterval, 400000, 1000000  ; Generate a random number between 400000 and 1000000 milliseconds (4.0 to 10.0 seconds)
    Click           ; Click at the current cursor position
    Sleep, ClickInterval
}



I created an object of Randon class in java , But when invoking nextInt() method using the object it's giving cannot find symbol error [duplicate]

java.util.Random ran = new java.util.Random();

int target_number = ran.nexInt(10);





 D:\CODING\JAVA\JAVA FILES>javac Gamelauncher.java
    Gamelauncher.java:21: error: cannot find symbol
                target_number = ran.nexInt(10);
                                   ^
    symbol:   method nexInt(int)
    location: variable ran of type Random
    1 error

i was trying to generate a random number under 10 and store it to a integer variable target_number but giving cant find symbol error




Recreate randperm Matlab function in Python

I have searched on stackoverflow for people facing similar issues and this topic Replicating MATLAB's `randperm` in NumPy is the most similar.

However, although it is possible to recreate the behavior of randperm function from Matlab in Python using numpy random permutation, the numbers generated are not the same, even though I choose the same seed generator for both languages. I am a bit confused since my tests were relevant for other random functions between Matlab and Python.

Here is what I have tried:

Matlab

rng(42);
randperm(15)

which returns

ans =

    11     7     6     5    15    14     1     4     9    10     3    13     8     2    12

Python

np.random.seed(42)
print(np.random.permutation(range(1,15)))

which returns

[10 12  1 13  6  9  3  2 14  5  8 11  4  7]

How can I change my Python code so it can reproduce the same order of random numbers than Matlab ?




dimanche 10 septembre 2023

mixing of noise from four corner glsl

I am studying noise from the bookofshaders and in 2d noise this is the code in the book or website.

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

// 2D Random
float random (in vec2 st) {
    return fract(sin(dot(st.xy,
                         vec2(12.9898,78.233)))
                 * 43758.5453123);
}

// 2D Noise based on Morgan McGuire @morgan3d
// https://www.shadertoy.com/view/4dS3Wd
float noise (in vec2 st) {
    vec2 i = floor(st);
    vec2 f = fract(st);

    // Four corners in 2D of a tile
    float a = random(i);
    float b = random(i + vec2(1.0, 0.0));
    float c = random(i + vec2(0.0, 1.0));
    float d = random(i + vec2(1.0, 1.0));

    // Smooth Interpolation

    // Cubic Hermine Curve.  Same as SmoothStep()
    vec2 u = f*f*(3.0-2.0*f);
    // u = smoothstep(0.,1.,f);

    // Mix 4 coorners percentages
    return mix(a, b, u.x) +
            (c - a)* u.y * (1.0 - u.x) +
            (d - b) * u.x * u.y;
}

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution.xy;

    // Scale the coordinate system to see
    // some noise in action
    vec2 pos = vec2(st*5.0);

    // Use the noise function
    float n = noise(pos);

    gl_FragColor = vec4(vec3(n), 1.0);
}

There are few things i am not able to understand in this code is

  1. why is the mixing or combining noise value from all the corner has calculation like that

      mix(a, b, u.x) + (c - a)* u.y * (1.0 - u.x) + (d - b) * u.x * u.y;
    

from initial understanding it is easy guess that everything is linear interpolation but i am not able to understand the thinking behind why u.y*(1.0-u.x) and u.x*u.y are used as a factor.

is it something like someone choosed this specific way and there is no concerete reason why it is specificially done this way or this mixing is not standard way of mixing but people can mix anyway they want ?

  1. and in the line of code

     vec2 pos = vec2(st*5.0)
    

i am not able to understand how does this increase the frequency of noise.

can anyone please help me understand this ?




RNG Challenge Python

I am trying to solve a CTF challenge in which the goal is to guess the generated number. Since the number is huge and you only have 10 attempts per number, I don't think you can apply binary search or any kind of algorithm to solve it, and that it has something to do with somehow getting the seed of the random function and being able to generate the next number, but I have no idea on where to start to get the correct seed. Do you have any idea? Here's the code of the challenge:

#!/usr/bin/env python3

import signal
import os
import random

TIMEOUT = 300

assert("FLAG" in os.environ)
FLAG = os.environ["FLAG"]
assert(FLAG.startswith("CCIT{"))
assert(FLAG.endswith("}"))


def handle():
    for i in range(625):
        print(f"Round {i+1}")
        guess_count = 10
        to_guess = random.getrandbits(32)
        while True:
            print("What do you want to do?")
            print("1. Guess my number")
            print("2. Give up on this round")
            print("0. Exit")
            choice = int(input("> "))
            if choice == 0:
                exit()
            elif choice == 1:
                guess = int(input("> "))
                if guess == to_guess:
                    print(FLAG)
                    exit()
                elif guess < to_guess:
                    print("My number is higher!")
                    guess_count -= 1
                else:
                    print("My number is lower!")
                    guess_count -= 1
            elif choice == 2:
                print(f"You lost! My number was {to_guess}")
                break
            if guess_count == 0:
                print(f"You lost! My number was {to_guess}")
                break


if __name__ == "__main__":
    signal.alarm(TIMEOUT)
    handle()




python random.choices() not giving equal number of elements even if we give equal weights

I want to create a random list with diffrent combinations of elements in the list. The count of each element appearing in the final list should same.

For example

>>> set_sizes = [0, 3, 6, 12]
>>> target_list = random.choices(set_sizes, weights = [1, 1, 1, 1], k= 40)
>>> print (target_list.count(0), target_list.count(3), target_list.count(6), target_list.count(12))

8 10 12 10

Here I was expecting the count of all elements will be 10 since I give equal weights. But it is not same always. How can I modify the code to get the equal count for all elements ? Please help.




samedi 9 septembre 2023

Repeatedly using randperm until a standard is met always gives duplicate results on two consecutive runs

We have in Matlab the magic function, which generates a magic square. However, it always gives the same square while there can be multiple possible magic squares for a given dimension.

Now, I want to generate randomly a magic square of a given dimension, and I have a piece of code here:

while true
    nums = randperm(9);
    A = reshape(nums, 3, 3);
    if all(sum(A, 1) == 15) && all(sum(A, 2) == 15) && sum(diag(A)) == 15 && sum(diag(fliplr(A))) == 15
        break;
    end
end
disp(A);

It works almost fine. It generates the magic square well enough. However, on consecutive runs it gives me the same matrix:

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     1     8
     7     5     3
     2     9     4

>> ranMagic
     6     1     8
     7     5     3
     2     9     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     2     9     4
     7     5     3
     6     1     8

>> ranMagic
     2     9     4
     7     5     3
     6     1     8

>> ranMagic
     2     9     4
     7     5     3
     6     1     8

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

Notice how the first two matrices are the same, then the third and forth, then the fifth and sixth... While it is true that 3D magic squares are scarce in number, with only 8 possible alternatives, this strikes me more than a mere coincidence. How come this happens?




jeudi 7 septembre 2023

Random integer generation performance optimization

I am looking to generate random integers on the interval [0, n) as fast as possible:

from random import Random

rand = Random(123)

def rand_func(max: int, random: Random):
    return int(random.random() * max)

for a in range(10_000_000):                 # perf_counter 9.7s
    ax = rand_func(456, rand)

for b in range(10_000_000):                 # perf_counter 3.9s
    bx = int(rand.random() * 456)

My experience in other languages leaves me surprised at how expensive this function call seems to be.

Is there a method, pattern or decorator I could use to further optimize speed while keeping the code simple and usable?

I've looked at some other less simple solutions. numpy random.integers is very fast at returning a large array of results, but consuming the results becomes more complex and less ideal.

(Of note I'm aware of the bias in the random integer sampling method above but it is acceptable for my requirements).




How to generate random double with RandomNumberGenerator in .NET 6

In .NET 6, as RNGCryptoServiceProvider has been marked as obsolete in .NET, I'm trying to find an alternative to generate evenly distributed random doubles (between 0 inclusive and 1 exclusive). I need something reliable both running on Windows or Linux.

I've found this online and I'd like to know if it reliable and how can I test the distribution.

        // Step 1: fill an array with 8 random bytes
        byte[] bytes = RandomNumberGenerator.GetBytes(8);

        // Step 2: bit-shift 11 and 53 based on double's mantissa bits
        ulong ul = BitConverter.ToUInt64(bytes, 0) / (1 << 11);
        return ul / (double)(1UL << 53);



mercredi 6 septembre 2023

how do i create a game of rock, paper and scissors where the game doesn't end until the user says no when asked if he wants to play again?

I am writing this game of rock, paper and scissors. I have used a while loop and some conditions. in one of the conditions, I have added that if the user wins, don't end the game right away, but instead ask if he wants to play again. if the user says no, then we break out of the loop. but if the user says yes, we start from the beginning of the loop again. but since I want to keep asking this question, how long do I continue this code? do I use some loop again, and if so, then how?

This is the code i have written:

     import random
    a=['rock','paper','scissors']
    b=random.choice(a)
    while True:
        c=input(print("rock,paper,or scissors? "))
        if (b=='rock' and c=='rock') or (b=='paper' and c=='paper') or (b=='scissors' and c=='scissors'):
            print(f"computer's choice:{b}\nyou are tied with the computer")
        elif(b=='rock' and c=='scissors') or (b=='scissors' and c=='paper') or (b=='paper' and c=='rock'):
            print (f"computer's choice:{b}\nyou have unfortunately lost to the computer. do not give up though and try again.")
        elif(b=='scissors' and c=='rock') or (b=='paper' and c=='scissors') or (b=='rock' and c=='paper'):
            print(f"computer's choice:{b}\ncongratulations! you have won against the computer!!")
            d=input(print("giving your answer in yes or no,would you like to play again?"))
            if d=='no':
                break
            else:
                for i in range(1000):
                    c = input(print("rock,paper,or scissors? "))
                    if (b == 'rock' and c == 'rock') or (b == 'paper' and c == 'paper') or (
                            b == 'scissors' and c == 'scissors'):
                        print(f"computer's choice:{b}\nyou are tied with the computer")
                    elif (b == 'rock' and c == 'scissors') or (b == 'scissors' and c == 'paper') or (
                            b == 'paper' and c == 'rock'):
                        print(
                            f"computer's choice:{b}\nyou have unfortunately lost to the computer. do not give up though and try again.")
                    elif (b=='scissors' and c=='rock') or (b=='paper' and c=='scissors') or (b=='rock' and c=='paper'):
                        print(f"computer's choice:{b}\ncongratulations! you have won against the computer!!")
                        d = input(print("giving your answer in yes or no,would you like to play again?"))
                        if d=='no':
                            break
                        else:
                            for i in range(1000):
                                c = input(print("rock,paper,or scissors? "))
                                if (b == 'rock' and c == 'rock') or (b == 'paper' and c == 'paper') or (
                                        b == 'scissors' and c == 'scissors'):
                                    print(f"computer's choice:{b}\nyou are tied with the computer")
                                elif (b == 'rock' and c == 'scissors') or (b == 'scissors' and c == 'paper') or (
                                        b == 'paper' and c == 'rock'):
                                    print(
                                        f"computer's choice:{b}\nyou have unfortunately lost to the computer. do not give up though and try again.")
                                elif (b=='scissors' and c=='rock') or (b=='paper' and c=='scissors') or (b=='rock' and c=='paper'):
                                    print(f"computer's choice:{b}\ncongratulations! you have won against the computer!!")

I don't know where I am going with this.




mardi 5 septembre 2023

getting random sampling from cartesian product

Consider the complex number z = x+iy. I have an object constructor class that can take a complex number and plot something from it, say pole(x,y).

I want to construct an array that considers all the possible combinations of x and y so that I can plot a square grid. Suppose that x and y are

a = [0,1,2]
b = [0,1,2]

then my array of interest is c = np.asarray(list(it.product(a,b)))

Using another complex number w = u+iv, I can also plot the following point by point: pole(x,y)*pole(u,v). I want to construct an array that considers all the possible combinations of z and w, and for this my attempt is

d = c.copy()
e = np.asarray(list(it.product(c,d)))

Up until this point, the code is working as intended especially if I consider an initial array a,b with only five elements. However, in the original problem, I need to consider an initial array a,b with at least 1000 elements. Worst, I need to consider pole(x,y)*pole(u,v)*pole(...)*pole(...) which means I get to have an array with (1000*1000)^4 elements.

What do you suggest I do to create an array that stores all the possible combinations of 2 parameters, 2x2 parameters, 2x2x2 parameters and so on?

I tried using np.meshgrid thinking it is more efficient than it.product but I am at lost after the first instance of

x,y = np.transpoe(np.meshgrid(a,b)).reshape(-1,2)

If I want to consider the next complex number w, I am not sure how to implement meshgrid.

I am also thinking of instead listing all the possible combinations of (x,y), (x,y) and (u,v), and so on, I could randomly pick from their combinations without constructing a huge list to conserve memory. However, I am not sure how to redefine this (documentation

def random_product(*args, **kwds):
    "Random selection from itertools.product(*args, **kwds)"
    pools = map(tuple, args) * kwds.get('repeat', 1)
    return tuple(random.choice(pool) for pool in pools)

to accommodate what I want.




how to sort and combine random generated numbers without large memory?

I will generate lots of integers range from 0 to about 2^30, a integer may appear multiple times. I want to get a result of a sorted array, contain all these integers without duplicate. Are there good algorithms both in time efficiency and memory efficiency? Before, I store all integers, then sort it and combine the duplicate adjacent integers, but it need large memory. The sorted result array's length may be only 1% of that of all integers array. I also get some idea about hash and binary tree, but don't know how is the performance, need help. And are there good algorithms recommend?




AutoHotKey, pick a random word from an array from a text file in a folder

I need help writing an application.

I have different arrays in text files and I would like one word to be randomly selected from them.

animals.txt

For example [ ‘cat’, ‘dog’, ‘horse’ ]

and

furits.txt

[ 'apple', 'banana, ]

When I press: ctrl + a

And the same for fruit

When I press: ctrl + x

Is it possible?

or

When I press: ctrl + d

output:

random animal + 'some text' + random fruit

Unfortunately, I don't have much time to try it, so I'm counting on your help




lundi 4 septembre 2023

RDRAND intrinsics on apple silicon - How to generate a random number in c++?

How would you create a random number based on RDRAND ARM64 intrinsics on apple silicon (M1+) ?

Since arm-v8.5-A RDRAND is supported, but how can you use it on a m1 machine?




Shuffle array of array pyspark columns

I have pyspark column Like this:

                   gm_array
[[1, 4, 6,...], [2, 7, 8,...], [3, 5, 7,...],...]
[[8, 11, 9,...], [7, 2, 6,...], [10, 9, 8,...],...]
[[90, 13, 67,...], [55, 6, 98,...], [1, 6, 2,...],...]
.
.

Now I want to shuffle this single array and also array inside this array, and then I want to pick 5 first element from first 5 array.

1st Out which is randomly shuffle array:

                  gm_array
[[19, 6, 1,...], [9, 80, 5,...], [30, 7, 3,...],...]
[[7, 9, 11,...], [6, 8, 7,...], [18, 7, 10,...],...]
[[90, 1, 7,...], [8, 9, 81,...], [6, 5, 1,...],...]
.
.

2nd Out 1st element of 1st 5 array inside main array:

[19, 9, 30,...]
[7, 6, 18,...]
[[90, 8, 6,...]
.
.



How can I shuffle data in csv file?

I have the following dataFrame

The data is from csv file and I would like to shuffle in each rows

this is my code that I imported csv file

    df = pd.read_csv('data1.csv',header=None, names=cols)
    df1 = df[['kac']]
    print(df1)

how can i do this?

I want to shuffled rows of csv file




crypto's randomInt not random enough?

So I tried to use randomInt from crypto (https://nodejs.org/api/crypto.html#cryptorandomintmin-max-callback) instead of Math.random() and to me it doesn't look random enough. I used to generate a random index for an array so I usually pass 0 and arr.length as min/max.

But a lot of times I get the same numbers. Is it because I am calling it many times in a loop?




dimanche 3 septembre 2023

Why are new seeds derived from older seeds in pseudo random number generators?

I looked through Java's Random class and saw that the initial seed is created using:

public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

But every consecutive seed is derived from old seed using:nextseed = (oldseed * multiplier + addend) & mask;

Why is new seed derived from old seed instead of being derived from system time every time? Maybe even put the system to sleep randomly (0-10ms, depending on last digit of system time or something like that) to ensure even more randomness.




Take random sample from each column by group in R

I have a dataset with several thousand households and for each household the consumption of roughly 60 food items was recorded for one month of the year.

I want to generate annual food consumption for each household and food item for the remaining months of the year by repeatedly sampling (with replacement) from my data.

This is what my data looks like but with only 3 food items.

data <- data.frame(matrix(NA, nrow=120, ncol=5))
names(data) <- c("ID", "Month", "Apple", "Maize", "Bread")
data$ID <- 1:120
data$Month <- rep(1:12, each=10)
data$Apple <- data1$Month + 2 * runif(12) - 1   # Consumption is seasonal but random
data$Maize <- data1$Month + 2 * runif(12) - 1
data$Bread <- data1$Month + 2 * runif(12) - 1

data

I want to group the data by month and then take a random sample from each column (food item) to have data for each household and item for every month of the year. The result should look like the data frame below.

data2 <- data.frame(matrix(NA, nrow=1440, ncol=5))
names(data2) <- c("ID", "Month", "Apple", "Maize", "Bread")
data2$ID <- rep(1:120, each=12)
data2$Month <- rep(1:12)

data2



samedi 2 septembre 2023

(Java) Why does a change in how a for loop index variable counts affect a random boolean result?

Below is a simple problem written for an exercise within the old CS106A Stanford course on Java. I know the course and java version/environment are outdated, but I am starting with this just to lay a foundation of problem solving and algorithmic thinking before I move on to something more contemporary:

`import acm.util.*;
import acm.program.*;

//extends for console output
public class RadioActiveDecay extends ConsoleProgram {
//sets constant of number of inital atoms
private static final int NUM_ATOMS = 10000;
    
    public void run() {
//states intro
        println("There are " + NUM_ATOMS + " atoms initially");
//initial atom amount
        int atomsremaining = NUM_ATOMS;
//sets year variable to be added after each loop run
        int year = 0;
//sets while loop to run until there are no atoms left
            while (atomsremaining > 0) {
//sets for loop to check every atom up the amount remaining each time
                for (int i = atomsremaining; i > 0; i--) {
//checks the atom and if returned true, marks it as decayed and removes it from the remaining amount
                    if (rgen.nextDouble() < 0.5) {
                        atomsremaining--;
                    }
                }
//adds year at the end of loop
            year++;
//prints the amount of atoms remaining after each year
            println("There are " + atomsremaining + " left after year " + year);            
            }
        }
//Private random instance variables
    private RandomGenerator rgen = RandomGenerator.getInstance();
}`

My question is in regards to the for loop. As shown here and as expected, in the program the amount of atoms that decay in the first year is around 50% and they all decay around 13-15 years. However, I previously had the for loop counting in the standard positive incremental manner, i.e.: for (int = 0; i < atomsremaining; i++). When run this way, during the first year only about 30-35% of the atoms decay and they all decay in a longer amount of time, around 20-23 years. Why does this change affect the results? I can't see why having the for loop counter count up or down affects the actual random results. If this is a quirk of these old libraries or the RandomGenerator class included with them I can accept that, but if there is something fundamental I'm missing with how the loops work or the order of how the "atomsremaining" variable in that loop is subtracted I'd love to know.

I have tried changing the program to use a random boolean generator(nextBoolean) but get the same results based on how the for loop is set up. I have also previously made a separate method to generate how many atoms decay in each loop and subtract that from a separate running total of atoms but had the exact same results.




uniform_real_distribution

I've observed that a sample generated from a std::uniform_real_distribution<float> can be equal to 1 (compiled using Visual Studio 2022).

This is in contrast to the description in standard stating that it should be a uniform draw from [0, 1); hence 1 should be excluded.

Is this cause I'm using float instead of double? Or is this a bug in the Visual Studio 2022 implementation?

And what can I do now? It is important for me that the draw is from [0, 1) and not from [0, 1]. My current solution is to replace the draw u by u - std::floor(u).




vendredi 1 septembre 2023

How to generate random number between closed interval in JavaScript? [duplicate]

I’m trying to generate a random number between 10 and 50 inclusive (the interval [10,50]) in JavaScript. I don’t need it to be an integer only, it can be any value in that interval. I know I need to use Math.random(), I’m just stuck on what the code would be to get that particular interval.

I’ve tried Math.random() * 50 + 10, but this doesn’t seem to give me values in the right interval I am looking for.