lundi 31 juillet 2023

Why this simple way to generate random integers work

var r = 12345

func rand() int {
    r = r*1103515245 + 12345
    return r & 0x7fffffff
}

This go function generate random numbers but I do not why it works (I did not evaluate how well it works.. just eyeballing the results). Can someone explain please? Thanks

you could see it here in action: https://go.dev/play/p/ji4-avVV1Mn

I am aware this may not be cryptographically safe.




Cant get rand int back

so im trying to build a snake game, and for somehow, while generating a new apple, im always getting the same results (cords are 0,0) Any idea? Im using VSCode btw.

import java.awt.event.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.util.Random;

public class GamePanel extends JPanel implements ActionListener {
    static final int SCREEN_WIDTH = 600;
    static final int SCREEN_HEIGHT = 600;
    static final int UNIT_SIZE = 25;
    static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
    static final int DELAY = 75;
    final int x[] = new int[GAME_UNITS];
    final int y[] = new int[GAME_UNITS];
    int bodyParts = 6;
    int applesEaten;
    public int appleX;
    public int appleY;
    char direction = 'R';
    boolean running = false;
    Timer timer;
    Random random;

    GamePanel() {
        random = new Random();
        this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
        this.setBackground(Color.BLACK);
        this.setFocusable(true);
        this.addKeyListener(new MyKeyAdapter());
        this.requestFocusInWindow(); // Request focus for the GamePanel
    }
    

    public void startGame() {
        newApple();
        running = true;
        timer = new Timer(DELAY,this);
        timer.start();
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        draw(g);

    }
    public void draw(Graphics g) {

        /*for(int i=0;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {
            g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
            g.drawLine(0,i*UNIT_SIZE ,SCREEN_WIDTH, i*UNIT_SIZE);
        }*/
        g.setColor(Color.red);
        g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
    }
    public void newApple() {
        // Generate random coordinates within the game grid
        appleX = random.nextInt((SCREEN_WIDTH / UNIT_SIZE)) * UNIT_SIZE;
        appleY = random.nextInt((SCREEN_HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
    }    

    public void move() {

    }
    public void checkApple() {

    }
    public void checkCollisions() {
        
    }
    public void gameOver() {

    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // Call move() and checkCollisions() methods here if needed
        repaint(); // This will trigger a repaint of the panel
    }    

    public class MyKeyAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {

        }
    }   
}

I tried to get randint, between like 0-600, and im always getting 0. I tried to set the value of appleX to an static int (appleX = 152;), and got the same result.




how to generate more fine-grained floats than normally generated by Python random()

I have the need to generate millions of random uniformly distributed numbers.

I tried the clever recipe (FullRandom) in https://docs.python.org/3/library/random.html to generate higher precision (or more fine-grained) random numbers – but it was relatively slow. If I use my GPU I can generate random numbers about 45x faster using cupy.random.random – but they aren’t as fine grained. (I can’t convert FullRandom to run on the GPU because there is no cupy equivalent of getrandbits() – I tinkered around a bit with no success.)

So I thought this may be a reasonable hack to possibly get some finer grain size in the cupy floats. Call FullRandom once, then add this to an array generated by cupy.random.random, and then normalise.

for i in range(large_integer):
    fine_grain = FullRandom.random()
    agpu = cupy.random.random(another_large_integer, dtype='float64')
    agpu += fine_grain
    agpu = agpu % 1.0000000000
    do stuff .......

QUESTION: Am I wasting my time? Does the addition and modulo just round the numbers down so that I am left with the same ‘grain size’ as the floats generated by cupy.random.random()?

Thanks in advance for your assistance.




dimanche 30 juillet 2023

Getting error while compiling the Fortran code to generate Gaussian random numbers

program Gaussian_random_number
  implicit none
  integer, parameter :: N = 1000    
  integer, parameter :: idum = -123456789  
  real(kind=8), parameter :: AA = 0.1d0 
  real(kind=8) :: noise 
  double precision::ran2,gasdev
  integer :: i
  do i = 1, N
     noise = AA * gasdev(idum)
     write(*, *) noise
  end do
end program Gaussian_random_number

 !The Uniform Random Number Generator 
DOUBLE PRECISION FUNCTION ran2(idum)
 implicit none
  INTEGER, PARAMETER :: IM1 = 2147483563, IM2 = 2147483399
  INTEGER, PARAMETER :: IA1 = 40014, IA2 = 40692, IQ1 = 53668, IQ2 = 52774, IR1 = 12211, IR2 = 3791
  INTEGER, PARAMETER :: NTAB = 32
  INTEGER :: IMM1, NDIV, idum
  DOUBLE PRECISION, PARAMETER :: AM = 1.0d0/IM1, EPS = 1.2e-7, RNMX = 1.0d0-EPS
  INTEGER :: idum2, j, k
  INTEGER, SAVE ::  iv(NTAB)
  INTEGER, SAVE :: iy
  SAVE idum2

  IMM1 = IM1 - 1
  NDIV = 1 + IMM1 / NTAB

  DATA idum2 / 123456789 /
  DATA iv / NTAB*0 /
  DATA iy / 0 /

  IF (idum.le.0) THEN
    idum = MAX(-idum, 1)
    idum2 = idum
    DO j = NTAB+8, 1, -1
      k = idum/IQ1
      idum = IA1*(idum-k*IQ1) - k*IR1
      IF (idum.lt.0) idum = idum + IM1
      IF (j.le.NTAB) iv(j) = idum
    ENDDO
    iy = iv(1)
  ENDIF

  k = idum/IQ1
  idum = IA1*(idum-k*IQ1) - k*IR1
  IF (idum.lt.0) idum = idum + IM1
  k = idum2/IQ2
  idum2 = IA2*(idum2-k*IQ2) - k*IR2
  IF (idum2.lt.0) idum2 = idum2 + IM2
  j = 1 + iy/NDIV
  iy = iv(j) - idum2
  iv(j) = idum
  IF (iy.lt.1) iy = iy + IMM1
  ran2 = MIN(AM*iy, RNMX)
END FUNCTION ran2


!Gaussian Random Number Generator
double precision function gasdev(idum)
implicit none
integer idum, iset
double precision fac,gset,rsq,v1,v2,ran2
save iset,gset
data iset/0/
if(iset.eq.0)then
1 v1 = 2.0*ran2(idum) - 1.0
  v2 = 2.0*ran2(idum) - 1.0
  rsq = v1**2.0 + v2**2.0
  if(rsq.ge.1.0.or.rsq.ge.0.0)goto 1
  fac = sqrt(-2.0*log(rsq)/rsq) 
  gset = v1*fac
  gasdev = v2*fac
  iset = 1
else
  gasdev = gset
  iset = 0
end if
end function gasdev 

I am trying to print Gaussian random numbers using the methods given in numerical recipes. The code is written in Fortran and compiling successfully. But I am getting error like "Segmentation fault - invalid memory reference" while executing the code. How to solve the problem? The code is given below




rock,paper,scissors gone wrong. c#

i'm a beginner in c#, i was making a simple rock,paper,scissors game, when the code was done i ran it, and the problem is that each time i pick rock,paper or scissors i get stuck in a loop where the console displays the computer pick, and if I won or lost (or if it's a tie).

here is a look at my stuckable, unsuccesful code :

using System.ComponentModel.Design;
using System.Runtime.CompilerServices;

Random random = new Random();

bool playagain = true;
String player = "";
int computer;
computer = random.Next(1,4);
Console.WriteLine("Enter, ROCK,PAPER,SCISSORS : ");
player = Console.ReadLine();
player = player.ToUpper();

while (playagain == true)
{
    
    
    while (player != "ROCK" && player != "PAPER" && player != "SCISSORS")
    {
        Console.WriteLine("Enter, ROCK,PAPER,SCISSORS : ");
        player = Console.ReadLine();
        player.ToUpper();


    }



    switch (computer)
    {
        case 1:// computer = rock
            if (player.Equals("ROCK"))
            {
                Console.WriteLine("Computer : Rock");
                Console.WriteLine("It's a tie !");
            }


            else if (player.Equals("PAPER"))
            {

                Console.WriteLine("Computer : ROCK");
                Console.WriteLine("You lose !");


            }
            else
            {
                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("You win !");

            }
            break;
        case 2:// computer = paper
            if (player.Equals("ROCK"))
            {
                Console.WriteLine("Computer : PAPER");
                Console.WriteLine("You lose !");
            }


            else if (player.Equals("PAPER"))
            {

                Console.WriteLine("Computer : PAPER");
                Console.WriteLine("It's  a tie  !");


            }
            else// player = scissors 
            {
                Console.WriteLine("Computer : PAPER");
                Console.WriteLine("You win !");

            }

            break;
        case 3: // computer = scissors 
            if (player.Equals("ROCK"))
            {
                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("You win !");
            }


            else if (player.Equals("PAPER"))
            {

                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("You lose  !");


            }
            else// player = scissors 
            {
                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("It's a tie  !");

            }
            break;

            

    }


    }
    Console.WriteLine("Do you want to play again? (yes/no)");
    String response = Console.ReadLine().ToLower();
    playagain = response == "yes";
    if (playagain.Equals("yes"))
        {
        Console.WriteLine("Enter, ROCK,PAPER,SCISSORS : ");
        player = Console.ReadLine();



        }

can anyone solve this, it's prolly an easy fix, but i'm to new to figure it out....

i tried moving the part where the player is asked if he want to continue tha game or not, specifcally this portion of the code :

    Console.WriteLine("Do you want to play again? (yes/no)");
    String response = Console.ReadLine().ToLower();
    playagain = response == "yes";
    if (playagain.Equals("yes"))
        {
        Console.WriteLine("Enter, ROCK,PAPER,SCISSORS : ");
        player = Console.ReadLine();



        }

nothing changed.




How to generate random between 0 and 1 in Netlogo with uniform distribution

I am trying to do some testing and stumble across the problem that (random 2 = 0) does always give me much more 0 than 1s, even though it is supposed to be uniform distribution. Any ideas?




rock,paper,scissors infinte loop

I'm very new to c#, i was making a simple rock,paper,scissors game everytime i run the code, i get stuck in a loop.

take a look at the code :

using System.ComponentModel.Design;
using System.Runtime.CompilerServices;

Random random = new Random();

bool playagain = true;
String player = "";
int computer;
computer = random.Next(1,4);
Console.WriteLine("Enter, ROCK,PAPER,SCISSORS : ");
player = Console.ReadLine();
player.ToUpper();

