jeudi 30 juin 2022

Is there a cheap way to obfuscate a 64bit int?

I'm writing C and C# code (same example, same algorithm, two languages).

I was wondering is there a fast way to obfuscate an int? The fastest way I can think of is newInt = currentInt ^ harcodedNumber. But that's obvious and lame. You'll 100% know the numbers are sequential. The other solution I thought of is newInt = currentInt ^ randomInt ^ harcodedNumber then return both newInt and randomInt. I was wondering if someone could come up with something better?




Python/numpy - conditional sampling of variables, distribution of subsequent value is based on result of previous value

I am trying to generate a random sample of multiple variables which are loosely related to each other. Meaning that "allowed" values of some variables depend on the value which is set for another variable.

For simplicity let's imagine that I have just two variables - A and B and let's say that both of them have uniform or gaussian distribution (we don't really care which exact distribution they follow and can accept both). For discussion let's assume both have uniform distribution.

Let's say that variable A can take any value between 0 and 100. We can easily sample from this distribution, say, 1000 data points.

Now, we also want to generate values for variable B, which can take any value between, say, 50 and 150. The catch here is that there is a constraint in resulting sample - sum of values A and B must be between 60 and 160.

Final catch is that each time we run the sampling process precise boundaries of sampling are changing (for example in one case A can be between 0 and 100 as above, next day it needs to be between -10 and 75 etc). Basically from day to day precise boundaries of sampling are evolving.

Right now we do it in a very inefficient way - generate completely random grid of A and B values independently, than eliminate all of the A and B combinations which don't satisfy constraints which we specify and than use them in subsequent steps. For example such grid could look like:

enter image description here

However, as you guess it is super-inefficient. In reality we have a lot of variables (30+) and large set of constraints we apply. Completely random generation of grid leads to instances where after applying all constraints we end up with no points satisfying all constraints if we don't use large enough sample size - and to ensure we always have at least some points we need to generate grid with millions points. Beyond that each time we re-run the sampling procedure we get different resulting dataset - sometimes all points are getting eliminated, sometimes we get 10 points as result and sometimes - 1000.

So my question is - is there a way to do it more efficiently in a "statistically correct way", ideally in a way which will allow us to specify how many sample points satisfying all constraints we want to get in the end of the day. Any guidance or pointers to some code examples will be much appreciated.




DolphinDB random sample functions

Can I sample an array a = [1, 2, 3, 4] based on the specified probabilities p = [0.1, 0.1, 0.3, 0.5]? For example, in python I can use np.random.choice(a=[1, 2, 3, 4], size=100, p=[0.1, 0.1, 0.3, 0.5])




How to run one type of simulation for multiple times under one loop to get a series of different results?

Py newbie here (really though, I literally started yesterday) Im basically trying to do a coin flip simulation, and its based on a BIASED distribution! Following are the inputs needed for the sim

#prob_up (success) = 0.472835862
#prob_down(fail) =  0.527164138
#up_scale(rate of increase) =   0.091889211
#down_scale(rate of decrease) = -0.061319729
#value = 1

Below is what I did

```for i in range(30):
  toss_outcome = np.random.random()
  if toss_outcome <= prob_up:
    value += value*(up_scale)

  if toss_outcome > 1-prob_up:
    value += value*(down_scale)
print(value)```

So this one works for me, but I would like to ask you how I could repeat this simulation for 100 times under one loop so that I can get something like 1.1, 1.09, 2.1, 0.98, 1.7, 0.89...

This is what I tried

#value =1
#count = 0


```for i in range(10):
  count = 0
  sims = []
  for x in range(20):
    toss_outcome = np.random.random()

    if toss_outcome <= prob_up:
      value+= value*(up_scale)
    if toss_outcome > 1-prob_down:
      value+= value*(down_scale)

    if count == 20:
      break
    sims.append(value)
  print(sims) ```

This is what I got

1.0918892105282665, 1.192222048068041, 1.3017743908394064, 1.2219499374001699, 1.1470202978485873, 1.0766853235214044, 1.1756210878871576, 1.1035323208530166, ...1.5467124250543491, 1.4518684376272906, 1.362840257848346, 1.4880705732181698 #Series 1

1.6248082034015325, 1.7741105464719504, 1.9371321639771295, 1.8183477437909779, 1.7068471521124233, 1.602183746548087, 1.5039382726953088, 1.4117171847179661, 1.541438762310887... #Series 2

So what happened here is that the new series simply continued from the previous one, instead of starting a new series of simulation from value = 1...

Id sincerely appreciate your help! Have a wonderful day.




mercredi 29 juin 2022

Generate same random number based on string parameter

I'm trying to create a function that will generate the same random number on each execution if the string is the same.

function generateRandom(maxInt, stringParam) {
  //generate random based on stringParam
  //output int number from 0 to maxInt
}

The goal is to generate the same random number (on different pages) if the stringKey is the same.

generateRandom(100, 'abc') // 73
generateRandom(100, 'abc') // 73
generateRandom(100, 'abc') // 73

generateRandom(100, 'qwe') // 45
generateRandom(100, 'qwe') // 45
generateRandom(100, 'qwe') // 45



bytes how many combinations calculation

Given the following code snippet

SecureRandom generator = new SecureRandom();
byte[] randomBytes = new byte[6];
generator.nextBytes(randomBytes);

How many combinations are there? And how do you work it out?

My current thinking is that it works like the following

byte[6]. creates an array of 6 bytes. Each byte of 8 bits. So in total that has 256 combinations. 2^8

So if you expand that to 6 bytes then you can do 256^6. 281,474,976,710,656

Have I got this right and answered my own question or have I missed something?




How create a random answers in quiz, android studio(java)?

I am tring to do a quiz app, there is a random flag and random 4 answers, one of them should be a correct answer and random 3.

For now I have only been able to random answers, but sometimes I have the same answer several times. Fails to random 3 different answers that will not repeat themselves and add to that the correct answer.

package com.example.guesstheflag;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class startGame extends AppCompatActivity {

    Integer[] flags ={
            R.drawable.france,
            R.drawable.england,
            R.drawable.brazil,
            R.drawable.belgium,
            R.drawable.germany,
            R.drawable.israel,
            R.drawable.russia,
            R.drawable.spain,
            R.drawable.ukrain,
    };

    String []answers = {
            "france",
            "england",
            "brazil",
            "belgium",
            "germany",
            "israel",
            "russia",
            "spain",
            "ukrain",
    };

    ListView listView;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_game);

        listView = findViewById(R.id.myList);
        imageView = findViewById(R.id.imagernd);

        MyAdapter myAdapter = new MyAdapter();
        listView.setAdapter(myAdapter);

        //rnd image
        Random rndImg = new Random();
        int img = rndImg.nextInt(flags.length);
        imageView.setImageResource(flags[img]);
    }

    // functions for answers list
    class MyAdapter extends BaseAdapter{
        @Override
        public int getCount() {

            return 4;
        }

        @Override
        public Object getItem(int i) {
            return answers[i];
        }

        @Override
        public long getItemId(int i) {

            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            LayoutInflater layoutInflater = getLayoutInflater();
            View row = layoutInflater.inflate(R.layout.custom, null);

            TextView textView = row.findViewById(R.id.myText);

            Random rnd = new Random();
            int name = rnd.nextInt(answers.length);

            textView.setText(answers[name]);

            return row;
        }
    }
}



Am tryin to generate different values for each element of a column of a numpy array using a certain range for each column but it's not abiding by it

I need each column to generate random integers with specified range for col 1 (random.randint(1, 50) for col 2 random.randint(51, 100)...etc

import numpy
import random
import pandas
from random import randint
wsn = numpy.arange(1, 6)
taskn = 3

t1 = numpy.random.randint((random.randint(2, 50),random.randint(51, 100),
    random.randint(101, 150),random.randint(151, 200),random.randint(201, 250)),size=(5,5))
t2 = numpy.random.randint((random.randint(2, 50),random.randint(51, 100),
    random.randint(101, 150),random.randint(151, 200),random.randint(201, 250)),size=(5,5))
t3= numpy.random.randint((random.randint(2, 50),random.randint(51, 100),
    random.randint(101, 150),random.randint(151, 200),random.randint(201, 250)),size=(5,5))
print('\nGenerated Data:\t\n\nNumber   \t\t\t Task 1 \t\t\t Task 2 \t\t\t Task 3\n')
ni = len(t1)
for i in range(ni):
    print('\t {0}    \t   {1}   \t {2} \t {3}\n'.format(wsn[i], t1[i],t2[i],t3[i]))
print('\n\n')

It prints the following

   Generated Data:  

Number               Task 1              Task 2              Task 3

     1         [  1  13  16 121  18]     [  5  22  34  65 194]   [ 10  68  60 134 130]

     2         [  0   2 117 176  46]     [  1  15 111 116 180]   [22 41 70 24 85]

     3         [  0  12 121  19 193]     [  0   5  37 109 205]   [  5  53   5 106  15]

     4         [  0   5  97  99 235]     [  0  22 142  11 150]   [  6  79 129  64  87]

     5         [  2  46  71 101 186]     [  3  57 141  37  71]   [ 15  32   9 117  77]

soemtimes It even generates 0 when I didn't even specifiy 0 in the ranges




What's the point of sampling multiple rays per pixel

What is the purpose of multisampled pixels in raytracing? In my experience writing raytracers, there is never any noise, only slight aliasing at lower resolutions, but in most diagrams I see, in the single sampled pixels, there is a ton of noise and black spots. Is this issue noise on single pixels exclusive to global illumination/antialiasing? Or is there another benefit to using multiple samples per pixel?




mardi 28 juin 2022

How to get a Rquared and F-ratio for a mixed effects model in R?

Data fits a mixed effects model with nested random effects. How do I get the r-square and F-ratio for this model?

set.seed(111)
df <- data.frame(level = rep(c("A","B"), times = 8),
                 time = rep(c("1","2","3","4"), each = 4),
                 x1 =  rnorm(16,3,1),
                 x2 = rnorm(16,3,1))

mod <- lmer(x1 ~ x2 + I(x2^2) + (1|time/level), df)
summary(mod)

Linear mixed model fit by REML. t-tests use Satterthwaite's method ['lmerModLmerTest'] Formula: x1 ~ x2 + I(x2^2) + (1 | time/level)    Data: df

REML criterion at convergence: 47.9

Scaled residuals: 
     Min       1Q   Median       3Q      Max 
-1.72702 -0.41979  0.00653  0.43709  2.36393 

Random effects:  Groups     Name        Variance Std.Dev.  level:time (Intercept) 0.00     0.00      time       (Intercept) 0.00     0.00    Residual               1.02     1.01     Number of obs: 16, groups:  level:time, 8; time, 4

Fixed effects:
            Estimate Std. Error       df t value Pr(>|t|)     (Intercept)  3.58299    0.81911 13.00000   4.374 0.000753 *** x2      
-0.59777    0.54562 13.00000  -1.096 0.293147     I(x2^2)      0.07686    0.09356 13.00000   0.822 0.426136    
--- Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Correlation of Fixed Effects:
        (Intr) x2     x2      -0.868        I(x2^2)  0.660 -0.928 optimizer (nloptwrap) convergence code: 0 (OK) boundary (singular) fit: see ?isSingular



Run this python script after every random interval between 30 min to 60 min

import pyttsx3
import random

engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[1].id)
engine.setProperty('rate', 110)
words = ["word 1", "word 2", "word 3, etc"]
engine.say(random.choice(words))
engine.runAndWait()

I want to run this script at every random interval between 30 mins to 60 mins




lundi 27 juin 2022

Generate a randon order number but prevent regeneration in WooCommerce

I am trying to add a random string when the order number is created as the default sequential number can be very easily guessed.

I tried this snippet:

function generate_random_string( $length = 16 ) {
    return substr( str_shuffle( str_repeat( $x = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil( $length / strlen( $x ) ) ) ), 1, $length );
}
    
add_filter( 'woocommerce_order_number', 'ct_change_woocommerce_order_number', 1, 2);

function ct_change_woocommerce_order_number( $order_id, $order ) {
     $random_string1 = generate_random_string(5);
    return $random_string1 . $order->get_id();
}

The problem is that this change the order number every time the order number is requested somewhere.