while (playagain)
{
    
    
    while (player != "ROCK" && player != "PAPER" && player != "SCISSORS")
    {
        Console.WriteLine("Enter, ROCK,PAPER,SCISSORS : ");
        player = Console.ReadLine();
        player.ToUpper();


    }



    switch (computer) {
        case 1:// computer = rock
            if (player.Equals("ROCK"))
            {
                Console.WriteLine("Computer : Rock");
                Console.WriteLine("It's a tie !");
            }


            else if (player.Equals("PAPER"))
            {

                Console.WriteLine("Computer : ROCK");
                Console.WriteLine("You lose !");


            }
            else {
                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("You win !");

            }
            break;
        case 2:// computer = paper
            if (player.Equals("ROCK"))
            {
                Console.WriteLine("Computer : PAPER");
                Console.WriteLine("You lose !");
            }


            else if (player.Equals("PAPER"))
            {

                Console.WriteLine("Computer : PAPER");
                Console.WriteLine("It's  a tie  !");


            }
            else// player = scissors 
            {
                Console.WriteLine("Computer : PAPER");
                Console.WriteLine("You win !");

            }

            break;
        case 3: // computer = scissors 
            if (player.Equals("ROCK"))
            {
                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("You win !");
            }


            else if (player.Equals("PAPER"))
            {

                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("You lose  !");


            }
            else// player = scissors 
            {
                Console.WriteLine("Computer : SCISSORS");
                Console.WriteLine("It's a tie  !");

            }
            break;



    }

}

evertime i run this code, i get stuck in a loop with the console displaying : Enter, ROCK,PAPER,SCISSORS :.

i tried putting the : Enter, ROCK,PAPER,SCISSORS : text outside of the main while loop, but nothing changed, it's very strange.




Cannot implicitly convert type 'bool' to 'int' with switch statement

I'm very new to c#, and I'm trying to make a simple number-guessing game, basically the user enters their guess and if the guess is the higher than the number, the system will display the it's higher or lower.

this is the code:

using System.Diagnostics.Tracing;

Random random = new Random();   

int num = random.Next(0,101);

Console.WriteLine("This is a number guessing game between 1 - 100 ! ");
Console.WriteLine("Enter your guess : ");
int respond = Convert.ToInt32(Console.ReadLine());



switch (respond) {

    case respond > num: Console.WriteLine("");
        break;

    case respond < num: Console.WriteLine("");
        break;
    case respond == num  : Console.WriteLine("You won !");
        break;


}




Console.WriteLine("You won !");
Console.WriteLine("It took you " + tries + " tries");



Console.ReadKey();

the problem comes in this part, the switch :

switch (respond) {

    case respond > num: Console.WriteLine("");
        break;

    case respond < num: Console.WriteLine("");
        break;
    case respond == num  : Console.WriteLine("You won !");
        break;
}

I always get an error when trying to compare 'respond' and 'num', specifically, this error :

Cannot implicitly convert type 'bool' to 'int'

does anyone know how to fix it?

I tried changing the place and the variable respond, same with 'num' nothing seemed to work.




samedi 29 juillet 2023

How to generate random text in each iteration in Jmeter tool

added the loop count as 10 Used randomString function to generate random string at each iteration

After 10 loops random string - example: "testabc" only generated 10 times.

What need to change if I expect 10 random Text

I have changed loop count, number of threads & so on. But the same result as random string generated as - "Testabc" for 10 loop counts




Create a list with the greatest gap between known occurrences

This is a python question.

If I have a dictionary of web addresses (key) has an associated name server (value).

A name server can be associated with more than 1 web address, anywhere from 1 to 10 times.

The dictionary is a few hundred addresses long.

a) From this dictionary I want to create a random list of web addresses that must have the greatest gap between the repeated use of the name server used and web address.

b) The random list may be 5-100 times the initial size of the dictionary. Hence (a)

I know how to cycle through, etc but how do I calculate the gap size ? Or better yet, anyone coded something like this before ? Python please. Hope this is clear enough.




My two-dimensional Sobol points seem wrong (from the scipy qmc module)

I'm using the qmc module from scipy to generate a Sobol sequence of 1024 2d points in this fashion:

        sampler = qmc.Sobol(d=2, scramble=False)
        sample = sampler.random_base2(10)
        points = torch.tensor(sample_scaled) 

But when I plot these points using

    points = points.numpy()
    plt.scatter(points[:, 0], points[:, 1], s= 0.2)

I get a figure that looks like this:

enter image description here

This seems totally wrong (compare this to the figure in the Wiki entry. What am I doing wrong?




vendredi 28 juillet 2023

Why do most `rdrand` implementations use signed integers as return value instead of an unsigned integer?

While browsing rdrand implementations (e.g. here) in C for curiousity, I've stumbled upon a detail I could not figure out myself.

Why do most rdrand implementations actually return a signed integer, instead of an unsigned integer? Since unsigned integers wrap around and cannot overflow, why use signed integers in random number generation in fist place, when it's the signed integers that are prone to integer overflows? Wouldn't it be more safe to return an unsigned integer?




jeudi 27 juillet 2023

Fourier Synthesis of randomly generated Sinusoidal waves using Math.NET Numerics

I'm trying to create a generator (i.e. a IEnumerable<double>) that mimics the variability of a power grid frequency signal. I had the idea that if I overlay some noise over the top of a series of composed sine waves, I might be able to get the kind of plausible shape I need.

Here's a good example of the kind of curve I need to reproduce. Not necessarily with the frequency excursion, which I can handle separately.

enter image description here

Alas, my math is a bit shaky on this and I can't find any nice libraries to handle the composition itself. Does anyone know how to piece together a new distribution given a set of generators based on Generate.Sinusoidal (see here: Math.NET Numerics Generation)




How to create a list of random numbers in c++ like in python

In Python I use the following function to create a list of random numbers between a range and with an amount of numbers. In this case the function throws me: 100 random numbers between 1 and 50.

randnums1= list(np.random.randint(1,50,100))

I want to know how to generate a list of random numbers between a range and with an amount of numbers




mercredi 26 juillet 2023

How do I take original files in one directory, shuffle the names to be randomized for the actual file, and move them without overwriting

I am working on taking the names of daily email list files for one week and randomizing the names/days of the files for the next week to where they wont get contacted on the same day of the week. I've been using random.choice() with the directory to change the name of the file to one of the existing ones in the original folder and moving it to a new folder, but when I get to the third or fourth file it either overwrites or stops completely.

import os
import random
import shutil

def shuffle_and_move_files(source_folder, destination_folder):
    if not os.path.exists(source_folder):
        print(f"Source folder '{source_folder}' does not exist.")
        return

    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    files_list = os.listdir(source_folder)
    random.shuffle(files_list)

    for filename in files_list:
        source_path = os.path.join(source_folder, filename)
        if os.path.isfile(source_path):

            random_name = random.choice(file_list)
            
            destination_path = os.path.join(destination_folder, random_name)
            
            shutil.move(source_path, destination_path)
            
            print(f"Moved '{filename}' to '{random_name}'")



mardi 25 juillet 2023

Samurai Sudoku Generator needs a clever blanking/masking technique [closed]

I have written a Samurai Sudoku Generator. It generates 5 Sudokos that overlap, this is an example output array using kronecker product as main matrix shuffler:

[[1 2 3 4 5 6 7 8 9 0 0 0 2 3 1 5 6 4 8 9 7]
 [4 5 6 7 8 9 1 2 3 0 0 0 5 6 4 8 9 7 2 3 1]
 [7 8 9 1 2 3 4 5 6 0 0 0 8 9 7 2 3 1 5 6 4]
 [2 3 1 5 6 4 8 9 7 0 0 0 9 7 8 6 4 5 3 1 2]
 [5 6 4 8 9 7 2 3 1 0 0 0 3 1 2 9 7 8 6 4 5]
 [8 9 7 2 3 1 5 6 4 0 0 0 6 4 5 3 1 2 9 7 8]
 [3 1 2 6 4 5 9 7 8 6 4 5 1 2 3 4 5 6 7 8 9]
 [6 4 5 9 7 8 3 1 2 9 7 8 4 5 6 7 8 9 1 2 3]
 [9 7 8 3 1 2 6 4 5 3 1 2 7 8 9 1 2 3 4 5 6]
 [0 0 0 0 0 0 7 8 9 4 5 6 2 3 1 0 0 0 0 0 0]
 [0 0 0 0 0 0 1 2 3 7 8 9 5 6 4 0 0 0 0 0 0]
 [0 0 0 0 0 0 4 5 6 1 2 3 8 9 7 0 0 0 0 0 0]
 [2 3 1 5 6 4 8 9 7 5 6 4 3 1 2 6 4 5 9 7 8]
 [5 6 4 8 9 7 2 3 1 8 9 7 6 4 5 9 7 8 3 1 2]
 [8 9 7 2 3 1 5 6 4 2 3 1 9 7 8 3 1 2 6 4 5]
 [3 1 2 6 4 5 9 7 8 0 0 0 1 2 3 4 5 6 7 8 9]
 [6 4 5 9 7 8 3 1 2 0 0 0 4 5 6 7 8 9 1 2 3]
 [9 7 8 3 1 2 6 4 5 0 0 0 7 8 9 1 2 3 4 5 6]
 [1 2 3 4 5 6 7 8 9 0 0 0 2 3 1 5 6 4 8 9 7]
 [4 5 6 7 8 9 1 2 3 0 0 0 5 6 4 8 9 7 2 3 1]
 [7 8 9 1 2 3 4 5 6 0 0 0 8 9 7 2 3 1 5 6 4]]

A better visual reprensentation is given by the pdf version: (https://i.stack.imgur.com/Vc6T1.png)

I dont know if it has been the long hours or what but i can't come up with a nice blanking / masking technique so that i generate the puzzle from the solution. How can i make sure each sudoko on its own remains solvable and how do i also control the difficulty. I'm completely out of ideas.

I have tried random deletion of numbers but that can lead to bad cases. I need a bullet proof solution that works each time and makes sure the samurai sudoku is always solvable (doesnt need to give only 1 unique solution).




mountain car with random agent

I am evaluating 'env = gym.make('MountainCar-v0', render_mode='rgb_array')' on random agent and getting 100% success rate that is weired can you please guide me on this.

Means always get car position greater than 0.5 which is the goal.

Code:

env = gym.make('MountainCar-v0', render_mode='rgb_array')
state, _ = env.reset()
max_position = -99
done = False
while not done:
    action = env.action_space.sample()
    next_state, reward, done, trun, info = env.step(action)
    
    if next_state[0] > max_position:
        max_position = next_state[0]
         
print(next_state[0], max_position)

0.50212365 0.50212365

I compared with other problems they are getting 0% success rate with random agent




Java Game with While Loop as sum 2 randoms

I'm doing a program in java that needs me have the 2 random in 6 to sum and also use a while loop. This is all I currently have, can anyone help as what I'm missing?

import java.util.Random;//*
import java.io.IOException;//*
class Test
{
    public static void main(String[] args) throws IOException{ //*
        System.out.print("按下Enter開始遊戲");
        int point=getPoint();
        int sum=0;      
        
        while(true)
        {
            System.in.read();
            
            if(System.in.read()=='n')
            {
                System.out.println("遊戲結束");
                break;
            }
            if(sum==0)
            {
                switch(point)
                    {
                            case 7:
                            case 11:
                                
                                    System.out.println("總和:"+point+" Winner");

                                break;                  
                            case 2:
                            case 3:
                            case 12:
                                
                                    System.out.println("總和:"+point+" False");                   
                                                    
                                break;
                            default:                                
                                break;
                    }       
                                
            }
                                
                if(sum==point)
                {
                    System.out.println("第1次總和為:"+point+"目前總和為"+sum+" Winner");
                    break;                      
                }else
                {                                                               
                    System.out.println("第1次總和為:"+point+"目前總和為"+sum+"是否繼續?");
                                        
                }
                sum=getPoint();                                                             
            
        }
    }
    public static int getPoint()
    {
        Random Ran =new Random();           
        int a=Ran.nextInt(6)+1;
        int b=Ran.nextInt(6)+1;//math.random改寫
        int sum=a+b;
        return sum; 
    }
}

...

else
                {                                                               
                    System.out.println("第1次總和為:"+point+"目前總和為"+sum+"是否繼續?");
                                        
                }

Why does it will print twice when I just Enter ''a'' 1 times in ''While'' Loop

I want when I Enter ''a'' each times and This code just run 1 times not 2 times




Can't find OPENSSL_cpuid_setup() to load custom engine for OpenSSL in C/C++

I'm trying to force OpenSSL's random number generator to use RDRAND, as described in the OpenSSL wiki here and also cited in this Stackoverflow post.

However, when I try to call this function OPENSSL_cpuid_setup();, I get the following error:

error: ‘OPENSSL_cpuid_setup’ was not declared in this scope

I've imported the following files, neither of which contain the function:

#include <openssl/evp.h>
#include <openssl/engine.h>

I've done some digging and it appears the function is present in cryptlib.h of OpenSSL, but I can't import that file.

This Stackoverflow answer seems to suggest that I don't need to call that function; indeed, when I comment that function out, the remainder of the code runs without error. Does anyone know what file I'm supposed to import, and whether the function call is necessary?




lundi 24 juillet 2023

Generate a random account unique number, using php, and laravel [closed]

Hi guys am not asking the question but i just want to share my idea on how i have implement it

Here is the my method on a controller

public function generateAndInsertTheAccountNumbers(Request $request)
    {
        $data = $request->validate(['numberOfAccounts' => "required|numeric"]);
        $numberOfBankAccountToGenerate = $data['numberOfAccounts'];
        $errorTimes = 0;
        $min = 1000000
        $max = 9999999
        for ($i = 0; $i < $numberOfBankAccountToGenerate; $i++) {
            try {
                AccountNumber::create(['accountNumber' => rand($min, $max)]);
            } catch (\Throwable $th) {
                $i--;
                $errorTimes ++;
            }
        }
        return response(['message' => "Successfully generate total of ".$numberOfBankAccountToGenerate." account numbers contain errors times ".$errorTimes]);
    }

So basically what am doing here is am generating the account number then store them on my db as you can see the number are not generated on demand as when the user is registering we just pick the first number that we could find in the account number table then use it then delete it from the account table, so in my model of accountnumber the accountNumber column is unique so if there was a repeation of the number we will try to generate a new account number that's it.

As of now the solution is fine, because we combine the number with other numbers that is unique to the user so if we combine with the account number that we generate we get a unique account number, i hope it helps someone out there.

NOTE: This is just a simple solution to my problem and it is not pure randomness if you want to have a pure random number consider go and see the api provided by random org




Weird behavior when passing a random number to html in javascript

I have the following HTML file where I want a number level within 50% of a given target (the "Level" field) to be input into the "Attribute" field

<!DOCTYPE html>

<html>
    <body>
        <input type = "number" name = "playerLevel" onchange = "populateAttributes()" id = "playerLevel">
        <label for = "playerLevel">Level</label>
    </body>

    <br>

    <tr>
        <td><input type = "number" id = "attributeScore"></td>
        <label for = "attribute">Attribute</label>
    </tr>

    <script src = "script.js"></script>
</html>

And I have the following Javascript code to generate random numbers

function generateRandomLevel(targetLevel)
{
    const target = targetLevel; // The target around which the random levels are generated
    const range = 0.5;  // 0.5 => 50% deviation from target and so on
    const upperLevelLimit = Math.round(target + target * range);    // Target + 50% deviation
    const lowerLevelLimit = Math.round(target - target * range);    // Target - 50% deviation
    let x = parseInt(Math.random() * (upperLevelLimit - lowerLevelLimit) + lowerLevelLimit);    // Generate Level within 50% of target
    return x;
}

function populateAttributes()
{
    let y = generateRandomLevel(document.getElementById("playerLevel").value);  // Passes the value of "playerLevel" to the random nunber generator
    document.getElementById("attributeScore").value = y;    // Set the value inside "playerLevel" to the random number generated
}

However, when I update the "Level" field, I get numbers totally out of range of the target like 72 incase of entering 10 into the "Level" field.

Does anyone know why this happens?

When I run the random number generator as a standalone, it works just fine, i.e

function generateRandomLevel(playerLevel)
{
    const target = playerLevel;
    const range = 0.5;
    const upperLevelLimit = Math.round(target + target * range);
    const lowerLevelLimit = Math.round(target - target * range);
    let x = parseInt(Math.random() * (upperLevelLimit - lowerLevelLimit) + lowerLevelLimit);
    return x;
}

console.log(generateRandomLevel(10));



how does the rand() function work in c++?

im trying to get back into coding so i figured id do a magic 8 ball type of program. im having trouble with rand() as i dont understand how to set a limit on it, for example i want to have 8 answers but wouldnt using rand() make it so it picks a number from 0-32767, is there a way to set it to a desired value or is there a better way to do this?

i tried this but it didnt work, apologies if thats a simple mistake but i decided to try using what i vaguely remember, ill go with tutorials to remember later

#include <iostream>
#include <cstdlib>

RAND_MAX = 6;
int number ;

int main(){
 
while(true){
    std::cout << "ask a question: ";
     rand() << number;
     std::cout << "your number is: " << number;
     return 0;
}


}

in this specific code i tried to just set the random numbers limit to see if that worked before i continued also this was the error it gave me

Untitled-1.cpp: In function 'int main()': Untitled-1.cpp:6:13: error: lvalue required as left operand of assignment RAND_MAX = 6; ^




dimanche 23 juillet 2023

strange behavior with randint in python

rol_dict = { 0: "value 1", 1: "value 2", 2: "value 3" }

def rol_rand():
    global rol_list
    return rol_dict.get(randint(0, 2))

rol_rand()

if rol_rand() == rol_dict.get(0):
    print("value 1")
elif rol_rand() == rol_dict.get(1):
    print("value 2")
elif rol_rand() == rol_dict.get(2):
    print("value 3")
else:
    print(rol_rand())
    print("rol don't exist")

For this code some times appear this output

value 1
rol don't exist

why???

Why does this behavior occur and what alternatives exist?




save a created random number in state and keep it as it is Reactjs

I created a chat application and allowed the user to create a chat room at any time with a name chosen by the user, and every time the user typed the name of the same room, the application will enter him in the same chat that he did before,

and I created a function that generates a random number for the room that is generated, but even if I write the name of the same room, it generates a different number for the same room,

how do I keep the number that was created the first time for the room?

this is app.js code:

import './style.scss';
import Register from "./pages/Register.jsx";
import Login from './pages/Login';
import { Home } from './pages/Home';
import { Auth } from './components/Auth';
import { useState, useRef } from 'react';
import Cookies from "universal-cookie";
import Chat from './components/Chat';
import {auth} from "./firebase";
import { signOut } from "firebase/auth";
import randomString from 'random-string';
const cookies = new Cookies();

function App() {
  const [isAuth, setIsAuth] = useState(cookies.get("auth-token"));
  const [room, setRoom] = useState(null);

  const roomInputRef = useRef(null)

  var x = randomString({
    length: 8,
    numeric: true,
    letters: false,
    special: false,
    
    });

  const signUserOut = async() => {
    await signOut(auth)
    cookies.remove("auth-token")
    setIsAuth(false)
    setRoom(null)
  }

    if (!isAuth) {
    return (
      <div className="App">
        <Auth setIsAuth={setIsAuth}/>
      </div>
    );
  }

  return (
  <>
    {room? (
      <Chat room={room} setRoom={setRoom} x={x}/>
        ) : (
          <div className='room'> 
            <label>Enter room name:</label>
            <input ref={roomInputRef}/>
              <button onClick={() => [randomString(),setRoom(roomInputRef.current.value)]}>
                Enter chat
              </button>
          </div>
        )
      }

      <div className='sign-out'>
        <button onClick={signUserOut}> logout </button>
      </div>

    </>
    )
}

export default App;

this is Chat.jsx code:

import { useEffect, useState } from "react";
import { addDoc, collection, serverTimestamp, onSnapshot, query, where, orderBy } from "firebase/firestore";
import { auth, db } from "../firebase";
import "../styles/Chat.css";


const Chat = (props) => {
  const {room, setRoom, x} = props
  const [newMessage, setNewMessage] = useState("");
  const [messages, setMessages] = useState([]);

  const messagesRef = collection(db, "messages");

  useEffect(()=>{
    const queryMessages = query(
      messagesRef, 
      where("room", "==", room), 
      orderBy("createdAt")
      );
    const unsubscribe = onSnapshot(queryMessages, (snapshot)=>{
      let messages = [];
      snapshot.forEach((doc) => {
        messages.push({ ...doc.data(), id: doc.id })
      });
      setMessages(messages)
    });

    return () => unsubscribe();
  },[])

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (newMessage === "") return;

    await addDoc(messagesRef, {
      text: newMessage,
      createdAt: serverTimestamp(),
      user: auth.currentUser.displayName,
      room,
    });

    setNewMessage("")
  };

  const roomExit = () => {
    setRoom(null)
  }

  return (
    <div className='Chat'>
      <div className="header">
        <h1> Welcome to: {room} number: {x} </h1>
      </div>
      <div className="messages">
        {messages.map((message) => (
        <div className="message" key={message.id}>
          <span className="user"> {message.user} </span>
          {message.text}
        </div>
        ))}
        </div>
      <form onSubmit={handleSubmit} className="new-message-form">
        <input 
        className="new-message-input" 
        placeholder="Type your message here..."
        onChange={(e) => setNewMessage(e.target.value)}
        value={newMessage}
        />
        <button type="submit" className="send-button">Send</button>
      </form>
      <button onClick={roomExit}>change room</button>
    </div>
  )
}

export default Chat



Does the Windows RNG have security problems?

The Windows RNG infrastructure is specified in this article. On page 4, it states that the PRNG called AES_CTR_DBNG is used.

According to Wikipedia, this PRNG has security problems when used with certain parameters.

Specifically:

When AES is used as the underlying block cipher and more than 128 bits are taken from this pseudorandom number generator, then the resulting security level is limited by the block size instead of the key size and therefore the actual security level is much less than the security level implied by the key size.

In my understanding, pseudorandom number generators are often used to produce thousands of random bits before reseeding, and thus many more than 128. Does this mean that the Windows RNG is unsafe?




select random item from a drop down list in excel

I have an Excel sheet with cells that can be filled only with items from the dropdown list and I want to fill it randomlyenter image description here

many of the solutions on the web select a random value from a list (not a dropdown list) this does not work for me because my drop-down lists are dependent on other cells so they change based on them what i want is to randomly select items from each new dropdown list




samedi 22 juillet 2023

TypeError: object of type 'NoneType' has no len() - unable to send text to webpage from random selection from txt file

Trying to get this function to work but it wont allow me to use send the random text picked (mylines).

driver.find_element(By.XPATH, '//*[@id="AppRouter-main-content"]/div/div/div[2]/div[3]/div[1]/div[2]/div[3]/div[2]/div[1]/div/textarea').send_keys(print(myline))

Text to be input into writing feild from txt file.




Math.ceil ; Math.random

Here's a very basic issue that i cannot resolve on my mind:

In JS if i do:

Math.random() i will get random numbers between 0 and 1 (including 0, not including 1)

So, if i do Math.ceil(Math.random() * 100) i will get random numbers between 0 and 100. Am i right?

I will get 0 if Math.random() was exactly 0, which is possible as i read in the documentation.

However I read everywhere that doing this "Math.ceil(Math.random() * 100)" i will get numbers between 1 and 100.

Please, can someone clarify this situation?

Thanks!

Math.random () -> [0; 1) Math.ceil(Math.random()) -> [0; 100]




C++ mt19937 getting the same sequence multiple times

im trying to create a deterministic hash generator using a pseudo random number sequence with the mt19937 engine in the random library. Therefore i need to get the same sequence of numbers everytime i feed the engine the same seed. My code looks like this:

#include <iostream>
#include <random>
#include <time.h>
#include <Windows.h>

int randomnumber = 0;

int main(){
    std::random_device rd;
    std::uniform_int_distribution<int> dist(0, 1);

    std::mt19937(123);
    for (int i = 0; i < 32; i++) {
        randomnumber |= ((unsigned)(dist(rd)) << i);
    }
    std::cout << (unsigned int)randomnumber << std::endl;

    std::mt19937(112);
    for (int i = 0; i < 32; i++) {
        randomnumber |= ((unsigned)(dist(rd)) << i);
    }
    std::cout << (unsigned int)randomnumber << std::endl;

    std::mt19937(123);
    for (int i = 0; i < 32; i++) {
        randomnumber |= ((unsigned)(dist(rd)) << i);
    }
    std::cout << (unsigned int)randomnumber << std::endl;

    return 0;
}

I tried setting the seed everytime i generated a new hash but the random number sequence was different never the less.

The outputs are

1126954929

3745251263

3753639871




In a MYSQL table of word definitions, within sql add 3 columns/fields of definitions taken randomly from other rows

I have a MYSQL table called aa_ngl_defs of the following form:

id Word POS Definition
1 the article used to point to something already mentioned
2 be verb used to show the identity of a thing
3 and conj used to join words or groups of words
4 of prep belonging to or connected with something
5 to prep used to indicate place or direction
6 a article one particular thing or one of a class of things
7 in prep used to indicate being inside of or surrounded by something else
8 have verb to own, possess, or hold something
9 it pronoun a thing that has been previously mentioned
10 you pronoun used to refer to the person the speaker is addressing
11 he pronoun used to refer to a male person that is the subject
12 for prep indicating the purpose or need of something
13 they pronoun used to refer to two or more people, animals, or things
14 not adverb used to make an expression negative
15 that adj used to identify a specific person, thing, fact or idea
16 we pronoun used to refer to the speaker and another person as the subject
17 on prep touching and being supported or physically in contact by something

The table has unique contiguous integers in the id column.

I want to create a new table by adding 3 columns of definitions taken randomly from other rows within this table. This would allow me to create quizzes with 3 distractors. I need reasonable performance speed but not necessarily high speed, as the table has 3,500 rows but I only need to generate a new quiz once-a-week.

So that it looks like this:

id  Word    POS Correct_Definition   Distractor1    Distractor2   Distractor3

The online quiz generators Quizlet, Kahoot and Blooket are able to take a simple list like this and produce quizzes with 3 distractors. That's what I'm trying to emulate.

The following works OK for adding 1 extra distractor definition:

    SELECT t1.id, t1.Word, t1.Definition, t2.Definition
    FROM aa_ngl_defs AS t1
    LEFT JOIN aa_ngl_defs AS t2 
      ON t1.id <> t2.id -- Ensure we don't join the row with itself
    ORDER BY RAND()
    LIMIT 3;

But I don't know how to add two more distractor definitions, and also my query took 17s which I suspect will multiply exponentially if I try to add more columns.

I tried to incorporate the following to improve performance

    SELECT *
      FROM aa_ngl_defs AS r1 JOIN
        (SELECT (RAND() * (SELECT MAX(id) FROM aa_ngl_defs)) AS id
        )
            AS r2
     WHERE r1.id >= r2.id
    ORDER BY r1.id ASC
    LIMIT 1;

... and this works very fast to select one row at random, but I am completely lost as to how incorporate this to add the three distractors. I think I need nested select statements or perhaps variables.

Obviously, since each row will have 3 distractors there will be some repeats of distractors across rows, but I can't have repeated distractors within any single row. Randomness only needs to be reasonably random, not strictly so.




I try to choose a random item from a list, but it constantly shows an error

I am making a terminal based game on python using the random module. In the following example, I am doing such, but the code return with the error TypeError: choice() takes 2 positional arguments but 282 were given.

import random

academy = random.choice('Manchester City',  'Manchester United',    'Liverpool',    'Arsenal',  'Newcastle',    'Brighton', 'Tottenham',    'Aston Villa',  'West Ham', 'Chelsea',  'Crystal Palace',   'Brentford',    'Southampton',  'Bournemouth',  'Fulham',   'Wolves',   'Nottingham Forest',    'Leicester City',   'Everton',  'Leeds', 'Burnley', 'Sheffield United', 'Luton Town',   'Middlesbrough',    'Coventry City',    'Sunderland',   'Blackburn Rovers', 'Milwall',  'West Brom',    'Swansea',  'Watford',  'Preston',  'Norwich City', 'Bristol City', 'Hull City',    'Stoke City',   'Birmingham United',    'Cardiff City', 'Reading',  'Blackpool',    'Wigan Atheltic',   'Plymouth Argyle',  'Ipswitch Town',    'Sheffield Wednesday',  'Barnsley', 'Bolton Rovers',    'Peterborough', 'Derby County', 'Portsmouth',   'Wycombe',  'Charlton Atheltic',    'Lincoln City', 'Shrewsbury',   'Fleetwood',    'Exeter City',  'Burton',   'Cheltenham',   'Briston Rovers',   'Port Vale',    'Oxford United',    'Cambridge United', 'MK Dons',  'Morecambe',    'Accrington Stanley',   'Forest Green', 'Leyton Orient',    'Stevenage',    'Northampton Town', 'Stockport',    'Carlisle', 'Bradford City',    'Salford City', 'Mansfield Town',   'Barrow',   'Swindon Town', 'Grimsby Town', 'Tranmere', 'Crewe Alexandria', 'Sutton United',    'Newport County',   'Walsall',  'Gillingham',   'Doncaster',    'Harrogate Town',   'Colchester',   'AFC Wimbledon',    'Crawley Town', 'Hartlepool',   'Rochdale', 'Wrexham',  'Notts County', 'Barcelona',    'Real Madrid',  'Real Sociedad',    'Atletico Madrid',  'Villareal',    'Real Betis',   'Osasuna',  'Athletic Club de Bilbao',  'Mallorca', 'Girona',   'Rayo Vallecano',   'Sevilla',  'Celta Vigo',   'Cadiz',    'Getafe',   'Valencia', 'Almeria',  'Valladolid',   'Espanyol', 'Elche',    'Granada',  'Las Palmas',   'Levante',  'Alaves',   'Eibar',    'Albacete', 'Andorra',  'Oviedo',   'FC Cartagena', 'Tenrife',  'Burgos',   'Racing',   'Zaragoza', 'Leganes',  'Huesca',   'Mirandes', 'Sporting Gijon',   'Ponferradina', 'Malaga',   'Ibiza',    'Lugo', 'Napoli',   'Lazio',    'Inter Milan',  'AC Milan', 'Atalanta', 'Roma', 'Juventus', 'Fiorentina',   'Bologna',  'Torino',   'Monza',    'Udinese',  'Sassuolo', 'Empoli',   'Salernitana',  'Lecce',    'Verona',   'Speiza',   'Cremonese',    'Sampdoria',    'Forsinone',    'Genoa',    'Bari', 'Parma',    'Cagliari', 'Sudtirol', 'Reggina',  'Venezia',  'Palermo',  'Modena',   'Pisa', 'Ascoli',   'Como', 'Ternana',  'Cittadella',   'Brescia',  'Cosenza',  'Perugia',  'SPAL', 'Benevento',    'Bayern Munich',    'Borussia Dortmund',    'RB Leipzig',   'Union Berlin', 'SC Freiburg',  'Bayer Leverkusen', 'Eintracht Frankfurt',  'Wolfsburg',    'Mainz',    'Monchengladbach',  'Koln', 'Hoffenheim',   'VfL Bochum',   'Augsburg', 'VfB Stuttgart',    'Schalke',  'Hertha Berlin',    'Heidenheim',   'Darmstadt',    'Hamburger',    'Dusseldorf',   'St. Pauli',    'Paderborn',    'Karlsruher',   '1. FCK',   'Hannover 96',  'Magdeburg',    'Furth',    'Hansa Rostock',    'Nurnberg', 'Eintracht Braunshweig',    'Arminia Biefield', 'Jahn Regensburg',  'Sanhausen',    'Paris Saint Germain',  'Lens', 'Marsielle',    'Rennes',   'LOSC', 'Monaco',   'Olympique Lyonnais',   'Clermont Foot',    'Nice', 'Lorient',  'Reims',    'Montpellier',  'Toulouse', 'Brest',    'Strasbourg',   'Nantes',   'Auxerre',  'Ajaccio',  'Troyes',   'Angers',   'Le Havre', 'Metz', 'Bordeaux', 'Bastia',   'Caen', 'Guingamp', 'Paris FC', 'St-Etienne',   'Sochaux',  'Grenoble Foot',    'Quevilly-Rouen',   'Amiens',   'Pau',  'Rodez',    'Stade Laval',  'Valencinnes',  'Annecy',   'Dijon',    'Nimes',    'Niort',    'Genk', 'Union Saint Gillose',  'Antwerp',  'Club Brugge',  'Gent', 'Strandard Liege',  'Westerlo', 'Cercle Brugge',    'Charleroi',    'Oud-Heverlee', 'Anderlecht',   'STVV', 'Mechelen', 'Eupen',    'Oostende', 'Zulte Waregem',    'RF Seraing',   'Feyenoord',    'PSV',  'Ajax', 'AZ Alkamaar',  'Twente',   'Sparta Rotterdam', 'Utrecht',  'Hereenveen',   'RKC Waalwijk', 'Vitesse',  'Go Ahead Eagles',  'NEC',  'Fortuna Sittard',  'FC Volendam',  'Excelsior',    'FC Emmen', 'Cambuur',  'Gronigen')
print(academy)

I have tried using file and importing the list from there, and using another list within this file itself, but it results in the following error:

  File "main.py", line 4, in <module>
    academy = random.choice(teams)
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]