This would work if I will use a constant prefix and suffix, but in the actual way a different order number is shown each time for the same order. Any advice?




Phone Number Generator ignoring user input

I'm quite new to Python.

#Amount of numbers wanting to be generated
numbers = str(int(input("How Many Numbers Do You Want To Generate: ")))
Number1 = int(numbers)
Number2 = int(numbers)
Number3 = int(numbers)

print("---------------------------------------------")

#generator values
gentype = "0123456789"

Telstra = "4001", "4002", "4003", "4004", "4005", "4006", "4007", "4008", "4009", "4601", "4609", "4800", "4901", "4909", "4910", "4914", "4920", "4929", "4070", "4079", "4080", "4089", "4090", "4099", "4170", "4179","4180", "4189", "4190", "4199", "4270", "4279", "4280", "4289", "4290", "4299", "4470", "4479", "4480", "4484", "4971", "4979", "4980", "4989", "4990", "4999"
Optus = "4010", "4019", "4020", "4029", "4030", "4039", "4110", "4119", "4120", "4129", "4130", "4139", "4810", "4819", "4340", "4349", "4350", "4359"
Vodafone = "test"

#generator code 
if carrier == "1": 
    for i in range(Number1):
     generatestarted1 = random.choice(Telstra)
     generatestarted2 = random.choice(gentype)
     generatestarted3 = random.choice(gentype)
     generatestarted4 = random.choice(gentype)
     generatestarted5 = random.choice(gentype)
     generatestarted6 = random.choice(gentype)
     generatestarted = ("+61"+generatestarted1+generatestarted2+generatestarted3+generatestarted4+generatestarted5+generatestarted6))
    print(generatestarted)
    savenumbers = open("TelstraPhoneNumbers.txt","a").write(generatestarted+"\n")
elif carrier == "2":
    for j in range(Number2):
     generatestarted1 = random.choice(Optus)
     generatestarted2 = random.choice(gentype)
     generatestarted3 = random.choice(gentype)
     generatestarted4 = random.choice(gentype)
     generatestarted5 = random.choice(gentype)
     generatestarted6 = random.choice(gentype)
     generatestarted = ("+61"+generatestarted1+generatestarted2+generatestarted3+generatestarted4+generatestarted5+generatestarted6)
    print(generatestarted)
    savenumbers = open("OptusPhoneNumbers.txt","a").write(generatestarted+"\n")

Output:

enter image description here




dimanche 26 juin 2022

How can I obtain random images with turtle?

I have a code. And I generated random fibers with turtle. But I would like to obtain 100 different randamized images. I will create a dataset. How can i change the code and obtain the 100 images in a file by turtle ?

from turtle import Screen, Turtle
from random import randint

width, height = 500,500
fiber_r = 35
fiber_num = 50
cursor_size = 20

screen = Screen()
screen.setup(width, height)

fiber = Turtle()
fiber.hideturtle()
fiber.color('black')
fiber.shape('circle')
fiber.shapesize(fiber_r / cursor_size)
fiber.speed('fastest') 
fiber.penup()

fibers = []

for _ in range(fiber_num):
    fiberr = fiber.clone()
    fiberr.setposition( \
        randint(fiber_r - width/2, width/2 - fiber_r), \
        randint(fiber_r - height/2, height/2 - fiber_r) \
    )

    while any(map((lambda a: lambda b: a.distance(b) < fiber_r)(fiberr), fibers)):
        fiberr.setposition( \
            randint(fiber_r - width/2, width/2 - fiber_r), \
            randint(fiber_r - height/2, height/2 - fiber_r) \
        )

    fiberr.showturtle()
    fibers.append(fiberr)

screen.exitonclick()



samedi 25 juin 2022

Unable to get a random string selection from my JavaScript array using the Math.Random function [duplicate]

I am trying to get a random input for my rock paper scissors game, but the console just returns 0 every time I call the function.

function computerPlay() {
    options = ["rock", "paper", "scissors"]
    let computerSelection = Math.floor(Math.random(options.length));
    console.log(computerSelection);
}



Get a seed to generate a specific set of pseudo-casual number

I was wondering if there is a way in R to find the specific seed that generates a specific set of numbers;

For example:

sample(1:300, 10)

I want to find the seed that gives me, as the output of the previous code:

58 235 243  42 281 137   2 219 284 184



Generating random student data

I'm trying to create a process that populates a student table. I want to be able to create a different combination of a student's first/last name and dob every time I run the query.

The code below appears to work fine as it generates 5 names. My first question is can this be modified to generate N NUMBER of rows sat for example 20. I tried using CONNECT by level <=20 but that gives me a syntax error.

Secondly, know the random_date function works


Select random_date(DATE '2001-01-01', DATE '2001-12-31') from dual 

17-NOV-2001 08:31:16

But I can't seem to incorporate into my SQL.

Any help would be greatly appreciated. Thanks in advance for your expertise and time


ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'DD-MON-YYYY  HH24:MI:SS.FF';

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

CREATE OR REPLACE FUNCTION random_date(
      p_from IN DATE,
      p_to   IN DATE
    ) RETURN DATE
   IS
   BEGIN
      RETURN p_from + DBMS_RANDOM.VALUE() * (p_to - p_from + 1 );
END random_date;
/

CREATE TABLE students (
   student_id  number(*,0),
  first_name VARCHAR(25) NOT NULL,
  last_name VARCHAR(25) NOT NULL,
   dob DATE,
  constraint teacher_pk primary key (student_id));

WITH  raw_names (first_name, last_name)  AS
(
  SELECT 'Faith', 'Andrews'  FROM dual UNION ALL
  SELECT 'Tom',   'Thornton' FROM dual UNION ALL
  SELECT 'Anna',  'Smith'    FROM dual UNION ALL
  SELECT 'Lisa',  'Jones'    FROM dual UNION ALL
  SELECT 'Andy',  'Beirs'    FROM dual
)
,  numbered_names  AS
(
  SELECT  first_name, last_name
  ,      ROW_NUMBER () OVER (ORDER BY dbms_random.value (0, 1)) AS first_num
  ,      ROW_NUMBER () OVER (ORDER BY dbms_random.value (0, 2)) AS last_num
  FROM    raw_names
)
SELECT   fn.first_num        AS student_id
,     fn.first_name
,     ln.last_name
FROM     numbered_names fn
JOIN     numbered_names ln ON ln.last_num = fn.first_num  
ORDER BY student_id
;




C++ generating distinct random numbers (infinite loop problem)

I am trying to generate 5 distinct numbers in the range 1 to 9 (inclusive). I am still learning c++ so i only know this "method" for generating random numbers and i am not familiar with the latest features of the language. This is what i tried :

#include <iostream>
#include <ctime>
#include <cstdlib>

void Generate(int arr[], const int size){
    std::srand(std::time(0));
    arr[0] = 1 + (std::rand() / ((1u + RAND_MAX) / 8));
    int random;
    int counter;
    bool flag;
    for(int i = 1; i < size; ++i){
        counter = 0;
        flag = true;
        while(flag){
        random = 1 + (std::rand() / ((1u + RAND_MAX) / 8));
        for(int j = 0; j < i; ++j){
            if(arr[j] == random){
                ++counter;
            }
        }
        if(!counter){
            arr[i] = random;
            flag = false;
        }
        else{
            std::cout << "false ";
        }
    }
    }
}

void Print(int const arr[], const int size){
    for(int i = 0; i < size; ++i){
        std::cout << arr[i] << ' ';
    }
}

int main() {

    constexpr int ksize = 5;
    int arr[ksize];
    Generate(arr, ksize);
    Print(arr, ksize);

    return 0;
}

This works fine sometimes, but on many occasions it gives an infinite loop. Why ?

By the way, i added:

else{
std::cout << "false ";
}

to the code just to make sure that i was getting an infinite loop.




Why does my code keep giving me the same result of else: statement?

I have tried many times to debug this but it keeps giving me the else statement output. I do not see where I went wrong. I am trying to get the game to work, I feel that the error lies in my if/elif/else statement.

import random
rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''
#Write your code below this line 👇
x = input("What do you choose? Type 0 for rock, 1 for Paper or 2 for Scissors\n")
options = [rock, paper, scissors]
print(options[int(x)])
print("Computer chose:")
y = random.randint(0, 2)
z = int(y)
print(options[z])

#For Rock
if x == 0 and z == 2:
  print("You win!")
elif x == 0 and z == 0:
  print("It is a draw!")
elif x == 0 and z == 1:
  print("You lose.")
#For Paper
elif x == 1 and z == 0:
  print("You win!")
elif x == 1 and z == 1:
  print("It is a draw!")
elif x == 1 and z == 2:
  print("You lose.")
#For Scissors
elif x == 2 and z == 1:
  print("You win!")
elif x == 2 and z == 2:
  print("It is a draw!")
else:
  print(z)



vendredi 24 juin 2022

Generate random numbers between two values with floating steps in python (numpy) [duplicate]

I want to generate 40 random numbers between two given values with a specific floating step; some thing like: random(start,stop,step); where: start=5,stop=7,step=0.1 Is there any function in numpy or other python's libraries to do that directly?




Repeating patterns in OpenSimplex noise?

I'm trying to generate a random field of stars using OpenSimplex noise, but I'm noticing repeating patterns appearing and now that I've noticed it, I can't stop noticing it. I think I've found a workaround but I still like to know why this is happening.

At the moment my code generates a 2D greyscale image using OpenSimplex noise, then sets every pixel below a threshold value to 0, so only a small, supposedly random set of "stars" are left. I'll post the code below but this is what I'm seeing (I can't embed images yet so please check the links):

My code as it stands is using this package for the noise implementation: https://github.com/ojrac/opensimplex-go

package main

import (
    "flag"
    "fmt"
    "image"
    "image/color"
    "image/png"
    "math/rand"
    "os"
    "time"

    "github.com/ojrac/opensimplex-go"
)

const (
    startupMessage = "starfieldtest"
)

var (
    flgSize          int
    flgSeed          int64
    flgCullThreshold float64
)

func init() {
    rand.Seed(time.Now().UnixNano())
    seed := rand.Int63()

    flag.IntVar(&flgSize, "size", 2048, "size of the starfield")
    flag.Int64Var(&flgSeed, "seed", seed, "random noise seed value")
    flag.Float64Var(&flgCullThreshold, "cull", 0.998, "normalised threshold to cull values below")
}

func main() {
    fmt.Println(startupMessage)
    flag.Parse()

    img := generate(flgSize, flgSeed, float32(flgCullThreshold))

    outName := fmt.Sprintf("generated_%s.png", time.Now().Format("20060102150405"))
    pngFile, err := os.OpenFile(outName, os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        panic(err)
    }
    defer pngFile.Close()

    if err = png.Encode(pngFile, img); err != nil {
        panic(err)
    }

    fmt.Printf("Done!\n")
}

func generate(size int, seed int64, threshold float32) *image.Gray {

    noise := opensimplex.NewNormalized32(seed)

    pix := image.NewGray(image.Rect(0, 0, size, size))
    for y := 0; y < size; y++ {
        for x := 0; x < size; x++ {
            v := noise.Eval2(float32(x), float32(y))

            if v < threshold {
                v = 0
            }

            pix.SetGray(x, y, color.Gray{Y: uint8(v * 255.0)})
        }
    }

    return pix
}

I think I can get around it by using the Eval3 function and changing depth after a certain number of pixels, but is this expected behaviour because it's only really pseudo-random, or is OpenSimplex noise not supposed to do this? I can't really find any statement by anyone knowledgeable one way or the other as to whether this is just a limitation of pseudo-random noise or a problem with the implementation.




Random selection not already in a list Python [closed]

I am trying to make random selection from all_items list for each type of item in types.

This needs to happen in such a way that total number of items in each list that gets added to selection for each type should be the as per the he value of type.

All items in selection should all be unique no matter which list they belong to.

My code below:

all_items = ['G1Item1', 'G1Item2', 'G1Item3', 'G1Item4',  'G1Item5', 'G1Item6', 'G2Item1', 'G2Item2', 'G2Item3', 'G2Item4', 'G2Item5', 'G2Item6',]
types = {'A': 1, 'B': 3, 'C': 5, 'D': 2}

check = list()
# selection = dict()

for i in types:
    
    while any(item in pick for item in selection) == True:
    
        pick = random.sample(all_items, types[i])
    
    check.extend(pick)
#     selection.update({i: pick})

But when I access the value of selection, I get:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [13], in <cell line: 4>()
      6 while any(item in pick for item in selection) == True:
      8     pick = random.sample(all_items, types[i])
---> 10 check.extend(pick)

NameError: name 'pick' is not defined

I am not sure how to ensure that any of my random selection is not already park of check.

Hope this makes sense.

Any help would be appreciated.




C random number generator generating numbers not in the range

enter image description hereI was demonstrating a rock paper scissors game to a friend of mine when i came across this problem. The random number generation wouldn't work for me and I am looking for a solution to the problem.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
void main()
{   int draw = 0;
    int user_win = 0, comp_win = 0;
    
    srand(time(0));
    int random,upper = 2,lower = 0;
    random = (rand()%(upper - lower + 1)) + lower;
    
    char comp_option,options[4] = {'r','p','s','\0'}, user_option[12];
    comp_option = options[random];
    for(int i=0; i<=5; i++){
    
    printf("%d\n%c",random,comp_option);
    printf("%s", "Enter your option ");
    scanf("%s", &user_option[12]);
    printf("computer choses: %s\n",comp_option == 'r' ? "Rock" : comp_option == 'p' ? "Paper" : "Scissor");
    
    if(strcmp(user_option,"rock") && comp_option=='s'){
        user_win+=1;
        }
    else if (strcmp(user_option,"scissor") && comp_option=='p'){
        user_win+=1;    
        }
    else if (strcmp(user_option,"paper") && comp_option=='r'){
        user_win+=1;
        }
    else if (strcmp(user_option,"scissor") && comp_option=='r'){
        comp_win+=1;
        }
    else if (strcmp(user_option,"rock") && comp_option=='p'){
        comp_win+=1;    
        }
    else if (strcmp(user_option,"paper") && comp_option=='s'){
        comp_win+=1;
        }
    else{
        draw+=1;
        }
}
    // decision 
    if(draw>comp_win && draw>user_win){
            printf("Match draw\n");
        }
    else if(comp_win>user_win){
        printf("Computer won the match\n");
        
        }
    else{ 
        printf("user won the match\n");
        }
    printf("User Score: %d\n", user_win);
    printf("Computer score: %d\n", comp_win);
    printf("Draws: %d\n",draw);    
    }

other improvements and ideas to the code are appreciated.




fillna the missing values from another column

enter image description here

LotFrontage column have relationship with LotArea the values of LotFrontage is between 0.005% - 0.01% of the LotArea.

I am trying to get the random values between 0.005% - 0.01% of LotArea where LotFrontage is missing.

Example: In the pic at 1019 index values is missing for LotFrontage. I want to fill it with LotArea value 8978 * 0.005 to 8978 * 0.01

Code(to solve this issue):

np.where(df_train[df_train["LotFrontage"].isnull()], np.random.rand(df_train['LotArea']*0.005, df_train["LotArea"]*0.01),df_train["LotFrontage"])
Error:
TypeError                                 Traceback (most recent call last)
<ipython-input-46-49a940deebcd> in <module>()
----> 1 np.random.rand(df_train['LotArea'] *0.005,df_train["LotArea"] * 0.01)
mtrand.pyx in numpy.random.mtrand.RandomState.rand()
mtrand.pyx in numpy.random.mtrand.RandomState.random_sample()
_common.pyx in numpy.random._common.double_fill()
TypeError: 'Series' object cannot be interpreted as an integer



jeudi 23 juin 2022

Choose random number from pre-determined set Discord.py

I have a function that pings a random user with a yes or no question every few hours. However, I want it so when the user responds yes/no, the bot will only answer if their message id = that of the ping ID.

The issue I'm running into is finding a way to get python to select from a set list of integers. I could just do this for the ping:

USER_ID = ["11111111111", "222222222222", "3333333333333"]

But the issue is, message.author.id ONLY works for integers, meaning they CAN'T be in quotes.

The code for the randomized ping is:

newvalue = False
@bot.command(pass_context=True)
async def randum(ctx):
    while True:
      global USER_ID_FOR_BOT
      USER_ID_FOR_BOT = random.choice(USER_ID)
      RESPONSES = ["<@" + USER_ID_FOR_BOT + ">" + " Do you want to hear a joke?", "(Other none yes/no questions)"]
      possibleresponse = random.choice(RESPONSES)
      if possibleresponse == "<@" + USER_ID_FOR_BOT + ">" + " Do you want to hear a joke?":
        global newvalue
        newvalue = True
        print ('Value is TRUE')
        await ctx.channel.send(possibleresponse)
        await asyncio.sleep(random.randint(minTime, maxTime))

The terminal tells me the value is True, so I can say this code isn't the issue. And then in the on_message....

if newvalue == True:
        if 'no' in message.content:
          if message.channel.id == 988993107368476692:
            if message.author.id == USER_ID_FOR_BOT:
                await message.channel.send(random.choice(denyresponse))
                newvalue = False
                return
        if 'yes' in message.content:
          if message.channel.id == 988993107368476692:
            if message.author.id == USER_ID_FOR_BOT:
                await message.channel.send(random.choice(jokeresponse))
                newvalue = False
                return
    await bot.process_commands(message)

I need USER_ID_FOR_BOT to be an int, but I have no clue how to make a list of per-determined ints that the program can choose from. It sounds simple, but I genuinely am having difficulty finding anything on google.




how to pick random number in an array but have more chance to pick the number if the number is bigger

example: I have an array of numbers like [1.0231, 1.1233, 2.1322, 2.321] I want to have like 35% pick 2.1322 and 40% to pick 2.321 and the rest for the other numbers.

I want a system that choose randomly but more odds to pick a number the bigger it is.




How do you make a list containing random letters?

I have this task where I have to create a list that contains random letters. I know you would have to use a 'for' loop to create it but I do not know how to make it contain random letters.




Character and Skin Change buttons in AS3

I have the code for both character random and skin buttons:

var HaurkaWS: Haurka_Wetsuit = new Haurka_Wetsuit();
var MinamiWS: Minami_Wetsuit = new Minami_Wetsuit();
var MinamiSWS: Minami_ShortWetsuit = new Minami_ShortWetsuit();
var KiraraWS: Kirara_Wetsuit = new Kirara_Wetsuit();
var TowaWS: Towa_Wetsuit = new Towa_Wetsuit();
var HaurkaSS: Haurka_Swimsuit = new Haurka_Swimsuit();
var MinamiSS: Minami_Swimsuit = new Minami_Swimsuit();
var KiraraSS: Kirara_Swimsuit = new Kirara_Swimsuit();
var KiraraBS: Kirara_Bikini = new Kirara_Bikini();
var TowaSS: Towa_Swimsuit = new Towa_Swimsuit();

For Character Button:

 var characterRandom: String;
 var characterRandomArray: Array = [HaurkaWS,MinamiWS,KiraraWS,TowaWS];
 var HaurkaSkin: Array = [HaurkaWS,HaurkaSS];
 var MinamiSkin: Array = [MinamiWS,MinamiSS,MinamiSWS];
 var KiraraSkin: Array = [KiraraWS,KiraraSS,KiraraBS];
 var TowaSkin: Array = [TowaWS,TowaSS];

character_btn.addEventListener(MouseEvent.CLICK, on_pressCharacter);
function on_pressCharacter(e: MouseEvent): void {
    if(contains(DisplayObject(character)))
        {
            character = characterRandomArray.splice(int(Math.random() * characterRandomArray.length));
        }
}

For Skin button:

skin_btn.addEventListener(MouseEvent.CLICK, on_pressSkin);
function on_pressSkin(e: MouseEvent): void {
    if(character == contains(DisplayObject(characterRandomArray[0])) && contains(DisplayObject(HaurkaSkin[0]))){
        var randomHaurkaSkin = HaurkaSkin.splice(int(Math.random() * HaurkaSkin[0].length));
    }
    else if(character == contains(DisplayObject(characterRandomArray[1])) && contains(DisplayObject(MinamiSkin[0])))
    {
        var randomMinamiSkin = MinamiSkin.splice(int(Math.random() * MinamiSkin[0].length));
    }
    else if(character == contains(DisplayObject(characterRandomArray[2])) && contains(DisplayObject(KiraraSkin[0])))
    {
        var randomKiaraSkin = KiraraSkin.splice(int(Math.random() * KiraraSkin[0].length));
    }
    else if(character == contains(DisplayObject(characterRandomArray[3])) && contains(DisplayObject(TowaSkin[0])))
    {
        var randomTowaSkin = TowaSkin.splice(int(Math.random() * TowaSkin[0].length));
    }
}

And then I have 2 errors:

TypeError: Error #1034: Type Coercion failed: cannot convert []@26f82b72b21 to Haurka_Wetsuit.
    at WetWorldChallenge_fla::MainTimeline/on_pressCharacter()[WetWorldChallenge_fla.MainTimeline::frame491:148]

TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/contains()
    at WetWorldChallenge_fla::MainTimeline/on_pressSkin()[WetWorldChallenge_fla.MainTimeline::frame491:157]

I was unable to change character or the skin, any ideas how to fix these?




Random surface shape over a random point distribution in python

I have this random point distribution:


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from random import shuffle

x0 = list(range(-100,100))
y0 = list(range(-100,100))
z0 = list(range(-100,100)) 


shuffle(x0)
shuffle(y0)
shuffle(z0)


figure = plt.figure()
axis = Axes3D(figure)

axis.scatter(x0,y0,z0)

I need to "cut" the distribution in randomly generated surfaces over this distrution, then save the points on the surface on an array or list and visualize the surface. I have tried to cut it with planes (as you can represent isolines in a 3D surface), but I need a rough surface

Thank you!




mercredi 22 juin 2022

What will Math.floor(Math.random() * 10 + 1); do [duplicate]

I came across the following command:

Math.floor(Math.random() * 10 + 1); 

I understand that Math.floor() will convert to the lowest integer, but what does Math.random() * 10 + 1 do?




How to generate a 500x500 pixel image in PIL with random place but i can choose what colors?

So for example I want the colors red, blue, and yellow in the 500x500 and the placement has to be random. I was looking at some posts and the documentation but couldn't really find it. With the image I'm going to convert it to a pygame surface using "pygame.image.fromstring".

it should be something like this but in 500x500 and the colors only should be randomized with red, blue and yellow, instead of all those random colors enter image description here

Thank You!




mardi 21 juin 2022

condition to randomly replace a character

tengo una secuencia, a la cual le remplazo 5 caracteres al azar, el problema que tengo es como remplazar el caracter al azar, este en algunos casos se reemplaza por si mismo, como puedo ponerle una condicionalidad para que por ejemplo si el caracter a reemplazar coincidencias Con "a" solo se reemplaza por "b,c,d o e", si el caracter a reemplazar coincide con "b" solo se reemplaza por "a,c,d o e"...

    import random
    s1='ecaaaeadddeeecbddddb'
    print(s1)
    change_locs = set(sample(range(len(s1)), 5))
    changed = (random.choice(['a','b','c','d','e',]) if i in change_locs else c for i,c in 
    enumerate(s1))
    s2=''.join(changed)
    print(s2)



R SQL: Is the Default Option Sampling WITH Replacement?

I want to sample a file WITH REPLACEMENT on a server using SQL with R:

Pretend that this file in the file I am trying to sample:

library(dplyr)
library(DBI)

con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "iris", iris)

I want to sample with replacement 30 rows where species = setosa and 30 rows where species = virginica. I used the following code to do this:

rbind(DBI::dbGetQuery(con, "SELECT * FROM iris WHERE (`Species` = 'setosa') ORDER BY RANDOM() LIMIT 30;"), DBI::dbGetQuery(con, "SELECT * FROM iris WHERE (`Species` = 'virginica') ORDER BY RANDOM() LIMIT 30;"))

However at this point, I am not sure if the random sampling being performed is WITH REPLACEMENT or WITHOUT REPLACEMENT.

  • Can someone please help me determine if the random sampling being performed is WITH REPLACEMENT or WITHOUT REPLACEMENT - and if it is being done WITHOUT REPLACEMENT, how can I change this so that its done WITH REPLACEMENT?

Thank you!




How can I print all possible answers in python?

There are 7 questions with 4 choices ( A, B, C, D). I want to log or print all possible answers. For example