Is the Windows RNG safe immediately after starting laptop?

Suppose that I startup my Windows 10 laptop, and the thirst thing I do is run a Python algorithm that generated a random number. The Python algorithm uses the CryptGenRandom algorithm from Windows. This algorithm gathers entropy from multiple sources, including timestamps of clicks of the user. However, when the laptop has just started up, there has not been a lot of data that the laptop could use for entropy. Therefore, is it possible that there is not enough entropy in the beginning, and that the first random number I generate is not completely random/safe?




vendredi 21 juillet 2023

Does it make sense to use Thread/Process-data as seed to generate random numbers?

Some additional questions: Is there some technical way to use thread-data (stored in RAM, i.ex. several sectors), use it as seed for lets say a couple rounds in a mersenne-twister ?

What about JavaScript?

Are there any Pros and Cons for that ? (let's say it reveals unwillingly data about the scheduler)

Are there already any 'cryptographically safe' random number generator - and what's their (algorithm) technique/usual approach on this ?

**I know the guidelines.




jeudi 20 juillet 2023

Generate ramdon string certain of times [closed]

Generate random string certain times (10), honestly i don't know how, specifically everytime the random string be generated needs to have a line in the middle every line, thanks.

import os
import random
import json
''.join([random.SystemRandom().choice("abdc0123456789ef") for i in range(64)]) 

for random.SystemRandom().choice in range(10)

Generate random string certain of times.




Discord.js Searching for a user in an array is always returning undefined

I've been trying to make a bot choose randomly from a list of players that reacted to a message and send the player it chooses, but it always sends undefined.

Here's the code for the randomizer.

const collector = giveawayMessage.createReactionCollector(filter, { time: timeRemaining });
const reactionUsers = [];
giveawayMessage.react('👍');
collector.on('collect', (reaction, user) => {
    if (reaction.emoji.name === '👍' && !user.bot) {
        for (let i = 0; i < reactionUsers.length; i++) {
            if (user === reactionUsers[i]) return;
        }
        reactionUsers.push(user);
    }
});
let chosenReaction;
for (let i = timeRemaining; i >= 0; i--) {
    delay(1000);
    timeRemaining--;
    numDays = Math.trunc(timeRemaining / 86400);
    numHours = Math.trunc((timeRemaining - (numDays * 86400)) / 3600);
    numMinutes = Math.trunc((timeRemaining - (numDays * 86400) - (numHours * 3600)) / 60);
    numSeconds = timeRemaining - (numDays * 86400) - (numHours * 3600) - (numMinutes * 60);
    timeRemainingFormatted = `${numDays}d ${numHours}h ${numMinutes}m ${numSeconds}s`;
    chosenReaction = Math.ceil(Math.random() * reactionUsers.length);
    embed = EmbedBuilder.from(embed).setFields({ name: 'Prize', value: `${interaction.options.getString('prize')}` }, { name: 'Time Remaining', value: `${timeRemainingFormatted}` });
    giveawayMessage.edit({ embeds: [embed] });
    if (timeRemaining <= 0 && i <= 0) {
        console.log('Done!');
        chosenReaction = Math.ceil(Math.random() * reactionUsers.length);
        embed = EmbedBuilder.from(embed).addFields({ name: 'Winner', value: `${reactionUsers[chosenReaction - 1]}` });
        giveawayMessage.edit({ embeds: [embed] });
    }

}

I tried making it choose on every iteration, expecting that the issue was that it stopped iterating before setting the variable, but it did not cause a noticable difference.




Randomly selecting a time on the half hour with a one hour buffer between two columns

I have a dataframe containing two different columns:

StartTime EndTime
8:00 2:00
8:00 12:00
8:00 4:00
2:00 6:00
12:00 6:00

I want to create another column "SelectedTime" that is a randomly selected time on half hour increments (1:00, 1:30, 2:00, 2:30) with an hour buffer between StartTime and EndTime. So for row one it would be a random time between 9:00 and 1:00. Is this possible?




Why are my divs overlapping with each other (Javascript)

As you very well know by now, I am trying to assign random positions, as in, randomised from a list, to divs. I am achieving so with this code:

var list = [100,210,320,430];
var square1 = document.getElementById("square1")
var square2 = document.getElementById("square2")
var square3 = document.getElementById("square3")
var square4 = document.getElementById("square4")
var squares = [square1,square2,square3,square4]
for(let looprun = 0; looprun<4; looprun++){    
    r=Math.floor(Math.random()*list.length)                       
    console.log(looprun)
    squares[looprun].style.left = (list[r])+"px";
    list.splice(r)
    if(looprun === 3){
    console.log("End of Loop Reached")
}   
    
}

Everything works fine apart from one thing: Because its random, its random. This means that it sometimes or usually chooses the same thing from the list twice or more, resulting in two or more divs having the same position, meaning they overlap each other.

There should be four divs here, but the fourth one has overlapped with the third one, for reasons I have already explained.

I have tried using list.splice to remove ones that have already been chosen, but that didn't work - some divs were resultantly not given a position. I am not sure how to resolve this so that it doesnt choose the same thing, e.g. 100 from the list twice. Help would be appreciated




mercredi 19 juillet 2023

How to save the order of records after rand()?

I have randomize the order of records in a table using

SELECT * FROM TableA ORDER BY rand();

How do I seva the result table of this query?

When execute the query, I indeed got a shuffle order of the table. But when I visit the page again, it shuffles again and the order change. How do I save the result of just one shuffle?




Generate secure random number in range Swift

I need to generate a secure random number in range (e.g. between 0 and 56, or any other range). But I can't find a way to do that, I looked through this thread. Most of the answers there are generating pseudo random numbers; but those that generate secure random numbers, don't allow to specify a range. For example this answer only allows generating numbers between 0 and 128, but I need to specify a different range.

I have no idea how to do this properly with SecRandomCopyBytes. In particular, I need to do this on iOS.




create a numpy array with zeros and ones at random positions BUT at least one or more '1's on a given sub axis

I am looking to make a numpy array randomly initialized with zeros and ones, I found the following question here that descripbes the basic random array and how to control the dimensions. However, I need my array to have at least a single '1' on each sub array of the nested axis. See example:

import numpy as np    
size = (3, 5, 5)
proba_0 = 0.7
n_positions = np.random.choice([0,1], size=size, p=[proba_0, 1-proba_0])
print(n_positions)

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

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

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

This issue here is that at the following position in this array n_positions[0][1] the data is populted ONLY with zeros. I need there to be at least one '1' in each row on axis 2. I can increase the probability of 1s occuring but this doesn't eliminate the risk.

I could make this with a loop or a comprehension using a method getting numpy to generate a random numer of ones between 1-5 and then filling out with zeros but its very slow. I am hoping there is a more numpy friendly method built in to achieve this?




mardi 18 juillet 2023

Random Number within Image Generation

I am making a website that allows input of text to convert to images, I have done the part where it converts the input into letter.png (Ie A -> A.png), however I would like it to accommodate both the new file system and for the letters to randomise through a range of colors.

The current file system is A1.png for A Red for example, B1.png for B red, and A2.png for A pink for example.

I have tried element.src = "FONT/" + character + randomNumber + ".png"; but it is not working.

Here is the JS I have so far:

for (var i = 0, len = userInput.length; i < len; ++i) {
        function getRandomNumber(min, max) {
          return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        var minNumber = 1;
        var maxNumber = 2;
        var randomNumber = getRandomNumber(minNumber, maxNumber);
        var image = document.createElement('img');
        var character = userInput[i].toUpperCase();
        var element;

 

        if (character === "\n") {
          element = document.createElement('br');
        } else if (character === ' ') {
          var image = document.createElement('img');
          image.src = 'FONT/SPACE.png';
          element = image;
        } else {
          var image = document.createElement('img');
          element.src = "FONT/" + character + randomNumber + ".png";
          element = image;
        } image.classList.add("bobbing-photo");
        imageOutput.appendChild(image);

 

        var span = document.createElement('span');
        ///span.textContent = userInput[i];
        span.classList.add("bobbing-photo");
        imageOutput.appendChild(span);
      }

Do you have any idea why and how I can resolve this? Thanks :)




SvelteKit: How To Route To URL Based On User Selection?

I'm fairly new to SvelteKit and I ran into a wall.

Brief Overview I'm building a web app where there is a main select element on the home page with different categories pulled in from Supabase. This part is already working and I have it populating from the table. It currently returns an array with an id and a name value.

The plan is for the user to select a category, hit submit, and then it takes them to a page where they'll see a random quote related to the category they select. Those quotes (I'm assuming) will be loaded in from another table in Supabase, based on the category ID selected by the user.