> A A A A A A A
  A A A A A A B
  A A A A A A C
  A A A A A A D
  B A A A A A A
  B A A A A A B
  B A A A A A C
  .
  .
  .
  .
  .
  .
  D D D D D D D

How can I print it?

I've tried the following

for a in range(7):
    for b in range(7):
        for c in range(7):
            for d in range(7):
                print(a, b, c, d)

But this outputs

> 1 1 1 1
  1 1 1 2
  1 1 1 3
  1 1 1 4
  . 
  . 
  .
  6 6 6 6

But i need to get 7 possible answers to be printed on each line.




Generate array of objects with unique value

Currently this code generate array with 10 objects with value number and display.The number is random from 0 to 9 so there can be duplicates. Is there a way, where i can get unique(all the objects having different number value ) number only?

const newArray = Array(10)
        .fill()
        .map(() => {
          return { number: Math.floor(Math.random() * 10), display: false };
        });



Dbms_random GENERATED different results

I'm putting together sample test data using SQL.

Is there a way in SQL I can get different results every time I rerun the same SQL statement.

I am familiar with using a seed but I think that only works with PLSQL, which I would like to avoid if possible.

Is there someway the SQL could be adjusted to emulate a seed and provide different results for every new run?


CREATE TABLE students (
   student_id  number(*,0),
  first_name VARCHAR(25) NOT NULL,
  last_name VARCHAR(25) NOT NULL,
  active VARCHAR2(1) DEFAULT 'Y',
constraint student_pk primary key (student_id));


 insert into students (student_id, first_name, last_name, active)
        select
          level,       
CASE round(dbms_random.value(1,25)) 
            WHEN 1 THEN 'Faith' 
            WHEN 2 THEN 'Tom' 
            WHEN 3 THEN 'Anna'
            WHEN 4 THEN 'Lisa' 
            WHEN 5 THEN 'Andy' 
            WHEN 6 THEN 'Thomas' 
            WHEN 7 THEN 'Alan'
            WHEN 8 THEN 'Keith' 
            WHEN 9 THEN 'Cheryl' 
            WHEN 10 THEN 'Chester' 
            WHEN 11 THEN 'Steve'
            WHEN 12 THEN 'Mel' 
            WHEN 13 THEN 'Micheal' 
            WHEN 14 THEN 'Ron' 
            WHEN 15 THEN 'Donald'
            WHEN 16 THEN 'Carolyn' 
            WHEN 17 THEN 'Racheal' 
            WHEN 18 THEN 'Debbie' 
            WHEN 19 THEN 'Madison'
            WHEN  20 THEN 'Danny' 
            WHEN 21 THEN 'Claude' 
            WHEN 22 THEN 'Peter' 
            WHEN 23 THEN 'Edna' 
            WHEN 24 THEN 'Anita'
            WHEN 25 THEN 'Mindy' 
         END AS first_name,

    CASE  round(dbms_random.value(1,25)) 
            WHEN 1 THEN 'Andrews' 
            WHEN 2 THEN 'Thorton' 
            WHEN 3 THEN 'Smith'
            WHEN 4 THEN 'Jones' 
            WHEN 5 THEN 'Beirs' 
            WHEN 6 THEN 'Stevens' 
            WHEN 7 THEN 'Feldman'
            WHEN 8 THEN 'Stein' 
            WHEN 9 THEN 'Ross' 
            WHEN 10 THEN 'Mednick' 
            WHEN 11 THEN 'Saltzman'
            WHEN 12 THEN 'Kramer'
            WHEN 13 THEN 'Monroe' 
            WHEN 14 THEN 'Hanks' 
            WHEN 15 THEN 'Dunn'
            WHEN 16 THEN 'Dunbar' 
            WHEN 17 THEN 'Rucker' 
            WHEN 18 THEN 'Silverberg' 
            WHEN 19 THEN 'Daniels'
            WHEN  20 THEN 'Kern' 
            WHEN  21 THEN 'Saladino' 
            WHEN  22 THEN 'Rice'
            WHEN  23 THEN 'Sanford' 
            WHEN  24 THEN 'Krantz'
            WHEN  25 THEN 'Roth' 
         END AS last_name, 
        
          CASE MOD(LEVEL, 10)
           WHEN 0
          THEN 'N'
          ELSE 'Y'
         end
      from dual
      connect by level <= 25;




lundi 20 juin 2022

Get a random number through Chainlink VRF v2., but it has been pending, and it has been pending for two days

Obtain a random number through Chainlink VRF v2. But it has been pending, and it has been pending for two days. My link balance is enough, but it just can't be successful.

enter image description here




How to assign to each layer used for be randomnly assembled, game stats that will be used for calculate final image stats in json?

as a beginner I look for a way to assign game stats to png layers that I use for randomly generate final character. I know how to generate image , I know how to assign to the final image extra attributes, but those values are randomly return and it is not what I would like. I would like on each layer randomly assembled in .png I assign specific game stats and skills and when the final image will be generated, be able to return a json file of the character with the final stats and skills with calculation of each stats build done.I have look for on net and not find yet relevant answer.Thks




Array of functions not working when called in object

So I'm working on what should have been an easy project but is giving me, my classmates, and my mentor a ton of headaches. We're nearly there but it's still missing one piece to finally wrap it up. I just need to get the fact area to fill out with one of the function options.

Here's the function:

function createHuman(){
  let height = parseInt(humanFeet) * 12 + parseInt(humanInches);
    debugger
    myNewHuman = new human(humanName, "human", humanWeight.value, height, humanDiet.value, compareRand);
    function compareWeight(humanWeight){
      let myRandNum = Math.floor(Math.random() * dinoArr.length);
      let myMessage = `You are ${dinoArr[myRandNum].weight - humanWeight} pounds lighter than a ${dinoArr[myRandNum].name}.`;
      return myMessage;
      };
    function compareHeight(height){
      let myRandNum = Math.floor(Math.random() * dinoArr.length);
      let myMessage = `You are ${dinoArr[myRandNum].height - height} pounds shorter than a ${dinoArr[myRandNum].name}.`;
      return myMessage;
      };
    function compareDiet(humanDiet){
      let myRandNum = Math.floor(Math.random() * dinoArr.length);
      let myMessage = `You're a ${humanDiet} while ${dinoArr[myRandNum].name} is a ${dinoArr[myRandNum].diet}.`;
      return myMessage;
      };
  const compareRand = Math.floor(Math.random() * compareArray.length);
  compareArray = [compareWeight(), compareHeight(), compareDiet()]; 
};

Individually the functions work fine when placed like this , compareWeight(humanWeight.value) where compareRand is right now and the results should look like this: Screenshot of example of one function working in the facts area. I would post a screenshot of all the dinos around the human tile but that's too big for stackoverflow.

I'd really appreciate any input anyone could give me so I can finally finish is project.