For the folder structure/file setup, I have a "category" folder inside of "routes" and inside of the category folder, I have a folder called "[num]" with the hopes of dynamically pulling in that category id from the user selection and displaying relevant quotes.

The Problem I'm having trouble connecting that category id from the user form submission to the +page.svelte file in the [num] folder to then generate a random related quote.

The Code /routes/+page.svelte form code:

<script>
    export let categories;
</script>
<form>
    <label for="selection">Select a category below:</label>
    <select name="category" id="category">
        <option value="" disabled selected>Select...</option>
        {#each categories as category (category.id)}
            <option value="{category.id}">{category.name}</option>
        {/each}
    </select>
    <button >Get Help</button>
</form>

Array from Supabase that's loaded into the dropdown:

{id: 1, name: 'Category1'}
{id: 2, name: 'Category2'}
{id: 3, name: 'Category3'}

The dropdown only shows the Category name on the frontend, but wanted to share the array here, if it's relevant.

Am I approaching this problem the wrong way? Does anyone have any tips on what I need to include in the +page.svelte and +page.server.js files inside of the [num] folder to get the appropriate data based on the user selection?

I tried reading the SvelteKit documentation on routing, but can't figure out how to apply it to my current code. I also tried experimenting with a several different things in the code, all of which broke the application. Any guidance would be greatly appreciated. I'm just trying to learn.




How can I track down desired direction in 2D space?

So let's say we have a bullet that have a wide and random spray pattern in a 2D space. When we shot it flies until one second is passed, then returns to start position. Here is the code for this

var velocity = Vector2()
var shot

func _physics_process(delta):
    if Input. is_action_pressed("ui_right") and not shot:
            velocity.x = 1000
            velocity.y = rand_range(-250,250)
            shot = true
            $Timer.start()
    
    velocity = move_and_slide(velocity * direction)

func _on_Timer_timeout():
    shot = false
    position = Vector2(500, 250)
    velocity = Vector2(0,0)

Here is the problem: when bullet flies to a random point it needs to face this point.

I want it to change directions according to the place it moves to so I need help. How can I do this?




Sampling the rows randomly by the specific rules in R

I have dat1 and dat2 like this:

dat1<-data.frame(company=c("a","b","c"),
                 random=c(2,1,1),
                 prior=c(1,3,1))

dat2<-data.frame(company=c("a","a",'a',"b","b","a","a","c","c","c",
                           "b","b","b"),
                 peter=c(5,0,1,1,1,0,100,7,8,7,0,0,1),
                 turner=c(5,1,2,1,2,0,200,7,9,6,0,0,0),
                 austin=c(7,5,3,1,0,0,300,77,10,5,0,1,1),
                 label=c("random","random","prior","random","random","random","prior",
                         "random","random","prior","prior","prior","prior"))

dat2 is the original data and dat1 gives the guidline how to pick sample rows from dat2. For example, if you look at the dat1 , for company==a, random=2 and prior=1. It means that you have to find company==a in dat2 and pick 2 rows randomly form company==a with label==random. Also, you have to find company==a in dat2 and pick 1 row from company==a with label==prior . So the possible extracted sampled rows data should look like this:

data<-data.frame(company=c("a","a","a","b","b","b","b","c","c"),
                 peter=c(5,0,100,1,0,0,1,7,7),
                 turner=c(5,1,200,1,0,0,0,7,6),
                 austin=c(7,5,300,1,0,1,1,77,5),
                 label=c("random","random","prior","random","prior","prior","prior","random","prior"))

So my question is how to get data ?




Does CryptGenRandom use the RNG in my processor?

On Windows, CryptGenRandom is the standard random number generator to use. It is called by many packages like Python’s Random and Secrets modules, which both use os.urandom, which in turns calls CryptGenRandom.

For the algorithm of CryptGenRandom, I found out the following:

In Windows Vista with Service Pack 1 (SP1) and later, an implementation of the AES counter-mode based PRNG specified in NIST Special Publication 800-90 is used. In Windows Vista, Windows Storage Server 2003, and Windows XP, the PRNG specified in Federal Information Processing Standard (FIPS) 186-2 is used.

However, the NIST publication does not specify which entropy source is used.

In the case of my laptop, I have an Ideapad Gaming laptop by Lenovo, with an Intel(R) Core(TM) i5-10300H processor. On this laptop I have Windows 10 installed. The processor contains a RNG called Secure Key Technology. Is this used as entropy source by CryptGenRandom?




lundi 17 juillet 2023

Can't reproduce normally distributed random numbers in parallel

I want to generate a reproducible sequence of random numbers in parallel with OpenMP. I wrote a small code that creates for each thread its own RNG with different seed. But when I start generating random numbers in parallel, something strange happens. With uniform distribution I get reproducible results (rand() here to generate same sequence of seeds whenever i launch the program), but with normal distribution i get different results!

My question: Why this might be happening? And how do I resolve this issue?

#include <iostream>
#include <random>
#include <omp.h>

int main() {
    std::normal_distribution<> normal(0,1);
    std::uniform_real_distribution<> uniform(0,1);
    std::mt19937 *rng = new std::mt19937[omp_get_max_threads()];
    for(int i = 0; i < omp_get_max_threads(); ++i) {
        rng[i].seed(rand());
    }

    int N = 100;
    double* arr = new double[N];
#pragma omp parallel for
    for(int i = 0; i < N; ++i) {
        arr[i] = normal(rng[omp_get_thread_num()]);
    }
    for(int i = 0; i < N; ++i) {
        std::cout << arr[i] << std::endl;
    }

    delete[] arr;
    delete[] rng;
    return 0;
}



How do I assign a percent chance to a value in python? [duplicate]

I am writing a program for a rock paper scissors game. Currently I am using the random command for the computer to choose between the three options. I want to add a fourth option, but instead of it being an even chance between the four I'd like to be a 1% chance to get the fourth option. Is there a way to assign a specific % chance to these options?

Here is my code currently:

import random
user_action = input("Choose: Rock, Paper, Scissors")
possible_actions = ["Rock", "Paper", "Scissors"]
computer_action = random.choice(possible_actions)
print(f"\n You Chose {user_action}, Computer Chose {computer_action}.\n")

if user_action == computer_action:
    print(f"Both player chose {user_action}. You Tied!")
elif user_action == "Rock":
    if computer_action == "Scissors":
        print("Rock smashes scissors! You win!")
    else:
        print("Paper covers rock, you lose!")
elif user_action == "Paper":
    if computer_action == "Rock":
        print("Paper covers rock, You Win!")
    else:
        print("Scissors cut the paper into shreds! You lose!")
elif user_action == "Scissors":
    if computer_action == "Paper":
        print("Scissors cut the paper into shreds! You win!")
    else:
        print("Rock smashes scissors! You lose!")



My application on Windows Forms goes into break when I try to call these functions

I have files on my computer containing all cards within a deck. What I want to do is generate all 52 numbers and give 7 of them to the user in the form of buttons so they can play these cards, another 7 cards to the computer, and the remaining cards stored in a queue for either of them to press to get more if needed. But the error I am facing is generating the 7 random numbers that need to be stored for the user to get.

This is the code I am referring to:

I believe this part of the code calls the SetButtonImage to begin to compile on load.

public FmClassic()
        {
            InitializeComponent();

            SetButtonImage();
        }

This is SetButtonImage gathering the images from within my computer as well as calling another function to generate the random numbers.

private void SetButtonImage()
        {
            button1.Image = Image.FromFile($"C:\\filepath\\{ShuffleOneTime()[0]}.jpg");
            button2.Image = Image.FromFile($"C:\\filepath\\{ShuffleOneTime()[1]}.jpg");
            button3.Image = Image.FromFile($"C:\\filepath\\{ShuffleOneTime()[2]}.jpg");
            button4.Image = Image.FromFile($"C:\\filepath\\{ShuffleOneTime()[3]}.jpg");
            button5.Image = Image.FromFile($"C:\\filepath\\{ShuffleOneTime()[4]}.jpg");
            button6.Image = Image.FromFile($"C:\\filepath\\{ShuffleOneTime()[5]}.jpg");
            button7.Image = Image.FromFile($"C:\\filepath\\{ShuffleOneTime()[6]}.jpg");

        }

This is then called to ensure they are random and not called twice with the hash table as well as converting to a string which I think is better for when searching for files?

public string ShuffleOneTime()
        {
            Random random = new Random();
            HashSet<int> generatednumbers = new HashSet<int>();
            int randomNumber = GenerateRandomNumber(random, generatednumbers);
            int numberOfUniqueNumbers = 54;
            for (int i = 0; i < numberOfUniqueNumbers; i++)
            {
                randomNumber = GenerateRandomNumber(random, generatednumbers);
                if (i == 7)
                {
                    List<int> numbers = new List<int>();
                    numbers.Add(randomNumber);
                }
            }
            string newrandomNumber = randomNumber.ToString();

            return newrandomNumber;
        }

This helps generate the numbers and return it back to the other function.

static int GenerateRandomNumber(Random random, HashSet<int> generatednumbers)
        {
            int randomNumber;
            do
            {
                randomNumber = random.Next(1, 54);
            }
            while (generatednumbers.Contains(randomNumber));

            generatednumbers.Add(randomNumber);

            return randomNumber;
        }

I have tried making it a string rather than an integer to help find it but it won't work. The filenames for the cards are all 1.jpg, 2.jpg etc so I don't know why there is an error. Everything compiles but then my screen freezes for 60 seconds and them inputs this error:

Managed Debugging Assistant 'ContextSwitchDeadlock' : 'The CLR has been unable to transition from COM context 0xa73c68 to COM context 0xa73bb0 for 60 seconds.




samedi 15 juillet 2023

How to extract, clear and refill the entropy pool from a USB hardware RNG?

Is there a programming method to permit the extraction of entropy bits from the entropy pool using standard python programming calls, so that they are replenished from a USB hardware RNG?

with open("/dev/random",'rb') as dr:
    b = dr.read(num_bytes)

Any help on this would be appreciated.

Please respect that this is a question about how to get and refresh entropy bits, not a solicitation for opinions about the cryptographic sufficiency of a fixed 256 bit entropy pool.




vendredi 14 juillet 2023

Is there a way to get a similiar result to this website?

I'm trying to make a website inspired by this website, https://impomu.com. I don't need it to have everything, like the secret prompt section and the discord advertisement. I'm mostly trying to get these main things working:

  • have a global counter (the total amount of times the button was clicked by every user that visited the site) and a local counter ( the total amount of times the button was clicked by the current user)
  • The website remembers the current count and doesn't reset back to zero (also updates the total count in real-time)
  • when the button is clicked, a randomly picked audio plays, as well as a completely randomly generated (different scale, rotation, and position it appears on screen) animated image that pops up for a little bit

I'm mostly having a difficult time reading the website code for reference, especially about the javascript code, as I'm kinda new to it. I'm having a hard time understanding what each javascript code is responsible for and which javascript code I need for my website. Especially which javascript code triggers the animated image pop-up. I tried looking for answers to previously asked questions from this site, but the answers given aren't what I looking for.

I'm asking if anyone can read the website's code, explain how it works, and how to achieve a similar result.

Before looking through the website code, I thought to get the counter to work; I needed to apply an increment to the button. But now, looking through the website's code, it doesn't involve increment, but something else I can't figure out.

Also, I couldn't understand how they achieved both audio and image working, especially the image part.




Excel randarray - create random number, duplicate number has same random number, no other duplication

In excel, I need to create random numbers that repeat when the number is in the list more than once.

So, 1 on the list would have the same random number, but this number would not repeat anywhere else on the list.

Sample date enter image description here

How it should look enter image description here

Thanks for your help

I have a data set of over 75,000 records some repeat up to 8 times and some are only on the list once.

How it should look enter image description here




How do I get the seed from a Random with a bound in Java?

int[] pos = (random.nextInt(16) - random.nextInt(16), random.nextInt(8) - random.nextInt(8), random.nextInt(16) - random.nextInt(16));

Hello, Can I calculate the seed from the following code with the 3 numbers that come out of the calculation?

I can only find examples to find out the java.until.random seed without a bound in the numbers.




mercredi 12 juillet 2023

Why does the c function srand() behave differently on Windows vs. Linux, where consecutive seeds produce the first consecutive random number?

Here we have a piece of c code that goes into a dead loop, reading the current timestamp and resetting the random seed each time, after which it prints a random number and sleeps for one second. The seeds are consecutive, and Windows generates the first random number consecutively for consecutive seeds, which is not the case with Linux.

Many languages written in c that don't have their own implementation of a random number generator also have this problem, e.g. lua 5.1

#include<time.h>
#include<stdlib.h>
#include<stdio.h>
#ifdef __linux__
#include <unistd.h>
#else
#include <windows.h>
#endif

void printRandoms(int lower, int upper,
                            int count)
{
    int i;
    for (i = 0; i < count; i++) {
        int num = (rand() %
        (upper - lower + 1)) + lower;
        printf("%d\n", num);
    }
}

int main(){
    while(1){
        srand(time(NULL));
        printRandoms(1,10000,1);
        #ifdef __linux__
        sleep(1);
        #else
        Sleep(1000);
        #endif
    }
    return 0;
}

The output:

On Windows:
I tried both gcc and clang.
1. gcc.exe (MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders) 13.1.0
2. (built by Brecht Sanders) clang version 16.0.5
3. gcc.exe (MinGW-W64 x86_64-msvcrt-posix-seh, built by Brecht Sanders) 9.5.0
5237
5238
5239
5240
5241
5242
5243
5245
5246
5247
5248

On Linux:
gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
5142
3660
7270
896
9500
3041
6659
5194
8809
7361
5960

I know that's usually the wrong way to use srand(), but was just curious what led to the difference.




Generate Random ID that don't already exist

I have a table containing IDs and they are all in 3-letter words. How do I use SELECT statement that returns a randomly generated 3 letter ID that does not yet exist in the current table and ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 are the only characters that can be used?

I would like to provide something I have in mind but I totally have no idea how to do this. Thank you so much.




How to randomly sample 2 indices of True values for each row in a boolean tensor in PyTorch, in the fastest way?

I'm given a PyTorch boolean tensor of size NxK (K>=2), which is guaranteed to have at least 2 True values in each row. For each row, I want to get the indices of 2 random cells with True values.

For example, let's say I have the following tensor:

tensor([[False,  True, False, False,  True],
        [ True,  True,  True, False,  True],
        [ True,  True, False,  True, False],
        [False,  True, False, False,  True],
        [False,  True, False, False,  True]])

So a possible output would be:

tensor([[1, 4],
        [4, 2],
        [0, 3],
        [4, 1],
        [4, 1]])

Because on the first row, we have True value on column 1 and 4, and on the second row we have True value on column 4 and 2, and so on.

Another possible output would be:

tensor([[4, 1],
        [1, 4],
        [0, 1],
        [1, 4],
        [1, 4]])

Because now a different random True values was selected for each row.

I've currently implemented a pytorch-numpy-pytorch solution for that, using np.random.choice:

available_trues = [t.nonzero(as_tuple=False).flatten() for t in input_tensor]
only_2_trues = [np.random.choice(t.cpu(), size=(2,), replace=False) for t in available_trues]
only_2_trues = torch.from_numpy(np.stack(only_2_trues)).cuda()

But this solution is not vectorized (since it works using lists) and it requires moving the data back and forth between the CPU and the GPU. Since I'm working on large matrices and running this operation many times, this causes a major slowdown.

I wonder if it can be done without list comprehension or without moving the data (or even without both :] )




mardi 11 juillet 2023

Ubuntu 22.04, python3, ryzen 7950x. From where does os.urandom() get its random bits?

I am running a python 3.11 program on an Ubuntu 22.04 Ryzen 7950x/asus system.
I have discovered that the size of the entropy file is limited to 256 bits.

$cat /proc/sys/kernel/random/entropy_avail

256

I assumed that os.urandom(nbytes) would return nbytes * 8 bits of entropy from /dev/random. However this does not seem to be the case. I have written a loop to empty the 256 bytes of entropy bits and keep it empty for a while, during which time I monitor the entropy in /dev/random. However the entropy pool does not seem to ever empty or even change its size.

for i in range(1000000000):
  b = os.urandom(32)

So I am under the impression that on this system, the os.urandom() function retrieves random bytes by some other means. A few questions come to mind:

  • Is the os.urandom() function supposed to return all the bits specified from /dev/random?

  • If not, does it just use a fraction of the entropy bits in /dev/random to generate a random set of bits which it returns? If so, what is that fraction?

  • If not, where does os.urandom() get its random bits?

Can anyone shed some light on this?




How to get a random seed from /dev/urandom?

In python 3.11 and ubuntu 22.04 I am trying to get a random seed (as opposed to a random number from a seeded system). I have a system running a process that is looping. At various points in the loop I set all python and system RNG settings to specific seeds for repeatability. At a particular point I need a random seed, separate from the specific seeds used for the system.