(Please note: the dinoArr is an array outside of this function pulling data from a .json file. As the screenshot shows it's pulling the data just fine I just need to get the random picking of the array of functions to work.)




A random item from a JavaScript array display a different phrase after a new search/refresh of page [duplicate]

I built a weather app and I just wanted to add some phrases every time a new city is searched up or the page is reloaded. I have the phrases in an array (they show up in the console) and just need to figure out what to use to have it actually display in the HTML (innerHTML or document.queryselector ???). I am also stumped on how to call this function with the addEventListener when the "click" happens to submit the city search. So I need to figure out if < p > or a div class is what I need in my HTML. I feel close to figuring it out but I've spent hours on this...

function displayPhrase() {
var phrases = [
  "Always check the weather before going on long drives!",
  "Make sure your tires have tread.",
  "Make sure your wipers work properly.",
  "Always check fuel and oil levels.",
  "Drive safe today!",
  "Dress accordingly!",
  "Check your tire pressure regularly.",
];

var randomPhrase = phrases[Math.floor(Math.random() * phrases.length)];

console.log(randomPhrase);

}



How to pick certain amount of random excel cells with text and combine them in a string

I have a big list with about ~300 hashtags where I want to pick a certain amount (like 10 hashtags) randomly. Is it possible without VBA?

enter image description here




dimanche 19 juin 2022

Generating 11x6 matrix of randomly placed 0 and 1

I want to generate 11x6 matrix that have randomly placed 0 and 1. I want every row to be symmetric. It is represented by array of 6 arrays of length 11. I used the randint() function from the random module but it generates 6 copies of the same row. Here's my code:

import random

def pattern_generator():
    row = [None] * 11
    pattern = [row] * 6
    for i in range(len(pattern)):
        for j in range(len(row)):
            x = random.randint(0, 1)
            pattern[i][j] = x
            pattern[i][10 - j] = pattern[i][j]
    return pattern

And example of the output:

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

Can anyone give me any tip what I'm lacking in this function? Thanks in advance




R: Unexpected Nulls Appearing in Output

I am working with the R programming language.

I was able to run the following code without any problems:

# first code: works fine
library(dplyr)
library(ranger)

original_data = rbind( data_1 = data.frame( class = 1, height = rnorm(10000, 180,10), weight = rnorm(10000, 90,10), salary = rnorm(10000,50000,10000)),  data_2 = data.frame(class = 0, height = rnorm(100, 160,10), weight = rnorm(100, 100,10), salary = rnorm(100,40000,10000)) )

original_data$class = as.factor(original_data$class)
original_data$id = 1:nrow(original_data)

test_set=  rbind(original_data[ sample( which( original_data$class == "0" ) , replace = FALSE , 30 ) , ], original_data[ sample( which( original_data$class == "1" ) , replace = FALSE, 2000 ) , ])

train_set = anti_join(original_data, test_set)

# Step 2: Create "Balanced" Random Subsets:

results <- list()
for (i in 1:100)
   
{
   iteration_i = i
   
    sample_i =  rbind(train_set[ sample( which( train_set$class == "0" ) , replace = TRUE , 50 ) , ], train_set[ sample( which( train_set$class == "1" ) , replace = TRUE, 60 ) , ])
   
    results_tmp = data.frame(iteration_i, sample_i)
    results_tmp$iteration_i = as.factor(results_tmp$iteration_i)
   results[[i]] <- results_tmp
   
}

results_df <- do.call(rbind.data.frame, results)

X<-split(results_df, results_df$iteration)

 invisible(lapply(seq_along(results),
       function(i,x) {assign(paste0("train_set_",i),x[[i]], envir=.GlobalEnv)},
       x=results))

I am now trying to run the same code in parallel - here is my attempt:

# second code: does not work fine
library(doParallel)
library(foreach)

registerDoParallel(cores = detectCores())
foreach(i = 1:100) %dopar% {
    
    
    results <- list()
    
    {
        iteration_i = i
        
        sample_i =  rbind(train_set[ sample( which( train_set$class == "0" ) , replace = TRUE , 50 ) , ], train_set[ sample( which( train_set$class == "1" ) , replace = TRUE, 60 ) , ])
        
        results_tmp = data.frame(iteration_i, sample_i)
        results_tmp$iteration_i = as.factor(results_tmp$iteration_i)
        results[[i]] <- results_tmp
        
    }
    
    results_df <- do.call(rbind.data.frame, results)
    
    X<-split(results_df, results_df$iteration)
    
    invisible(lapply(seq_along(results),
                     function(i,x) {assign(paste0("train_set_",i),x[[i]], envir=.GlobalEnv)},
                     x=results))
    
}

stopImplicitCluster()

The code appears to have run - but unlike the first code, no additional files were created in the global environment and a series of nulls have appeared now:

[[100]][[91]]
NULL

[[100]][[92]]
NULL

[[100]][[93]]
NULL

[[100]][[94]]
NULL

[[100]][[95]]
NULL

[[100]][[96]]
NULL

[[100]][[97]]
NULL

[[100]][[98]]
NULL

[[100]][[99]]
NULL

My Question: Can someone please show me what I am doing wrong and how can I make the second code run like the first code?

Thanks!




Haskell - creating a string of 26 letters but randomized

I am new to Haskell (trying to self learn and write a semi complex program to familiarize myself) and trying to write a string generator that gives you a randomized alphabet without repeating the letters.

Example 1: "PLMOKNIJUHBVGYCTFDRXEZSWAQ" Example 2: "QAZWSXEDCRFVTGBYHNUJMIKOLP"

I am not really sure how to approach this since Haskell doesn't have loops, if this was in python, I'd understand how to implement this.

If anyone can show me how to implement this then I would greatly appreciate it.




Are these codes random and unpredictable? [closed]

Are the following codes random and unpredictable?

WRXPDFF

HBNKMRY

YPDYBYC

GGHYXYZ

MVWBJJQ

NTWMBHH

TWZBGJB

BWKRCYC

ZCMPBYN

GMBVZGH

YJYLWQV

DPDXZKV




Can you get a uniformly-random key-value pair from an std::map in sub-linear time?

Given an std::map<K,V> of size n, can you randomly get a key (and value) in the container, portably? Randomly here refers to key's position in the container. Let's say the distribution has to be only close to uniform.

My thinking was that standard library maps are often (always?) implemented as red-black trees, which are decently balanced. So locating an (almost-)uniformly random value could be done in log-time if you can access this underlying structure. It wouldn't be trivial but it could be done (idea: each node can estimate roughly how many child-nodes are left and how many are right of it).

In general one cannot access that information, so the obvious solution is to linearly iterate over it until you find the ith element for some uniformly-random chosen 0 <= i < n. However, as of C++17 there is also the rudimentary node interface that allows one to extract and re-insert nodes. But after some thought I don't see how this would be helpful.

Is there something I am overlooking or is this truly impossible in sub-linear time given the standardised interface of std::map?


Note: Obviously, if one wants to get more than, say, n / log n elements, shuffling a vector of map iterators is likely the best option.




vendredi 17 juin 2022

My array can't find the source of my pictures, how do I fix it? [closed]

So I'm building an comic slider on javascript and I want it to have a "pick a random comic" option. So, naturally, I tried to built a random function over a pretty big array. And made it, but, the function can't find the src of the pictures! What should I do? Everything seems good but maybe I'm missing something... can u help me with my code? thanks!

function random() {    
var randomNum = Math.floor(Math.random() * imgArray.length);
document.getElementById("comicdehoy").src = imgArray[randomNum];
}



Generate two false Booleans every ten rows in excel

I need to add a column to my spread sheet that generates two "false" at random intervals every ten frames.

So for example rows 1 though 10 could read:

  1. true
  2. true
  3. true
  4. False
  5. true
  6. false
  7. true
  8. true
  9. true
  10. true

and then repeat that for rows 11 through 20, but the false are randomly put in different places. etc. I want write a formula that does this for me.




Generate a big random array QT C++

Does anyone know how to generate a large array of random numbers from 100 or more repetitions. For example, I need to generate 100 times from 1 to 6 to simulate a dice roll. But when I repeat the cast more than 70 times it gives wrong values. I'm trying QRandomGenerator.system() And std::random, but that doesn't help. I also tried to do Sleep(1) every 50 throws.

long roll_D6(){
    QRandomGenerator generator;
    return (generator.system()->generate() % 6) + 1;
}

// other func
long current = 0;
for(size_t i = 0; i < 100; i++){
    current+=roll_D6();

}



create a sales and inventory system [closed]

that has the ability to create, delete, and edit a product of your company. Data of the company's products should be saved in a text file, and the receipt will be in a text file format. this system should have a GUI for the use of your cashiers/receptionists of the company.




Is there a way to make an if statement with random() using the any keyword?

i made this:

import random

import math


def RandomInteger(fint, fint2):
    print(random.randrange(fint, fint2))


if RandomInteger(any, any) > 100:
    print("Your values are greater than 100")

if RandomInteger(any, any) > 1000:
    print("You values are greater than 1000")


RandomInteger(99, 1000)

and i dont know why "any" isnt working this is probably a stupid question for senior devs because the answer seems obvious and i cant find it




jeudi 16 juin 2022

How can I create a program that simulates a lottery in Python?

I need to write a program that simulates a lottery. The program should have a list of seven numbers that represent a lottery ticket. It should then generate seven random numbers. After comparing the numbers the proram should output a prize for three matching numbers, four matching numbers, etc.

I'm not sure how to do the last bit where I need to check if there are three, four, five, etc matching numbers and output a prize depending on how many numbers are matching.




Decimal precission problems with runif

I'm running into issues when simulating low-probability events with runif in R, and wondering how to solve this.

Consider the following example for an experiment where we simulate values of TRUE with probability 5e-10 in a sample of size 10e9, and check if any of these samples got that value of TRUE. This experiment is repeated 10 times:

set.seed(123)
probability <- 0.0000000005
n_samples <- 1000000000
n_tries <- 10
for (i in 1:n_tries) {
  print(any(runif(n=n_samples, min=0, max=1) < probability))
}

Code above will run relatively fast, and nearly half of the experiment replicates will return TRUE as expected.

However, as soon as the probability becomes 5e-11 (probability <- 0.00000000005), that expectation fails and no TRUE values will be returned even if the number of replicates is increased (used n_tries <- 100 twice with no luck; the whole process took 1h running).

This means runif is not returning values with as many precision as 11 decimals. This was unexpected, as R to my understanding works with as much as 16 decimals of precision, and we might need to simulate processes with probabilities that small (around 15 decimals).

Is this why runif fails to provide the expected output? are there any other alternatives/solutions to this problem?

Thank you




Generate random number and save it in database in every minute

I want to generate random number automatically and save it in database in every minute. I am not expert in php and can someone help me to do it




mercredi 15 juin 2022

Logitech Lua Script randomized button press in repeat loop on random sleep timers

first time i try to code sth for me so....... Here i got a script that repeats (on mouse button 5 press) pushing multiple buttons with random sleep timers each after one another, checking after each button, if mouse button is still pressed. Working fine so far. Sorry for the chaotic look.

Goal:

  • holding down button 5
    • Pressing assigned buttons (7,8,w,q,f,s) in random order,
    • random sleep timers,
    • check after each random button press if mouse button is still pressed

Remaining Problem:

  • repeating same button order while holding down mouse button 5 (not randomized)

After hours of research i couldn't find somethin that helps me with that problem by myself, so i thought i'll try it here!

I really would appreciate some help here :)))

    EnablePrimaryMouseButtonEvents(true)
function OnEvent(event, arg)
   if event == "MOUSE_BUTTON_PRESSED" and arg == 5 then
      repeat
        PressKey("8")
         Sleep(math.random(16, 21)) 
         ReleaseKey("8") 
if not IsMouseButtonPressed(5) then break end
 Sleep(math.random(13, 47)) 
        PressKey("7")
         Sleep(math.random(16, 38)) 
         ReleaseKey("7") 
if not IsMouseButtonPressed(5) then break end
 Sleep(math.random(13, 47)) 
        PressKey("w")
         Sleep(math.random(43, 87)) 
         ReleaseKey("w") 
if not IsMouseButtonPressed(5) then break end
 Sleep(math.random(10, 49)) 
        PressKey("q")
         Sleep(math.random(16, 38)) 
         ReleaseKey("q") 
if not IsMouseButtonPressed(5) then break end
 Sleep(math.random(13, 47)) 
        PressKey("w")
         Sleep(math.random(43, 87)) 
         ReleaseKey("w") 
if not IsMouseButtonPressed(5) then break end
 Sleep(math.random(13, 47)) 
        PressKey("f")
         Sleep(math.random(15, 63)) 
         ReleaseKey("f") 
if not IsMouseButtonPressed(5) then break end
 Sleep(math.random(13, 47)) 
        PressKey("s")
         Sleep(math.random(16, 28)) 
         ReleaseKey("s") 
if not IsMouseButtonPressed(5) then break end
      until not IsMouseButtonPressed(5)
end



Generate random letters and give a coordinate Assembly 8086

im doing a word puzzle game, how can i generate letters in assembly 8086 and give them coordinates to print them in the specific locations? I have a code that generates numbers but i cant restrictic to only letters and give it coordinates to the right places to print.

Here is the code:

;------------------------------------------------------------------------
;   Base para TRABALHO PRATICO - TECNOLOGIAS e ARQUITECTURAS de COMPUTADORES
;   
;   ANO LECTIVO 2020/2021
;--------------------------------------------------------------
; Demostração duma rotina de calculo de números aleatórios 
;
;--------------------------------------------------------------

.8086
.MODEL SMALL
.STACK 2048

DADOS   SEGMENT PARA 'DATA'
    ultimo_num_aleat dw 0

    str_num db 5 dup(?),'$'
DADOS   ENDS

CODIGO  SEGMENT PARA 'CODE'
    ASSUME CS:CODIGO, DS:DADOS

PRINC PROC
    MOV AX, DADOS
    MOV DS, AX

    mov cx,10
ciclo:
    call    CalcAleat
    pop ax ; vai buscar 'a pilha o numero aleatorio

    mov dl,cl
    mov dh,70
    push    dx
    push    ax
    call    impnum
    loop    ciclo

FIM:
    MOV AH,4Ch
    INT 21h
PRINC ENDP

;------------------------------------------------------
;CalcAleat - calcula um numero aleatorio de 16 bits
;Parametros passados pela pilha
;entrada:
;não tem parametros de entrada
;saida:
;param1 - 16 bits - numero aleatorio calculado
;notas adicionais:
; deve estar definida uma variavel => ultimo_num_aleat dw 0
; assume-se que DS esta a apontar para o segmento onde esta armazenada ultimo_num_aleat
CalcAleat proc near

    sub sp,2
    push    bp
    mov bp,sp
    push    ax
    push    cx
    push    dx  
    mov ax,[bp+4]
    mov [bp+2],ax

    mov ah,00h
    int 1ah

    add dx,ultimo_num_aleat
    add cx,dx   
    mov ax,65521
    push    dx
    mul cx
    pop dx
    xchg    dl,dh
    add dx,32749
    add dx,ax

    mov ultimo_num_aleat,dx

    mov [BP+4],dx

    pop dx
    pop cx
    pop ax
    pop bp
    ret
CalcAleat endp

;------------------------------------------------------
;impnum - imprime um numero de 16 bits na posicao x,y
;Parametros passados pela pilha
;entrada:
;param1 -  8 bits - posicao x
;param2 -  8 bits - posicao y
;param3 - 16 bits - numero a imprimir
;saida:
;não tem parametros de saída
;notas adicionais:
; deve estar definida uma variavel => str_num db 5 dup(?),'$'
; assume-se que DS esta a apontar para o segmento onde esta armazenada str_num
; sao eliminados da pilha os parametros de entrada
impnum proc near
    push    bp
    mov     bp,sp
    push    ax
    push    bx
    push    cx
    push    dx
    push    di
    mov     ax,[bp+4] ;param3
    lea     di,[str_num+5]
    mov     cx,5
prox_dig:
    xor     dx,dx
    mov     bx,10
    div     bx
    add     dl,'0' ; dh e' sempre 0
    dec     di
    mov     [di],dl
    loop    prox_dig

    mov     ah,02h
    mov     bh,00h
    mov     dl,[bp+4] ;param1
    mov     dh,[bp+13] ;param2
    int     10h
    mov     dx,di
    mov     ah,09h
    int     21h
    pop     di
    pop     dx
    pop     cx
    pop     bx
    pop     ax
    pop     bp
    ret     4 ;limpa parametros (4 bytes) colocados na pilha
impnum endp

CODIGO  ENDS
END PRINC



Is there a python library that allows for use of different PRNGs? [closed]

I'm working on a project where I'm using python to execute different analysis techniques to test "how random" a data set is. To act as a control I'd like to analyze different known pseudo-random number generators (PRNGs) and see if the analysis performs as expected. I was wondering if there were any python libraries that had functions similar to Python's native random function (which I believe utilizes the Mersenne Twister PRNG) but with controls to use different PRNGs? I did some quick google searching and didn't really find anything useful.




srand() and rand() giving the same numbers in c [duplicate]

I have this code

BTree randomTreeRec(int n)
{
    if(n <= 0)
        return NULL;
    //random value
    srand(time(NULL));
    int *value = malloc(sizeof(int));
    *value = rand() % 101;

    BTree bt = buildTree(NULL, NULL, value);

    //branches option 0 is left 1 is right

    int branches = rand() % 2;

    if(branches == 0)
        bt->left = randomTree(n - 1);
    if(branches == 1)
        bt->right = randomTree(n - 1);
    return bt;
}

why does rand always give me the same numbers even if I'm using srand(time(NULL)) ? I tried putting srand out from the recursive function because I thought the cpu was too fast and always used the same seed but it didn't work

BTree randomTreeRec(int n)
{
    if(n <= 0)
        return NULL;

    //random value
    int *value = malloc(sizeof(int));
    *value = rand() % 101;

    BTree bt = buildTree(NULL, NULL, value);

    //branches 0 is left 1 is right
    int branches = rand() % 2;
    if(branches == 0)
        bt->left = randomTree(n - 1);
    if(branches == 1)
        bt->right = randomTree(n - 1);
    return bt;
}

BTree randomTree(int n)
{
    srand(time(NULL));
    return randomTreeRec(n);
}

how can I solve this?




Why my code doesn't run when I use random.randint?

I am trying to make a wordle with python but finally when I run it, it doesn't work. First it seems to work but there is nothing in the output, then when I press CTRL+C to cancel the console gives me an error message: "line 26, in num = random.randint(0,(len(wordlist)-1)) keyboard interrupt"

CODE:

import random


listaPalabras = ["casa", "gato", "hola", "mesa"]


intentos = 5

class Colors:
    OKGREEN = '\033[92m'
    OKBLUE = '\033[94m'
    ENDC = '\033[0m'


def verde(pos):
    return Colors.OKGREEN+pos+Colors.ENDC

def azul(pos):
    return Colors.OKBLUE+pos+Colors.ENDC


resp = "S"

while resp.upper() == "S":

    # The problem appears in the next line
    num = random.randint(0,(len(listaPalabras)-1))

    sol = (listaPalabras[num])


for i in range (intentos):
    listaPalabra = []
    listasol = []

    palabra = input("\nEscribe una palabra de 4 letras:\n")

    while not (len(palabra) == 5):
        palabra = input("\nEscribe una palabra de 4 letras:\n")

    
    if sol == palabra:
        break

    else:
        for i in palabra:
            listaPalabra.append(i)

        for i in sol:
            listasol.append(i)

        for i in range (len(listaPalabra)):

            if listaPalabra[i] in listasol[i]:
                print(verde(listaPalabra[i], end = ""))

            if not listaPalabra[i] in listasol[i]:
                print(listaPalabra[i], end = "")

            elif listaPalabra[i] in sol and not (listaPalabra[i] in listasol[i]):
                print(azul(listaPalabra[i], end = ""))

print ("")

if palabra == sol:
    print(verde(palabra))
    print("La palabra es correcta!")

else:
    print("Se te han acabado los intentos\nNo has acertado")


resp = input ("Quieres volver a jugar? (S/N)")

while not resp.upper() in ["S", "N"]:
    resp = input ("Quieres volver a jugar? (S/N)")



mardi 14 juin 2022

what does VRFCoordinatorV2Interface(vrfCoordinator) mean in chain link documentation

I know that VRFCoordinatorV2Interface is an interface and we put the respective chain coordinator address in it. what does it signifies and how to visualise it. OR What will be the outcome when we put an address in a interface.




How can I use same random background color to fill rectangle in P5js

I'm trying to do something in P5js. For this, I need to pick random color of an array for background that has to be in setup. Then I want to pick this random selected background color to fill rectangle under draw function.

There are other shapes with randomness under background that has to be run once. And there is another object under rectangle that has to be in a loop. That is why one is in setup and other one is under draw function. But, I'm going to simplify my problem as;

function setup() {
  createCanvas(400, 400);
  colorsPaletteSecond = [color(0, 0, 0),
                         color(160, 57, 164),
                         color(93, 94, 198),
                         color(135, 198, 112), ];            
  let screenColor = random(colorsPaletteSecond);
  background(screenColor);
}

function draw() {
  stroke(0)
  fill(screenColor);
  rect(200,200,100,100);
}

I need to define screenColor in draw section as well, to pick same color with background. Any suggestions? Thanks in advance.




How can I generate every possible integer in a range without repeats from a seeds that is also reversible

I have been looking for a while at large number generation through seeds and I’ve struggled to find what I am looking for due to how specific it is. I think the main thing that is causing the problems is the size of numbers I want to generate, for example... I want to have it so that I can generate every single number that is 5000 digits long through some form of seed or selective input process. The other problem being that I would like to be able to reverse the process to know how I got there. If I have this number I want to know what inputs or what seed would generate this. Hope this makes sense and I understand this is a extremely specific question.




lundi 13 juin 2022

How to generate random numbers using an array? [closed]

I would like to generate an array of random numbers between 8-12 using this array?

int[] parArray = new int[18];




How to randomize Header with Users Agent list?

i have a question,

in my script .py i have:

    headers = {'Connection': 'keep-alive',
              'Cache-Control': 'max-age=0',
              'Upgrade-Insecure-Requests': '1',
              'User-Agent': {agents},
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
              'Accept-Encoding': 'gzip, deflate',
              'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8',
              'referer': 'bing.com'}

On the .json file

    { 
      "user_agent_list": [
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
      ]
    }

and when i send the request:

find_file = (grequests.get(url_a, headers={headers}, timeout=None, stream=True, verify=False, allow_redirects=False) for url_a in [f'{site_link}{x}' for x in file_rootl])

how i can, randomize headers={headers} for each requests ? of course " for agents in user_agent_list "

more better:

'User-Agent': {agents}, this i need randomize inside headers...

Some idea ? Thanks Max




Xamarin.Forms Random List

I am running into a problem when trying to pull random List items, it keeps getting an "Out of Range Exception" rather than starting back at the begining. How do I get it to keep pulling randomly from the list?

        var rand = new Random();
        var next = rand.Next(1);

        Device.StartTimer(TimeSpan.FromSeconds(1), () =>
        {
            _countSeconds--;

            if (_countSeconds == 0)
            {
                count--; //trying to use count instead of index to go past the 4 list items
                next++;
                _countSeconds = 3;

                if (count < 6 && count >= 0)
                {
                    BindingContext = Footwork2[next];                       
                }
                else
                {
                    return false;
                }
            };

            CountLabel.Text = _countSeconds.ToString();

            return true;
        });



dimanche 12 juin 2022

How to sample across a dataset with two factors in it?

I have a dataframe with two species A and B and certain variables a b associated with the total of 100 rows.

I want to create a sampler such that in one set it randomly picks 6 rows reps from the df dataset. However, the samples for A must only come from rows associated with sp A from df, similarly from B. I want do this for 500 times over for each of species A and B.

I attempted a for loop and when I ran sampling it shows a single row with 6 columns. I would appreciate any guidance

a <- rnorm(100, 2,1)
b <- rnorm(100, 2,1)
sp <- rep(c("A","B"), each = 50)  

df <- data.frame(a,b,sp)

df.sample <- for(i in 1:1000){
             sampling <- sample(df[i,],6,replace = TRUE)
}

#Output in a single row
a     a.1 sp        b sp.1     a.2
1000 1.68951 1.68951  B 1.395995    B 1.68951

#Expected dataframe
df.sample
set rep a b sp
  1  1  1 9  A
  1  2  3 2  A
  1  3  0 2  A
  1  4  1 2  A
  1  5  1 6  A
  1  6  4 2  A
  2  1  1 2  B
  2  2  5 2  B
  2  3  1 2  B
  2  4  1 6  B
  2  5  1 8  B
  2  6  9 2  B
  ....



distribution 2 lists random to another 2 lists

I have two list A and B ,

and P1,P2

and I need to take A,B and randomly distribution them to the two lists P1,P2

A = [ A1,A2,A3,A4 = "A1","A2","A3","A4" ]

B = [n101,n102,n103,n104 = "101","102","103","104"]

this loop should distribution the lists 4 times randomly unitll all P1 and P2 get filled up randomly

for i in range(4):
    if(i <= 3) and a == 3:
        P1 = range(A1,A2,A3,A4,n101,n102,n103,n104)
        a += 1
    
    if(i <= 3) and b == 3:
        P2 = range(A1,A2,A3,A4,n101,n102,n103,n104) 
        b += 1
    

expected result

P1 = A4,101,104,A2
P2 = 102,A3,103,A1

P1,P2 random distribution from A,B




What is the randomness in crimCV?

I asked a question about crimCV different results in R and I learned that it uses randomness. That is why I get different results every time I use it. My question is what is its randomness? I searched for it but I didn't find any answers.




The fastest way to generate Gaussian Orthogonal Ensemble (GOE) matrix and find its eigenvalues

I want to generate a Gaussian Orthogonal Ensemble (GOE) matrix (definition please refer to https://www.lpthe.jussieu.fr/~leticia/TEACHING/Master2019/GOE-cuentas.pdf) and find its largest and the second largest eigenvalues. Is there any faster way?

My code is like below now:

def simulate_f(n):
    main = np.sqrt(2) * np.random.normal(size=(1, n))
    off = np.random.normal(size=(n, n))
    tril = np.tril(off, -1)
    W_n = tril + tril.T
    np.fill_diagonal(W_n, main)

    eigenvalues = LA.eigvals(W_n)
    w = np.flip(np.sort(eigenvalues))
    # GOE_L12_dist[:,i] = w[0:2]
    return w[0:2]



samedi 11 juin 2022

Why are /dev/random and /dev/urandom stopping after 32MiB?

I get this output on very single commandline listed below:

0+1 records in
0+1 records out
33554431 bytes (34 MB, 32 MiB) copied, 0.14532 s, 231 MB/s

Here are the different options I tried:

a) dd if=/dev/random of=/dev/null status=progress bs=1G count=1

b) dd if=/dev/urandom of=/dev/null status=progress bs=1G count=1

c) dd if=/dev/urandom of=/dev/null status=progress bs=100M count=1

d) dd if=/dev/urandom of=/dev/null status=progress bs=50M count=1

e) dd if=/dev/random of=/dev/null status=progress bs=50M count=1

f) dd if=/dev/random of=/dev/null status=progress bs=33M count=1

g) dd if=/dev/urandom of=/dev/null status=progress bs=33M count=1

This dd if=/dev/urandom of=/dev/null status=progress bs=10M count=1 is doing as expected and outputs:

1+0 records in
1+0 records out
10485760 bytes (10 MB, 10 MiB) copied, 0.0518184 s, 202 MB/s

I tried this with MX Linux (Kernel 5.10) and with KDE neon and with Ubuntu 20.04

Does someone have a under-the-hod answer? Or some possible ideas?




Best ways to evaluate randomness of a shuffled list

I'm trying to qualify the randomness of some shuffled list. Given a list of distinct integers, I want to shuffle it with different random generators or methods and evaluate the quality of the resulting shuffling.

For now, I tried to do some kind of dice experiment. Given a list of input_size, I select some bucket in the list to be the "observed" one and then I shuffle the initial list num_runs * input_size (always starting with a fresh copy). I then look the frequencies of the elements that fell in the observed bucket. I then report the result on some plot. You can observe the results bellow for three different methods (line plots of the frequencies, I tried histogramms but it would look bad).

The dice experiment over three methods

Reporting plots only is not formal enough, I would like to report some numbers. What are the best ways to do it (or used in academic publications).

Thanks in advance.




"Enter command number "

when I was trying to run a program in Command prompt , it keep displaying "Enter command number " . I even restarted my pc and tried again but it keep displaying "Enter command number "




vendredi 10 juin 2022

Why is random device creation expensive?

C++11 support pseudo-random number generation through <random> library. I've seen multiple books which mention that it is quite expensive to keep constructing and destroying std::random_device, std::uniform_int_distribution<>,
std::uniform_real_distribution<> objects and they recommend to keep a single copy of these objects in the application.

Why it is expensive to create/destroy these objects? And what exactly mean by expensive here? Is it expensive in terms of execution speed or executable size or any other thing?

Can someone please provide some explanation. Thanks.




Sympy changes the random seed

I am working on a python 3 project where I use deap and sympy. I set the seed to a fixed value after I imported the random module in the main file.py that I execute in order to have a reproductible code. but then I found out that I do not obtain the same results after I run it more than once (deap uses a lot of random numbers), when I tracked the bug I found that it's in the sympy parsing function sympy.parsing.sympy_parser.parse_expr used to transform a string to a sympy expression. I am pretty sure sympy is messing with the random seed but I have no idea how to rectify it. Any suggestions or ideas would be appreciated and let me know if the problem described is clear or not. Thanks!