The random seed I need is an integer with the upper range of (2^32 -1). Yes there is a function, but it returns a value from the seeded system.

I have a hardware RNG in a USB port that works with the rng5-tools package, but I cannot access it directly. I assume it is used to fill the entropy pool and that os.urandom() pulls bits from that pool.

I tried using os.urandom() to generate an integer, then take the last character of that integer. The distribution of the ten individual characters (0 thru 9) is uniform. I have run samples of 10^3 to 10^7 to verify this.

I do this 10 times, each time adding the single character to a string, then convert the string to an integer. Each time I add an integer to the string, I right-pad it with zeros and test if it is < 4294967296 (2^32 -1). If it fails, the character is discarded and a new character is obtained and tested until it passes the test. If it succeeds I keep it in the string and repeat the process for new characters until a total of ten-characters are obtained. I then convert the string to an integer.

However the distribution of the resulting integers is skewed as shown in the graph. Can anyone shed any light as to why? The code is:

def gen_seed(digits = 10): 

  ssc = ""
  for i in range(digits):
    found_digit = False
    while found_digit == False:
    
      rand=f"{int.from_bytes(os.urandom(1), sys.byteorder)}"
      digit = f"{rand[-1]}"

      ssc_test = int(f"{ssc}{digit}".ljust(10,"0"))

      if ssc_test < 4294967296:
        found_digit = True
        ssc = f"{ssc}{digit}"
  ss = int(ssc)
  return(ss)

Resulting ten-digit integer frequency




How to add a random variable between a to z to a turtles-own

Is it possible to assign a random letter between a and z to a turtles-own? I know how to assign a random number but not a random letter. My goal is to have each letter represent a breed and when two breeds produce offspring then the child will have letters from both parents.




lundi 10 juillet 2023

Python Global random seed vs Numpy Generator

I am currently using randomness in functions and unit-tests. Moreover sometimes the functions should support joblib parallelism. I am wondering what are the issues with using numpy.random.seed vs Generator?

For example say we have the Generator pattern:

# pseudocode
def do_something_with_seed(rng):
    rng = np.random.default_rng(rng)

# you can just call as is
do_something_with_seed(12345)

# I need to generate a seed sequence as I understand, when using parallelism
Parallel(do_something_with_seed(_rng) for _rng in rng.spawn(n_jobs))

Next, say we use the np.random.seed pattern

# pseudocode
def do_something_without_seed(seed):
    np.random.seed(seed)
    ...

# this requires you to always set the global seed before running this function
do_something_with_global_seed(12345)

# when using parallelism
random_seeds = np.random.randint(np.iinfo(np.int32).max, size=len(seeds))
Parallel(do_something_with_global_seed(seed) for seed in random_seeds)

As I can see it, the performance, functionality is the same as long as you remember to do things properly. Is there any differences or reasons that we for sure need/want to use the Generator pattern? What about for unit-testing?




Beginner in R - Step by step guide to random effects poisson regresion model

I am conducting a meta-analysis and wish to combine data from multiple studies reporting injury incidence. I know I need to complete a random effects poisson regression model, offset by exposure hours, with 3/4 covariates. But I don't know how to do this - so any help / step by step guides would be really helpful. Many thanks. Nicola

I haven't tried in R yet.




dimanche 9 juillet 2023

Using operator>> to seed mt19937

In a blog post entitled "C++ Seeding Surprises," Melissa E. O'Neill reports that, "When std::seed_seq tries to “fix” high-quality seed data, it actually makes it worse."

So, if you have a good source of entropy, why not bypass seed_seq entirely?

That's what function seed_randomly() does below. It's taken from my rand_replacement repository on GitHub. It uses operator>> to overwrite all 624 state variables in mt19937.

template <typename ResultType>
class rand_replacement
{
public:
    using urbg_type = std::mt19937;
    using seed_type = typename std::mt19937::result_type;
private:
    urbg_type eng_{ seed_type{1u} };  // By default, rand() uses seed 1u.

    // ...

    void seed_randomly()
    {
        std::random_device rd;
        std::stringstream ss;
        for (std::size_t i{ std::mt19937::state_size }; i--;)
            ss << rd() << ' ';
        ss >> eng_;
    }
};

Is this a novel and interesting idea, or is it really foolish?

Regarding std::string_stream: I understand that it is relatively slow, but that's okay. Seeding should be an infrequent operation.

Regarding std::random_device: I understand that random_device may be deterministic on some systems, may block on other systems, and also that it has a checkered history with mingGW, but for now, at least, I am satisfied with it. My question is not about random_device; it is strictly focused on the idea of bypassing seed_seq using operator>>, a technique that could be used with any entropy source.

Are there any downsides?




Calling random in secrets module

In the secrets module, they call a specific class of the Random module called Systemrandom. Here is the code from secrets:

from random import SystemRandom

_sysrand = SystemRandom()

randbits = _sysrand.getrandbits
choice = _sysrand.choice

def randbelow(exclusive_upper_bound):
    """Return a random int in the range [0, n)."""
    if exclusive_upper_bound <= 0:
        raise ValueError("Upper bound must be positive.")
    return _sysrand._randbelow(exclusive_upper_bound)

However, when I check the source code of random.py, I only see the randbelow function in the Random class. It does not appear in the Systemrandom class. The relevant code in random.py is:

class Random(_random.Random):
...
class SystemRandom(Random):

So how can the secrets module work when the randbelow is called?




vendredi 7 juillet 2023

How do I get a random number to link with my specific number?

Im trying code a simple dice roll game where the player is to roll a dice and they try to get it to land on a specific number to win. How do I get it to print “you won” when it lands on this number?

I tried save the secret number as a string in the variable total. I then tried to do an if statement where if int is equal to total, then it would print “you won”




Getting random items up to a certain price

I have a map of 73 items, each item has a price and I need to make a random list of 6 items, the sum of items must not be greater than N. I don't know what algorithm to use to implement this.

Can you tell me what algorithm can be done for this?

P.S. I'm want to write this functionality in Typescript

I can only think of an idiotic way, to randomize items until there is a list with the right sum or cheaper.




Different Random Generators for different processes

I have several delays that are all distributed. These distributions involve random number generation.

I want each processing station to have its own RNG. According to anylogic I can simply create an instance (for example: Random myRNG1 = newRandom(); ) and then use this in the distribution: triangular(5, 10, 25, myRNG1).

Unfortunately, I don't know where exactly I insert the code Random myRNG1 = newRandom();. If I do it in the field "onStartup" in the main agent and then use the generator with triangular(5, 10, 25, myRNG) in the delayblock, I get the following error message: myRNG1 cannot be resolved to a variable.

It seems that the own random generator is not publicly visible. How can I change this?

Thanks in advance!




jeudi 6 juillet 2023

Im getting a Index Error when i tried to make a dummy console game with basic oop

Now i will give you more details, the game has max 10 min 6 players,they should randomly choose another player and attack them. So here in for loop i am tring to randomly choose who is gonna atack and who is going to get hurt, but it gives error

import random

class Fighter:
    def __init__(self, name, health, power, stamina):
        self.name = name
        self.health = health
        self.power = power
        self.stamina = stamina
        self.fighter_stats = [self.name, self.health, self.power, self.stamina]

    @classmethod
    def Get_Hurt(cls):
        pass

    @classmethod
    def Attack(cls):
        pass

fighters_list = []
atackers_list = []
dummy_value = 0
fighter_num = random.randint(6, 10)
atackers_num = random.randint(1, 6)

for i in range(1, fighter_num + 1):
    fighter_health = random.randint(55, 100)
    fighter_power = random.randint(20, 35)
    fighter_stamina = random.randint(3, 7)
    fighter = Fighter(f"fighter{i}", fighter_health, fighter_power, fighter_stamina)
    fighters_list.append(fighter.name)
    dummy_value += 1
    while True:    #this while loop is for making sure if the for loop is in its last loop  
        if dummy_value != fighter_num + 1:
            dummy_value += 1
            continue
        else:
            for i in range(atackers_num):
                rand_attacker = random.choice(fighters_list)
                atackers_list.append(rand_attacker)
                fighters_list.remove(rand_attacker)
            break

print(fighters_list)
print(atackers_list)

And that is the console output:

Traceback (most recent call last):
  File "C:\Users\azaz9\PycharmProjects\oyrenme\yoxlama.py", line 38, in <module>
    rand_attacker = random.choice(fighters_list)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
IndexError: list index out of range



lundi 3 juillet 2023

Error assigning random rank using random() and row_number in R

I am trying to replicate the analysis made here Three Strategies for Working with Big Data in R, chunk-by-chunk. When i get to the part of sampling the data, i type

df_mod <- df %>% group_by(is_delayed) %>% mutate(x = random() %>% row_number()) %>% ungroup()

and as result i get the error :

Error in mutate(): i In argument: x = random() %>% row_number(). i In group 1: is_delayed = FALSE. Caused by error in random(): ! could not find function "random"

Is the random function part of an external package? I did load the library suggested by the article author with no success.

I would be glad to receive any insights of yo all.

Thank you!

As described above, the code returns an error that i have not yet experienced.




dimanche 2 juillet 2023

Simple test for different PRNG algorithms

Many papers on PRNG tests for quality are complicated and "theoretical". I don't see much comparison on concrete examples like computing PI and such (i.e. Known results)using the least amount of iterations vs accuracy. Does anybody know of any tests of this kind. Since for now I am using JavaScript I would like a comparison between Math.random() vs MT for example, others would be great.

I have tried to search for any tests for real world examples but all the papers were very general.




torch randint() function is not working properly

I am trying to use below code to choose random values from defined integer constrained.

block_size = 4 batch_size = 8

def get_batch(split):
    data = [list of 2 million numbers numbers]
    ix = torch.randint(len(data) - block_size, (batch_size,))
    print(ix)
    x = torch.stack([data[i:i+block_size] for i in ix])
    y = torch.stack([data[i+1:i+block_size+1] for i in ix])
    return x,y

But, every time, the tensor generated is --> tensor([0, 0, 0, 0])

But when i run below code independently, i get random values

ix = torch.randint(len(data) - block_size, (batch_size,))

tensor([ 560685, 1199, 167746, 1028068])

Can anyone tell me what i am doing wrong? I have tried using for loop as well

for i in range(batch_size):
    print(i)
    ix = torch.randint(len(data) - block_size, (batch_size,))
    print(ix)
    x = torch.stack([data[i:i+block_size] for i in ix])
    print(x)
    y = torch.stack([data[i+1 : i+block_size + 1 ] for i in ix])



samedi 1 juillet 2023

Name spacing random/unique IDs

I am building a web app that generates unique IDs for user-created resources, so URLs or just IDs can easily be shared. I would like to “namespace” the IDs in some way, while keeping the IDs a reasonable length and looking consistent.

There are currently three hierarchical types of resources: a file, a collection (group of related files), and a project (a group of related collections).

Currently my scheme uses a 12 character nanoID (excluding underscores and dashes) with a prefix, e.g., [fcp]-x17Y8rSk03al. Where f, c, p stand for file, collection or project.

I don’t quite like this scheme and would prefer all the IDs to look indistinguishable to the user, while still being able to figure out resource type from the ID on the backend.

Possible solutions I’ve considered:

  1. Different ID lengths for each of the 3 resources. This is easy to expand in the future if I add more resource types but it’s inconsistent.

  2. Add a numerical prefix like myapp-xxxx-(nanoID), where xxxx are just random numbers. For example, 0-4999 is a file, 5000-7999 is a collection, 8000-8999 is a project and the rest is reserved for future uses, or something like that. The second dash is optional or course.

  3. Add a random prefix like above but in base64 but I don’t want to use - or _, so base 62 I guess? This is the one I like most.

With approaches 2 and 3 I’m not sure how to split up the range into the three resource types and leave room for future additions.

All these solutions seem a bit hacky and I’m worried I’m reinventing the wheel. Is there some kind of standard/convention or a “cleaner” way to do this? Maybe generate the IDs with some scheme so that characters can be manipulated/combined in a specific way to tell me what type of resource it is? But that also sounds unnecessarily complicated.

(I’m using python and JS but ultimately my question is completely language agnostic.)




std::uniform_int_distribution changed in Visual Studio 2022 version 17.6

After upgrading to Visual Studio 2022 version 17.6, the tests of our project showed discrepancies. Performed investigation has found that the reason was in changed behavior of std::uniform_int_distribution from STL.

It can be demonstrated with the example (derived from cppreference):

#include <iostream>
#include <random>
 
int main()
{
    std::mt19937 gen(0); // mersenne_twister_engine seeded with 0
    std::uniform_int_distribution<> distrib(1, 6);
 
    // Use distrib to transform the random unsigned int
    // generated by gen into an int in [1, 6]
    for (int n = 0; n != 10; ++n)
        std::cout << distrib(gen) << ' ';
    std::cout << '\n';
}

In Visual Studio 2019 and early versions of Visual Studio 2022, it prints

3 4 6 1 2 4 2 2 2 4

And in Visual Studio 2022 version 17.6 it outputs

4 4 5 6 4 6 4 6 3 4

And the difference comes from std::uniform_int_distribution, while the behavior of std::mt19937 seems unchanged.

In Visual Studio 2022 version 17.6 Release Notes there is nothing related to this change.

My main question: is there a way to restore old behavior of std::uniform_int_distribution, e.g. by command-line switch or by some #define?

And a side question: what was the motivation of this change (e.g. the desire to make exactly the same result as in GCC, or not standard-compliance of the previous implementation)?




Random seed in research papers

To present results in research papers, a random seed is typically used for repeatability. However, it we know that the choice of the random seed can significantly impact the obtained results. This makes me wonder what researches do to report their results metrics.

Do they select the seed that produces the highest or lowest metrics, or report the average.