Python Class Var [closed]

I'm trying to print a range of numbers, but the following error keeps happening

Traceback (most recent call last):
  File "/home/user/scripts/./a.py", line 36, in <module>
    out()
  File "/home/user/scripts/./a.py", line 32, in out
    a = Class()
  File "/home/user/scripts/./a.py", line 27, in __init__
    n.var = (str(random_n))
AttributeError: 'int' object has no attribute 'var'

I don't know why it says that "int object has no attribute var", since I have changed it to string when I declared n.var = (str(random_n))

Actual code

import random


class Class:
    def __init__(ddd):
        for n in range(13):
            random_n = random.randint(11, 25)
            n.var = (str(random_n))



def out():
    a = Class()
    print(n.var)


out()

I wanna do like this, because previously I was doing like this

old code

def numbers():
    #global count
    for n in range(13):
        random_n = random.randint(11, 25)
        #print(random_n)
        for pre in range(32):
            random_fixos = random.randint(67, 99)
            print(str(random_n)+str(random_fixos))
            for f in range(1000000):
                random_numbers = random.randint(1000000, 10000000)
                numeros = (str(random_ddd)+str(random_fixos)+str(random_numbers))
                print(numbers)
                time.sleep(1.0)


numbers()

The problem is that, while the final part, (for f in range (1000000)) prints randomly the numbers, the first (for n in range(13)) and the second (for pre in range (32)) print in a sort of steady way.

For example: First execution

11845407780
11847790993
11845521441
11844457881
11841447069

Second execution

18794056402
18797877007
18796405493
18799151318
18796108887

In both outputs of the executions, the first four digits it's not being printed randomly (first output stuck at 1184 and second output at 1887). As long as I know, those "stuck" numbers will only change once the rest of the number reach all possible combinations. In addition, the first four digits just changes once I reset the execution.

My goal is to print numbers in a fully random way, but considering what I've already set for their range

Sorry for the long question. I thank in advance for anyone who ever helps me!!!




jeudi 9 juin 2022

How to generate 6 random number where their sum is equal to a certain value? [duplicate]

I have looked at comparable questions such as:

  1. How to generate a list of random numbers so their sum would be equal to a randomly chosen number
  2. Generating a list of random numbers, summing to 1

but these do not seem to answer my question.

I would like to generate 6 random numbers where the sum of all numbers = 157750 (or well 5 random and the last to be the difference). I have looked at Dirichlet distribution and other methods but not really help.

Does anyone know how to approach this?




Too frequent Random Byte Collision

I've written a program to simulate collisions in accordance to the typical "Birthday Problem".

However, even taking that into account I'm seeing collisions happen far too frequently in the random data, to the point where my generator is reporting collisions in random 1024 byte data which should be infeasible if my code is correct.

I suspect my problem is in my implementation of my EqualityComparer

void Main()
{
    var gen = System.Security.Cryptography.RandomNumberGenerator.Create();
    
    foreach (int i in new int[]{1,2,3,4,8,16,64,256,1024})
    {
        (var dupe, var counter) = BirthdayByte(gen, i);
        Console.WriteLine($"{i:00}. Found duplicate byte after {counter:000000} tries: {BitConverter.ToString(dupe)} ");    
    }
}

public (byte[], long) BirthdayByte(RandomNumberGenerator rng, int bufferLength)
{
    var found = false;
    HashSet<byte[]> members = new HashSet<byte[]>(new ByteArrayComparer());
    byte[] randomBytes = new byte[bufferLength];
    long counter = 0;
    while (!found)
    {
        counter++;
        rng.GetBytes(randomBytes);
        found = members.Contains(randomBytes);
        if (!found)
        {
            members.Add(randomBytes);
        }
    }
    return (randomBytes, counter);
}

public class ByteArrayComparer : IEqualityComparer<byte[]>
{
    bool IEqualityComparer<byte[]>.Equals(byte[] x, byte[] y)
    {
        if(x.Length != y.Length) return false;
        
        for (int i = 0; i < x.Length; i++)
        {
            if(!x[i].Equals(y[i])) return false;
        }
        return true;
    }

    int IEqualityComparer<byte[]>.GetHashCode(byte[] obj)
    {
        unchecked
        {
            if (obj == null)
            {
                return 0;
            }
            int hash = 17;
            foreach (byte element in obj)
            {
                hash = hash * 31 + element.GetHashCode();
            }
            return hash;
        }
    }
}

One typical output is:

01. Found duplicate byte after 000017 tries: D8 
02. Found duplicate byte after 000044 tries: 9D-59 
03. Found duplicate byte after 000536 tries: 49-DF-8D 
04. Found duplicate byte after 004234 tries: 09-02-ED-18 
08. Found duplicate byte after 095210 tries: 46-1D-86-37-00-ED-AD-6D 
16. Found duplicate byte after 040305 tries: 79-EF-C4-C8-49-97-DD-8A-28-45-CD-D8-E8-EA-58-3E 
64. Found duplicate byte after 068927 tries: 57-12-3E-6D-EF-A1-90-F0-F2-F9-3F-E8-C8-76-0E-15-E9-AF-F0-D4-14-C4-AA-85-D6-D0-56-D6-CB-66-1C-7D-F0-5B-73-CC-67-90-F7-73-0D-DB-7B-64-FC-D8-D3-86-6D-38-DD-6E-9F-1E-18-A3-C1-96-86-C2-5A-BD-47-76 
256. Found duplicate byte after 073932 tries: 11-4D-5E-B7-92-0D-84-58-79-53-60-14-B9-80-3A-7B-00-CC-A4-33-77-E8-8F-21-C5-AB-38-7F-F1-61-3B-9D-F7-C6-3D-F1-39-9A-9E-57-7B-E7-E7-DA-A3-6E-69-D0-5E-8B-9A-94-0D-74-1E-83-F0-02-A4-FD-BF-76-C8-DC-09-CD-4E-55-39-7C-AA-58-0D-5F-FF-6B-1B-A6-51-1B-13-38-FD-FD-DE-C7-35-03-85-5B-AF-3D-F6-21-BA-9F-94-15-05-E8-4F-D0-A6-AA-F2-0D-0D-B7-41-B7-E0-DE-A8-BE-F1-D5-CB-DC-FD-A6-B2-82-72-AC-C5-49-63-5F-55-5B-0D-E5-4A-AD-B9-2D-3D-F5-B5-61-A8-0F-31-91-8F-3C-7D-67-F8-A6-14-58-C6-AA-C5-97-6F-66-19-AC-66-07-BB-BF-FC-FB-E0-C6-41-9F-24-36-5E-51-4D-5B-6D-1C-C6-96-43-09-24-A7-38-86-89-BC-C1-1F-5F-44-48-0C-F8-58-CB-76-01-46-F9-84-EE-CE-77-E7-9C-B6-35-D9-2F-ED-A7-7B-F4-C6-94-6E-79-63-68-29-1C-3A-52-BA-04-DD-80-4E-A2-B0-FB-BF-09-FC-C6-B0-1F-BA-79-2F-F5-DE-3A-D5-00-B0-20-82-65-ED-15-C8-DA-4F 
1024. Found duplicate byte after 026518 tries: F5-54-6A-81-92-27-FB-75-3D-EA-CC-D2-2D-26-90-1D-B8-B5-8F-52-BB-60-49-47-E0-8D-AC-E4-02-1C-76-EA-64-FD-A5-AC-9A-9D-A2-52-69-6E-28-D8-EF-8C-6D-1D-CA-24-3D-85-8B-F5-64-47-81-72-97-24-B9-DA-5E-A9-CB-6E-97-65-2E-96-7C-71-A8-12-79-27-43-31-72-36-0E-F4-C1-D8-E1-17-D9-EA-88-FF-9B-E6-E7-59-10-95-74-7F-6A-D6-6C-95-3A-5B-22-CD-99-6E-C7-D2-09-68-47-B6-F5-14-F0-BB-9B-D0-04-67-E0-85-3E-03-85-AB-68-8D-DB-93-97-8E-B2-65-55-03-47-5E-DC-8B-05-45-44-F8-5C-FA-6D-0B-08-C9-2B-16-6E-35-20-AD-56-BA-14-6B-F1-0B-98-69-52-23-5A-86-6E-CF-08-2B-6A-8D-0E-B1-0F-36-F8-BF-70-33-FB-EB-50-94-D9-12-AB-C9-4E-0B-8C-1C-53-B2-63-96-E9-D1-AF-44-8C-79-23-54-0E-3E-AA-C2-1D-D6-DF-0A-95-01-38-D4-A8-68-0E-FF-5E-6B-EC-20-70-5D-7F-43-FD-43-32-AF-E4-DC-67-6F-8A-0A-33-67-9A-9E-5A-7B-29-07-FA-70-36-0B-96-E4-B9-28-86-FF-FA-0B-9B-38-46-C1-7B-9E-92-F5-E1-F1-44-44-98-D0-DE-0B-9B-88-24-B6-8D-E4-0A-D7-93-5D-65-07-BD-84-E1-54-BC-90-D0-67-38-96-62-4F-4A-C4-04-BC-A7-68-43-F2-77-C7-83-39-CD-D9-44-0D-A7-A7-6D-DF-01-CE-50-ED-D7-36-8B-50-71-FC-AE-16-ED-FD-A9-DD-C3-92-B2-5E-16-6C-67-D0-F6-E5-84-5B-25-AD-34-BA-4D-EB-92-5E-2F-3B-F5-AE-7E-6F-E4-8D-D2-8D-70-DE-D6-38-0C-89-43-26-B6-91-9E-FC-C4-24-43-FC-CB-56-2D-12-84-88-F4-B2-76-01-82-BA-68-6A-4A-07-E2-78-C1-F5-F1-9A-73-35-D2-A9-D7-9A-9A-B5-10-54-1C-D7-BA-63-7E-A4-B6-CA-4C-76-86-B5-FE-03-6C-6C-93-B2-60-14-47-EE-D5-55-36-2F-6B-BA-57-73-53-F2-0F-81-97-2B-A5-5E-79-DF-E0-DF-50-55-B6-1D-BE-EC-40-7A-14-2B-99-BA-31-C8-4E-BC-CE-89-50-87-63-B1-26-70-4D-76-AB-5A-DD-AB-3A-EF-D1-06-17-8E-CD-BE-14-0B-8D-3C-91-05-20-07-23-31-6B-8B-17-76-5E-8B-A7-EC-57-6F-53-56-6A-33-45-0F-85-F0-D8-1F-35-ED-B8-9B-CF-1D-28-19-F4-C9-9E-CA-EF-E3-C9-3A-AE-87-03-20-F2-8D-03-0B-C0-2E-22-C8-0B-71-8D-9E-50-C2-4B-D2-8C-B1-5B-75-2B-D2-AC-2F-0B-D8-CB-3B-41-E0-F1-04-0F-3B-06-F0-85-BE-B8-9A-41-ED-57-EF-C3-A8-85-15-8A-48-96-0F-6C-37-24-C2-54-0E-F3-07-8E-4D-47-0A-FC-68-FC-5E-72-3B-37-49-2A-29-2F-F0-E3-8B-D5-BF-83-40-4C-08-65-ED-2F-25-AC-CA-DF-07-6F-3D-08-32-6F-AB-75-35-67-44-2C-2B-75-69-23-B0-56-1B-7D-9C-BF-A3-E9-EB-37-9A-05-D7-18-55-A4-4D-A1-BF-79-5D-A4-59-93-BF-83-99-70-27-C5-CA-31-BD-4F-58-81-FC-E0-A5-DE-2C-2A-DA-48-DC-8C-4C-21-95-15-F9-DF-23-E8-1D-45-77-A9-3E-55-13-1F-77-DC-C4-A8-8F-9F-02-76-73-72-A5-0E-3D-F6-03-DF-B8-5E-91-DF-83-7C-AB-08-C0-99-54-58-32-A0-7C-41-4D-87-61-BF-32-D0-FD-13-27-4A-70-F7-5A-9D-C5-B8-03-C7-A7-22-5A-AF-E9-EF-93-5E-96-66-D4-91-09-60-B7-AA-21-77-AD-A1-A0-9D-82-5E-C0-28-E4-24-68-DA-32-D8-BE-8F-97-27-7C-FE-47-90-A9-FE-A5-0E-0C-84-BF-47-50-D0-74-B9-AF-77-A8-5F-55-D6-6F-00-79-C8-79-42-16-D9-70-7A-98-72-28-6B-B9-9E-89-18-4E-2A-7B-BA-CB-0C-09-A3-25-0C-D1-E8-4A-51-2D-E8-CA-95-F4-AE-56-3B-86-30-09-D2-92-F9-6B-40-CB-0F-40-F8-92-26-71-CE-AA-11-26-F9-E7-F2-EF-C8-4F-D1-10-7B-54-11-41-F4-8C-13-C2-19-30-1E-8F-E2-2F-EC-69-5E-9B-3C-5A-CE-9E-B3-49-EE-74-53-2D-FE-02-AD-9E-C1-04-88-68-40-91-06-6E-38-AC-DE-15-8F-75-9C-72-E0-49-95-75-1A-11-70-AD-33-4E-A2-90-99-D6-9E-B3-84-17-56-7D-54-86-B2-E3-53-61-D1-92-8F-B1-C4-20-3D-CE-89-38-CE-B2-6C-77-9E-39-02-2A-9E-A8-1F-1C-97-DC-7D-A6-9B-03-A6-B7-0E-95-B8-46-1A-9E-38-26-2E-B2-F3-B7-72-E6-69-1C-42-BC-DC-8C-39-A2-DE-20-3F-66-7A-52-3C-5D 

The first result with a single byte feels about right, but I'd expect that doubling the buffer length ought to make the search take significantly longer and that doesn't seem to be the case.

I've tried printing out the bytes and while they appear to be "genuine" collisions I struggle to believe that I'm really generating random collisions so easily.

Is the problem in the way I'm filling the randomBytes buffer, or a problem in my ByteArrayComparer?




mercredi 8 juin 2022

How would you build in criteria when using Random assign people to groups

I would like to assign people randomly to a group. I have used the following code from an existing script but I would like to add a criteria where "Kimani" is always no. 2 in a group

'''
import random

participants= 
["Alex","Elsie","Elise","Kimani","Ryan","Chris","Paul","Chris1","Pau2l", 
"Chris3","Paul3"]
group=1
membersInGroup=5

for participant in participants[:]:               # only modification
if membersInGroup==5:
    print("Group {} consists of;".format(group))
    membersInGroup=0
    group+=1
person=random.choice(participants)
print(person)
membersInGroup+=1
participants.remove(str(person))
'''



What's the most efficient way of randomly picking a floating number within a specific range?

I have a random number generator function to generate both an integer and floating point number within a specific range. My only problem is with float wherein I simply used range() to generate the range of possible values that can be picked by mt_rand() or random_int(). One can only imagine the inefficiency of generating a range from -9.99999999999999 to 9.99999999999999.

Although I tried other approaches such as separating the integer part and the fractional part then generating them separately, removing the decimal point then generating from that range, but they all have their own complexities.

Is there a better way to randomly pick a floating number within a specific range?

PHP Code

function generateNumber(int|float $start = PHP_INT_MIN, int|float $end = PHP_INT_MAX, int|null $seed = null, bool $isInteger = true, bool $isCryptographic = false): int|float {
    $randFunction = ($isCryptographic === false ? 'mt_rand' : 'random_int');

    var_dump($randFunction);

    if ($isInteger === true) {
        $start = (int) $start;
        $end = (int) $end;

        if (!$isCryptographic && $seed !== null) mt_srand($seed);

        return $randFunction($start, $end);
    }

    $start = (float) $start;
    $end = (float) $end;

    $hasDecimalPoint = strrchr(haystack: (string) $start, needle: '.');
    $start = ($hasDecimalPoint ? $start : "{$start}.0");

    $hasDecimalPoint = strrchr(haystack: (string) $end, needle: '.');
    $end = ($hasDecimalPoint ? $end : "{$end}.0");

    $startFractionDigits = strlen(substr(strrchr(haystack: (string) $start, needle: '.'), offset: 1));
    $endFractionDigits = strlen(substr(strrchr(haystack: (string) $end, needle: '.'), offset: 1));

    var_dump($startFractionDigits);
    var_dump($endFractionDigits);

    $step = 10 ** -($startFractionDigits > $endFractionDigits ? $startFractionDigits : $endFractionDigits);
    $numberList = range($start, $end, $step);

    var_dump($step);
    print_r($numberList);

    if (!$isCryptographic && $seed !== null) mt_srand($seed);

    $min = 0;
    $max = count($numberList) - 1;
    $index = $randFunction($min, $max);

    return $numberList[$index];
}

var_dump(generateNumber(start: -1.18, end: -1.25, seed: null, isInteger: false, isCryptographic: false));

Sample Output:

string(7) "mt_rand"
int(2)
int(2)
float(0.01)
Array
(
    [0] => -1.18
    [1] => -1.19
    [2] => -1.2
    [3] => -1.21
    [4] => -1.22
    [5] => -1.23
    [6] => -1.24
    [7] => -1.25
)
float(-1.22)



Evaluating convergence of a random variable (unknown expected value)

I have a stochastic simulation model that produces random deviates of a variable, whose expected value is unknown. I would like to determine the minimal number of simulations necessary to obtain convergence of the mean of the random variable.

For instance, using a reproducible example:

sample_size <- 10000
X <- runif(sample_size)
plot(sapply(seq_len(sample_size),
            function(i) mean(y[seq_len(i)])),
     type = "l",
     ylim = c(0, 1),
     xlab = "Number of samples, n",
     ylab = "Average of n samples")

enter image description here

Here, I would like to determine the minimal sample_size to obtain convergence of the mean of X (here probably somewhere between 2000 and 10000), while the expected value of X is unknown (for the reproducible example I know that the expected value is 0.5, but let's pretend we ignore that).

Any advice on the method I should use?




Randomly select multiple values from a list based on a TRUE filter in Excel

Summary

I would like to select multiple randomly selected options from a list within Excel, but filtered to only include those with a TRUE indicator in another column. The number of random selections to make will need to be vary. Additionally, duplicates shouldn't be pulled. Ideally, I would like to have the formula contained within one cell, and have it spill to the required length, if such a thing would be possible.

Current attempt

I have tried making this logic work through the combined used of =INDEX, =RANDBETWEEN =FILTER and a helper =RAND() column, in an attempt to filter the data, then randomly select from it. The issue I'm finding is that =FILTER does not like to combine properly (although I'm likely doing something wrong). Additionally, this involves copying the formula down to each cell I'd like a new randomly selected option for, which isn't ideal if possible.

Example of required output

ID T/F Number to randomly select? Output
1 TRUE 5 2 [Formula is here and spill down]
2 TRUE 5
3 FALSE 7
4 FALSE 9
5 TRUE 12
6 FALSE
7 TRUE
8 TRUE
9 TRUE
10 FALSE
11 TRUE
12 TRUE

Here is an example of how I'd ideally like the output of the data. The data itself is in A1:B13. I'd enter the number of options to randomly select in C2, then the output would be generated based on a solution contained in D2, which spills down accordingly. The requirements that it only selects from an ID population in column A where the TRUE/FALSE indicator from column B for that ID is TRUE. I'm looking for the solution to this question to be the formula I'd need to put into D2, please.

Extra detail

I'm always looking to improve, so any explanation on how something works is always appreciated, so I don't end up asking the same things again!

I am using MSO 365, but I am restricted to version 2108 due to rollout schedules.

Thanks for any help with this!




How do I randomly fill my list with zeros and ones such that their number is equal?

This is what I am doing right now:

import numpy as np
import matplotlib.pyplot as plt
from math import *

K=np.array([np.random.choice([1,0]) for i in range(20)])
print(K)

The OUTPUT gives:

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

I want to fill this list like above where the positions for ones and zeros are random but the above method does not render them to be equal in number. I understand why this happens. The "choice" randomly chooses from 1 and 0 so there is no reason for them to be equal in number in the list. But if I want them to be randomly chosen and still be equal in number (10 ones and 10 zeros for the above case) what do I do?




mardi 7 juin 2022

How do I loop through dummy data in R to randomly replace a random amount of values with NA using the sample function?

So in the biotech company I work for, we scan for small biomarkers that are present in various sample types from experiments being performed by research institutions. For example, some research institution/department is studying what biomarkers may be present in certain individuals of some population of interest. Perhaps over time, they do this kind of a study three times (not necessarily with the same individuals, though some of the same individuals may be present in the future studies -- this is case by case dependent), and then they want to merge the data into one single, finalized data frame. Sounds easy enough, right? Well, it can be a bit more complicated than just stacking the data sets on top of each other.

As you might imagine, sometimes a biomarker shows up in some individuals and not in others. Furthermore, sometimes, a biomarker shows up solely in one of the sampled populations and not any of the other ones sampled. I'm working on an internal R&D project for my company, and am trying to simulate data that we might get from three separate experiments (which are stored in the three "toy" data frames I've created in the code provided below). If you run what I've created below, it will result in one "all" data frame at the end that consists of 30 observations from 30 (fake) individuals, where each biomarker is a column labeled "x1", "x2", etc. Again, the point here is to try and simulate real data for an internal research project I'm working on. I've tried to simulate the fact that sometimes, a biomarker is present in one set and not all the others. This is why the column names aren't all the same and some have names that aren't present in the others.

# bringning in the best data management package there is!
library(dplyr)

# making a couple toy data frames used to try and create dummy examples of all the merged files
set.seed(42)
toy_df1 <- as.data.frame(matrix(data = rnorm(n = 100, mean = 0, sd = 1), nrow = 10, ncol = 10))
toy_df2 <- as.data.frame(matrix(data = rnorm(n = 100, mean = 0, sd = 1), nrow = 10, ncol = 10))
toy_df3 <- as.data.frame(matrix(data = rnorm(n = 100, mean = 0, sd = 1), nrow = 10, ncol = 10))

names(toy_df1) <- c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10")
names(toy_df2) <- c("x1", "x2", "x3", "x5", "x6", "x7", "x8", "x9", "x10", "x11")
names(toy_df3) <- c("x1", "x3", "x4", "x5", "x7", "x8", "x9", "x10", "x11", "x13")

# adding a dummy SSID to each toy dataframe
toy_df1$SSID <- as.numeric(rep(24001, nrow(toy_df1))) # Sample set ID from the first study
toy_df2$SSID <- as.numeric(rep(24002, nrow(toy_df2))) # Sample set ID from the second study
toy_df3$SSID <- as.numeric(rep(24003, nrow(toy_df3))) # Sample set ID from the third study

# inserting each dummy dataframe into a list object for storage (might be useful later)
toy_data_list <- list(toy_df1, toy_df2, toy_df3)

# merging the toy data sheets into the "Data All"-esque file; this takes each dataframe and stacks them
# and stacks them on top of each other in sequential order of the SSIDs. 
toy_data_all <- bind_rows(toy_df1, toy_df2, toy_df3)

My issue is this: I'm having trouble trying to simulate the randomness of the NA occurrences within each "toy" dataframe. For instance, in toy_df_1, perhaps biomarker x1 was observed in all but the first, third, and seventh individuals. Also still in toy_df_1, perhaps x3 was only observed in only the even numbered observations, so observations 1, 3, 5, 7, and 9, have NA values. Etc.

I don't know how to best simulate this random data in each data frame, per each biomarker, and this is what I'm seeking help/input on here. I have provided below the currently (very rough) code ideas I'm working with. My current idea/thought process is this: I want to loop through each toy data frame stored in this toy dataframe list, which I have named toy_data_list, and then loop through each column within each of these toy data frames and take a random sample of the observations, and replace them with NA. This is the part I am having trouble with the most I think. I don't want the randomly selected amount of observations to always be 3 or 4. Ideally, sometimes it'd be all 10, 0, 1, 5, 3, 2, etc., see what I mean? The below code is my best attempt at doing this but I'm running into issues with that sample() function . If anybody has any better ideas or ways of doing this I'm all ears. Thank you!

# adding NA values to the original toy dataframes to simulate real data
amount_sampled <- c(0:10)

for (i in 1:length(df_list)){
  for (j in 1:nrow(df_list[[i]])){
    
    df_list[[i]][,j][sample(df_list[[i]][,j], size = sample(amount_sampled, 1))] <- NA
    
  }
}