vendredi 31 mars 2023

php - generate a 4 digit number

For the captcha, the code below generates a 5-digit number. I want it to be 4 digits. how can I do it.

// generate random numbers
$sayilar = '';
for ($x = 15; $x <= 95; $x += 20) {
    $sayilar .= ($sayi = rand(0, 9));
    imagechar($image, rand(3, 5), $x, rand(2, 14), $sayi, $textcolor);
}



how do I get to a random index in a object that holds a array of objects and get a specific property and append that property content?

I'm trying to make a trivia game as a project at my bootcamp I'm still new to coding but I get some basic stuff and I want to use Dom manipulation to grab a object from state that holds a questions array of objects and I'm using the form element in html to make the textContent of the label element in the form to be the question property which is a string and evaluate the input to the answer that I put in my trivia question constructor. I have tried everything i learned so far but I'm getting no where.

class Question {
  constructor(question, answer, hint) {
    this.question = question;
    this.answer = answer;
    this.hint = hint;
    this.attempts = 3;
    state.questions.push(this);
  }
}
// helper function for generating a random question from the state index.
function getRandomQuestion() {
  return Math.floor(Math.random() * state.questions.length);
}
function renderQuestion() {

  let currentQuestion = getRandomQuestion();
  for (let i = state.questions.length; i === 0; pocketArray.push(state.questions[currentQuestion])) {
    while (state.questions[currentQuestion].attempts > 0) {
      question.innerText = state.questions[currentQuestion].question;
    }
  }
}
     <form class="current-question">
                <label for="userInput" id="question"></label>
                <input type="text" name="userInput" id="user">
                <button type="button" for="userInput" id="submit">Submit</button>
            </form>



How can I use an rng so that each number that is generated is with a seed that ascends?

I want to use an lfsr to generate a kind of 2d random terrain, where you introduce the xy coordinate to the rng and it takes you the height of the terrain at that point, of course if you use an lfsr, the terrain will be generated with a slightly random pattern , rather linear. How can I modify the x coordinate to introduce it to the rng as a seed and make the pattern random?

I have tried to use trigonometric functions multiplying by x but I don't know if it is the best.




jeudi 30 mars 2023

SAS Create a noise with random realization of a negative binomial distribution in a dataset

I’m working in SAS with a dataset such this:

enter image description here

I would like to introduce a variable, named “noised_y”, such this:

enter image description here

Every value of "noised_y" must be obtained, as a random realization of a negative binomial distribution of mean ugual to the correspondent value of y.

May you suggest a Sas procedure to create a random noise as this?

Thank you very much

G




Algorithm to randomize output order of a short array in Go

The key difference between this question and the lots of duplicated answers is that, the input array is short, only 3 elements. --

Say I have an ordered set of int. The size of array is only 3 (or a bit more). I need to randomize their order and return a new array. Although it is a pure algorithm question, but the prefered answer language is in Go.

However, this is my code:

https://go.dev/play/p/CVu8_Q96-9F

func randShuffle(a []int) {
    rand.Seed(time.Now().UnixNano())
    rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] })
}

And this is one of my test run result:

[2 1 3]
[1 3 2]
[2 1 3]
[2 1 3]
[1 3 2]
[1 2 3]
[2 3 1]

which doesn't seems to be very randomized.

Any good idea to have a better randomization for a short 3-elements array?

BTW,




mercredi 29 mars 2023

Questions about golang's rand package

I've been using and reading about the Golang rand package but I can't find a resource that actually explains what it's doing in a way I can understand.

First, what is really happening when you "seed"? If you are then asking for a random number in a range (for example using rand.Intn(7)), it seems like that should be enough to tell Go what you're looking for, but it's not. What does rand.Seed() contribute?

Here is an example that you can play with here:

func main() {
  rand.Seed(time.Now().UnixNano())
  fmt.Println(rand.Intn(7))
}

I was thinking maybe the "Source" is all possible numbers you could pull from and then something like rand.Intn() gives you a random number from a subset of the Source. So seeding is just defining the Source. But if I try getting a random number from a range outside of the initial seed, it stills works, so that doesn't seem to be right, unless it just excludes the part of the range that doesn't exist. See this example:

func main() {
  rand.Seed(6)
  fmt.Println(rand.Intn(7))
}

And what about this line in the documentation that says:

If Seed is not called, the generator is seeded randomly at program startup.

That doesn't seem to happen because if you don't call rand.Seed() and try to use rand.Intn(), you just get the same thing over and over, similar to if you use a constant with rand.Seed().

Second, the documentation for rand.Intn() says it "panics if n <= 0". I've tested this using the above link and it's not true, it will return 0 without panicking. I actually want to include 0 so this is good but it's not lining up with what the docs say. Is there another, proper way to include 0 when specifying a range? I couldn't find one.

Third, the documentation talks about a "default Source" here. Is that just something that exists without us having to do anything? And then if I want a specific Source I use rand.New() to create one? Why would I want a specific one?

Go's documentation is considered very good and well thought out so I think I must just be missing something here, appreciate anyone's insight!




mardi 28 mars 2023

Why do we use Math.floor() for creating random numbers vs. Math.round() or Math.ceil()

So I am confused why we use Math.floor() for creating random numbers versus Math.round() or Math.ceil().

For example:

var enemyNumber = Math.floor(Math.random() * 4);

Why don't we use var enemyNumber = Math.ceil(Math.random() * 4); or var enemyNumber = Math.ceil(Math.random() * 4);




lundi 27 mars 2023

How to use environment property say “companies” in formula contacts.where('company': ['ABC','HBO']) in workato

How to use environment property say “companies” in formula contacts.where('company': ['ABC','HBO']). I assigned value ‘ABC’, ‘HBO’ to companies property and mapped in above formula it didn’t work

I assigned value ‘ABC’, ‘HBO’ to companies property and mapped in above formula it didn’t work




Simple Slot Machine (Classes)

I finally finished my simple slot machine code, however am struggling to understand classes a little bit. I want to Split this into two classes and not sure how to go about it. My idea is to take the first half which is doing the random generation. Creating a class called Reels, and putting the code in method like public void spin(). Although, when I split it into another class and tried to call the spin method things got crazy... I apologize if this was not the easiest explanation and hope/appreciate any help I can get.

    import java.util.Scanner; 
    import java.util.Random;
    import java.util.Arrays;
       
    
    
    public class LabProgram {
    
    
       public static void main(String[] args) {
          Scanner scnr = new Scanner(System.in);
       
          final int numReels = 3; //Declare how many reels spin on machine
          Random random = new Random(); // Create Random
    
          int[ ] symbols = new int[numReels]; // Create an array of three random numbers
          String[ ] logo = new String[numReels]; // Second Array to assign numbers to symbols
          final String[] allSymbols = {"Cherry", "7", "Grape", "Orange", "Lemon", "Spade", "Club", "Diamond", "Heart", "Ace"}; // A final list of what symbols there are
          
          
          for (int i = 0; i < symbols.length; ++i) { // Loop through the integer list to obtain random numbers
             symbols[ i ] = random.nextInt(10); //Random numbers from 0 - 9
          //System.out.println(symbols[i]); Test to make sure list is looping properly
          }
          for (int i = 0; i < symbols.length; ++i) { // Assign second array to the correct symbol according to number
             logo[i] = allSymbols[symbols[i]];
    }
             
          
       //Test each element in list to make sure obtaining correct values
    //System.out.println("symbol #: " + symbols[0] + " logo: " + logo[0]);
    //System.out.println("symbol #: " + symbols[1] + " logo: " + logo[1]);
    //System.out.println("symbol #: " + symbols[2] + " logo: " + logo[2]);
       
       // Simplify each element by assigning to single letter variables
       int a = symbols[0];
       int b = symbols[1];
       int c = symbols[2];
       
       String answer = "Y"; // Variable to be used in while loop (continue playing or not)
       int userBet; // Variable for amount user bets
       int doub; //Variable for reward when user matches two symbols
       int trip; //Variable for reward when user matches three symbols
       int jack; //Variable for reward when user matches three jackpot symbols
       int amountWon = 0;
       
       System.out.println("Welcome to the Simple Slot Machine! Enter a betting amount to spin!!"); // Print intro to user
       
       do { //do-while loop for when answer variable is Y or y
       userBet = scnr.nextInt(); // Take input for betting amount
       if (userBet < 10) { // Bet must be higher than $10
        System.out.println("Bet must be higher then $10");
       }
       
       if (a != b && a != c && b != c) { // When no symbols match the user loses amount that was bet
          System.out.println("You lost your $" + userBet);
          amountWon -= userBet;
       }
       else if (a == 1 && b == 1 && c == 1) { // When all jackpot symbols match user wins Jackpot and adds to winnings
        jack = userBet * 100;
        System.out.println("Congratulations! You have won with a " + logo[0] + ", " + logo[1] + ", " + logo[2] + " the jackpot of $" + jack);
        amountWon += jack;
       }
       else if (a == b && b == c) { // When three symbols match user wins triple award and adds to winnings
        trip = userBet * 70;
        System.out.println("Congratulations, you have won with a Triple!" + logo[0] + ", " + logo[1] + ", " + logo[2] + " $" + trip); 
        amountWon += trip;
       }
       else if (a == b || a == c || b == c) { // When two symbols match user wins award and add to winnings
        doub = userBet * 30;
        System.out.println("Congratulations, you have won with a Double!" + logo[0] + ", " + logo[1] + ", " + logo[2] + " $" + doub);
        amountWon += doub;
       }
       System.out.println("Continue? Y/N "); // Once awards accounted for ask if player continues or not
       answer = scnr.next();
    } while (answer.equals("y") || answer.equals("Y"));
      if (!answer.equals("Y")) {
         if (amountWon < 0) { //Print statement for when player is in the hold
          System.out.println("You ended losing " + amountWon +" dollars" + ", but people always stop before they hit it big!");   
         }
         else { // Print statement for when player is in positive
        System.out.println("You ended with $" + amountWon + " come back again!"); 
         }
       }
      
       }
          
       }

Better visual of how I am splitting code:

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

public class Reel {
   
   public void spin() {
   final int numReels = 3; //Declare how many reels spin on machine
      Random random = new Random(); // Create Random

      int[ ] symbols = new int[numReels]; // Create an array of three random numbers
      String[ ] logo = new String[numReels]; // Second Array to assign numbers to symbols
      final String[] allSymbols = {"Cherry", "7", "Grape", "Orange", "Lemon", "Spade", "Club", "Diamond", "Heart", "Ace"}; // A final list of what symbols there are
      
      
      for (int i = 0; i < symbols.length; ++i) { // Loop through the integer list to obtain random numbers
         symbols[ i ] = random.nextInt(10); //Random numbers from 0 - 9
      //System.out.println(symbols[i]); Test to make sure list is looping properly
      }
      for (int i = 0; i < symbols.length; ++i) { // Assign second array to the correct symbol according to number
         logo[i] = allSymbols[symbols[i]];
}
}
   
}

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


public class LabProgram {


   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
   Reel action = new Reel();
         
   action.spin();   
   //Test each element in list to make sure obtaining correct values
//System.out.println("symbol #: " + symbols[0] + " logo: " + logo[0]);
//System.out.println("symbol #: " + symbols[1] + " logo: " + logo[1]);
//System.out.println("symbol #: " + symbols[2] + " logo: " + logo[2]);
   
   // Simplify each element by assigning to single letter variables
   int a = symbols[0];
   int b = symbols[1];
   int c = symbols[2];
   
   String answer = "Y"; // Variable to be used in while loop (continue playing or not)
   int userBet; // Variable for amount user bets
   int doub; //Variable for reward when user matches two symbols
   int trip; //Variable for reward when user matches three symbols
   int jack; //Variable for reward when user matches three jackpot symbols
   int amountWon = 0;
   
   System.out.println("Welcome to the Simple Slot Machine! Enter a betting amount to spin!!"); // Print intro to user
   
   do { //do-while loop for when answer variable is Y or y
   userBet = scnr.nextInt(); // Take input for betting amount
   if (userBet < 10) { // Bet must be higher than $10
    System.out.println("Bet must be higher then $10");
   }
   
   if (a != b && a != c && b != c) { // When no symbols match the user loses amount that was bet
      System.out.println("You lost your $" + userBet);
      amountWon -= userBet;
   }
   else if (a == 1 && b == 1 && c == 1) { // When all jackpot symbols match user wins Jackpot and adds to winnings
    jack = userBet * 100;
    System.out.println("Congratulations! You have won with a " + logo[0] + ", " + logo[1] + ", " + logo[2] + " the jackpot of $" + jack);
    amountWon += jack;
   }
   else if (a == b && b == c) { // When three symbols match user wins triple award and adds to winnings
    trip = userBet * 70;
    System.out.println("Congratulations, you have won with a Triple!" + logo[0] + ", " + logo[1] + ", " + logo[2] + " $" + trip); 
    amountWon += trip;
   }
   else if (a == b || a == c || b == c) { // When two symbols match user wins award and add to winnings
    doub = userBet * 30;
    System.out.println("Congratulations, you have won with a Double!" + logo[0] + ", " + logo[1] + ", " + logo[2] + " $" + doub);
    amountWon += doub;
   }
   System.out.println("Continue? Y/N "); // Once awards accounted for ask if player continues or not
   answer = scnr.next();
} while (answer.equals("y") || answer.equals("Y"));
  if (!answer.equals("Y")) {
     if (amountWon < 0) { //Print statement for when player is in the hold
      System.out.println("You ended losing " + amountWon +" dollars" + ", but people always stop before they hit it big!");   
     }
     else { // Print statement for when player is in positive
    System.out.println("You ended with $" + amountWon + " come back again!"); 
     }
   }
  
   }
      
   }



dimanche 26 mars 2023

How to generate random numbers with view functions of Python Flask?

I´m trying generate new random numbers with view functions in Python Flask, but the numbers are always the same in the same web session.

Here a simplified code version:

def random_expression():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    operator = random.choice(["+", "-", "*", "/"])
    return f"{num1} {operator} {num2}"

class MyForm(FlaskForm):
    expression = IntegerField(label=random_expression(),default=None)
    

@app.route("/", methods=['GET','POST'])
def index():
    form = MyForm()
    return render_template("index.html",form=form)

It´s like the random_expression() was executed only once no matter how many times the view function index() is called.




Very long startup time in a program simulating a matrix digital rain using `curses.h` library and random numbers

I am trying to write a program simulating the matrix digital rain using curses.h library and random numbers. The program seems to be working but the startup of the program is very slow (up to 10 seconds on MacOS 11.6.1, 2.8GHz Quad-Core Intel Core i7). Why is that? Is it relate to how random numbers are used? How can I improve the code so that the start of the program becomes snappy

Here is the code:

/*matrix_digital_rain.c*/

#include <curses.h>
#include <unistd.h>
#include <locale.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "set_characters.h"
#include "hyperparameters.h"
#include "functions.h"

int main() {
  srand((unsigned) time(NULL));   // Initialization, should only be called once.
  setlocale(LC_ALL, "");
  int max_y = 0, max_x = 0;
  Drop_init_vals drop_init_vals01;
  //Drop_init_vals drop_init_vals02;
  //Drop_init_vals drop_init_vals03;
  //Drop_init_vals drop_init_vals04;
  //Drop_init_vals drop_init_vals05;
  //Drop_init_vals drop_init_vals06;
  //Drop_init_vals drop_init_vals07;
  //Drop_init_vals drop_init_vals08;
  //Drop_init_vals drop_init_vals09;

  int iter_start01 = rand() % ITER_START_RANGE; 
  //int iter_start02 = rand() % ITER_START_RANGE; 
  //int iter_start03 = rand() % ITER_START_RANGE; 
  //int iter_start04 = rand() % ITER_START_RANGE; 
  //int iter_start05 = rand() % ITER_START_RANGE; 
  //int iter_start06 = rand() % ITER_START_RANGE; 
  //int iter_start07 = rand() % ITER_START_RANGE; 
  //int iter_start08 = rand() % ITER_START_RANGE; 
  //int iter_start09 = rand() % ITER_START_RANGE; 

  int iter = 0;
 
  initscr();
  noecho();
  curs_set(FALSE);
  start_color();
  init_color(CUSTOM_GREEN1, 90, 280, 90);
  init_color(CUSTOM_GREEN2, 100, 500, 100);
  init_color(CUSTOM_GREEN3, 100, 900, 100);
  init_color(COLOR_BLACK, 0, 0, 0);

  char char_set[DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING] = {SET_CHAR};
  char str_display[DIM_0_ARRAY_STRING][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING];
  for (int i = 0; i<DIM_0_ARRAY_STRING; i++){
    for (int j = 0; j<LEN_STRING_DISPLAY; j++){
      strcpy(str_display[i][j], char_set[rand() % N_COMMAS]);
    }
  }

  while(1) 
  {
    getmaxyx(stdscr, max_y, max_x);
 
    clear();

    if (iter % ITER_REFRESH == iter_start01){
      drop_init_vals01 = random_drop_init_vals(drop_init_vals01, iter);
      drop_init_vals01.n_dim_str = 0;
    }

    print_n_string_from_string_array_struct(
      drop_init_vals01,
      str_display,
      iter
    );

/*
    if (iter % ITER_REFRESH == iter_start02){
      drop_init_vals02 = random_drop_init_vals(drop_init_vals02, iter);
      drop_init_vals02.n_dim_str = 1;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals02,
      str_display,
      iter
    );


    if (iter % ITER_REFRESH == iter_start03){
      drop_init_vals03 = random_drop_init_vals(drop_init_vals03, iter);
      drop_init_vals03.n_dim_str = 2;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals03,
      str_display,
      iter
    );

    if (iter % ITER_REFRESH == iter_start04){
      drop_init_vals04 = random_drop_init_vals(drop_init_vals04, iter);
      drop_init_vals04.n_dim_str = 3;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals04,
      str_display,
      iter
    );


    if (iter % ITER_REFRESH == iter_start05){
      drop_init_vals05 = random_drop_init_vals(drop_init_vals05, iter);
      drop_init_vals05.n_dim_str = 4;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals05,
      str_display,
      iter
    );


    if (iter % ITER_REFRESH == iter_start06){
      drop_init_vals06 = random_drop_init_vals(drop_init_vals06, iter);
      drop_init_vals06.n_dim_str = 5;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals06,
      str_display,
      iter
    );


    if (iter % ITER_REFRESH == iter_start07){
      drop_init_vals07 = random_drop_init_vals(drop_init_vals07, iter);
      drop_init_vals07.n_dim_str = 6;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals07,
      str_display,
      iter
    );

    if (iter % ITER_REFRESH == iter_start08){
      drop_init_vals08 = random_drop_init_vals(drop_init_vals08, iter);
      drop_init_vals08.n_dim_str = 7;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals08,
      str_display,
      iter
    );

    if (iter % ITER_REFRESH == iter_start09){
      drop_init_vals09 = random_drop_init_vals(drop_init_vals09, iter);
      drop_init_vals09.n_dim_str = 8;
    }
    print_n_string_from_string_array_struct(
      drop_init_vals09,
      str_display,
      iter
    );

*/

    iter++;

    refresh();
    usleep(DELAY);
 
  }
  attron(COLOR_PAIR(1));
  attron(COLOR_PAIR(2));
  attron(COLOR_PAIR(3));
 
  endwin();
  refresh();
  use_default_colors();
}
/*functions.c*/

#include "hyperparameters.h"
#include "functions.h"
#include <curses.h>
#include <time.h>
#include <stdlib.h>


void print_GREEN1(int y1, int x1, int i, int n_string, int n_dim_str, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING])
{
  init_pair(1, CUSTOM_GREEN1, COLOR_BLACK);
  attron(COLOR_PAIR(1));
  mvprintw(y1+i-n_string, x1, str_display[n_dim_str][i]);
}

void print_GREEN2(int y1, int x1, int i, int n_string, int n_dim_str, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING])
{
  init_pair(2, CUSTOM_GREEN2, COLOR_BLACK);
  attron(COLOR_PAIR(2));
  mvprintw(y1+i-n_string, x1, str_display[n_dim_str][i]);
}

void print_GREEN3(int y1, int x1, int i, int n_string, int n_dim_str, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING])
{
  init_pair(3, CUSTOM_GREEN3, COLOR_BLACK);
  attron(COLOR_PAIR(3));
  mvprintw(y1+i-n_string, x1, str_display[n_dim_str][i]);
}


Drop_init_vals random_drop_init_vals(Drop_init_vals drop_init_vals, int iter)
{
  

  struct timespec ts;
  clock_gettime(CLOCK_MONOTONIC, &ts);

  srand((unsigned int) (time_t)ts.tv_nsec);

  drop_init_vals.y1 = 0;
  drop_init_vals.x1 = rand() % X1_RANGE;
  drop_init_vals.n_string = 5 + rand() % N_STRING_RANGE;
  drop_init_vals.iter_init = iter;
  return drop_init_vals;
}

void print_n_string_from_string_array_struct(Drop_init_vals drop_init_vals, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING], int iter)
{
  int y1 = drop_init_vals.y1;
  int x1 = drop_init_vals.x1;
  int n_string = drop_init_vals.n_string;
  int n_dim_str = drop_init_vals.n_dim_str;
  int y_start = iter - drop_init_vals.iter_init;


  int count = 0;
  for (int i=y_start; i<y_start+n_string; i++)
  {
    if (count == 0 || count == 1){
      print_GREEN1(y1, x1, i, n_string, n_dim_str, &str_display[n_dim_str]);
    }
    else if (count == 2 || count == 3 || count == 4){
      print_GREEN2(y1, x1, i, n_string, n_dim_str, &str_display[n_dim_str]);
    }
    else{
      print_GREEN3(y1, x1, i, n_string, n_dim_str, &str_display[n_dim_str]);
    }
    count++;
  }
}

//int gen_rand_int(){
//  struct timespec ts;
//  clock_gettime(CLOCK_MONOTONIC, &ts);
//
//  srand((unsigned int) (time_t)ts.tv_nsec);
//
//  return rand();
//}
/*functions.h*/

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

typedef struct {
  int x1, y1, n_string, n_dim_str, iter_init; 
} Drop_init_vals ;


int gen_rand_int(void);
void print_n_string_from_string_array_struct(Drop_init_vals drop_init_vals, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING], int iter);
Drop_init_vals random_drop_init_vals(Drop_init_vals drop_init_vals, int iter);

void print_GREEN1(int y1, int x1, int i, int n_string, int n_dim_str, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING]);
void print_GREEN2(int y1, int x1, int i, int n_string, int n_dim_str, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING]);
void print_GREEN3(int y1, int x1, int i, int n_string, int n_dim_str, char str_display[][DIM_1_ARRAY_STRING][DIM_2_ARRAY_STRING]);



#endif
/*hyperparameters.c*/

#ifndef HYPERPARAMETERS_H
#define HYPERPARAMETERS_H

#define DELAY 60000 //480000
#define CUSTOM_GREEN1 8
#define CUSTOM_GREEN2 9
#define CUSTOM_GREEN3 10
#define COLOR_BLACK 0
#define DIM_0_ARRAY_STRING 20
#define DIM_1_ARRAY_STRING 200
#define DIM_2_ARRAY_STRING 4
#define LEN_STRING_DISPLAY 100 
#define MAX_Y 100 
#define MAX_X 100 
#define N_STRING_MAX 20

#define Y1_RANGE 10
#define X1_RANGE 30
#define N_STRING_RANGE 5
#define Y_START_RANGE 15
#define ITER_REFRESH 60
#define ITER_START_RANGE 25


#endif
/*set_characters.c*/

#ifndef SET_CHARACTERS_H
#define SET_CHARACTERS_H

#define N_COMMAS 56

#define SET_CHAR "ㇰ", "ㇱ", "ㇲ","ㇳ","ㇴ","ㇵ","ㇶ","ㇷ","ㇸ","ㇹ","ㇺ","ㇻ","ㇼ","ㇽ","ㇾ", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "<", "=", ">", "T", "H","E", "M", "A", "T", "R", "I", "X", "Z", ":", "・", ".", "=", "*", "+", "-", "<", ">", "¦", "|", "#", "_"


#endif
#makefile

CC = gcc 
CFLAGS = -Wextra -Wall -Wfloat-equal -Wundef -Wshadow -Wpointer-arith -Wcast-align -Wstrict-prototypes -Wstrict-overflow=5 -Wwrite-strings -Waggregate-return -Wcast-qual -Wswitch-default -Wswitch-enum -Wconversion -Wunreachable-code -pedantic -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition

BINC=matrix_digital_rain

allc: $(BINC) 

$(BINC): $(BINC).c $(BINC).o functions.o
    $(CC) $(CFLAGS) $(BINC).o functions.o -o $@ -lncurses

$(BINC).o: $(BINC).c set_characters.h hyperparameters.h
    $(CC) $(CFLAGS) -c $(BINC).c

functions.o: functions.c functions.h
    $(CC) $(CFLAGS) -c functions.c 

clean:
    $(RM) -rf $(BINC) *.dSYM *.o

runc: allc
    ./$(BINC)



samedi 25 mars 2023

Is there any way or algorithm to generate unique random numbers without store?

I wanna create unique random numbers with size of m and range of 0 to n-1. I think there are 2 traditional ways to do this as below.

val m = 1000
val n = 100
val set = mutableSetOf<Int>()

while (set.size < m) {
    val v = Random.nextInt(n)
    set.add(v)
}
val m = 1000
val n = 100
val set = (0..m).shuffled().subList(0, n).toSet()

Both are good ways to get unique random numbers, but they need some storage to check if numbers are unique or not.

However, I need to generate unique random numbers without any space, because the m or n would be quite big(e.g. a billion). And note that the generated numbers do not have to be same every time the code is executed.(like Random with seed). Is there any algorithm for this ?




How should a random function be chosen to be run?

I have several functions and want to choose one randomly to run. I am using Go.

Currently I am using a switch statement. This does not feel ideal because if I want to add another function I have to increment the rand.intn() and add a new case. Removing a case is even worse because then I also have to decrement all cases after that.

switch rand.Intn(5) {
case 0:
    function1()
case 1:
    function2()
case 2:
    function3()
case 3:
    function4()
case 4:
    function5()
}



vendredi 24 mars 2023

Random numbers between -1 and 1 summing to 0

With R, how to generate n random numbers x_1, ..., x_n that lie between -1 and 1 and that sum to 0?

What about the generalization to another sum and another range?




Why are the sums of randomly rolled dice in Python always 7? [closed]

import random

dice=[1,2,3,4,5,6]

possibilities=[]

def most_frequent(List):
    counter = 0
    num = List[0]

    for i in List:
        curr_frequency = List.count(i)
        if(curr_frequency> counter):
            counter = curr_frequency
            num = i

    return num

for i in range(1000):
    b=random.choice(dice) 
    c=random.choice(dice)
    possibilities.append(b+c)

print(most_frequent(possibilities))

I rolled random dice 1000 times. I listed the sum of the two dice. and it was the 7th most popping up almost every time. Anyone know why? very rarely 6 and 8 came out. because they are close to 7.




jeudi 23 mars 2023

P5.JS - How can I make an image array without repeating?

I made a falling game with images. When I click the x box button on the image, it generates another image. I can't figure out how I can make the images non-repeatable. So far, I have 6 png images, and they repeat when I play the game. I used for loop in the function preload. Please advise.

Here is my code.

//variables 
let x = 10;
let y = 200;
let iw = 300;
let ih = 200;
let score = 0;
let speed = 1.5;
let screen = 0;
let bw = 24;
let bh = 20;
let slider;
var timerValue = 60;

// let ads;
let ads = [];

function preload() {
  for (let i = 0; i < 6; i++) {
    // ads[i] = loadImage(`ads/ad${i}.png`);
    ads[i] = loadImage("ads/ad" + i + ".png");
  }
}

function setup() {
  createCanvas(windowWidth, windowHeight);
  for (let i = 0; i < 1; i++){
    img = random(ads);
  }
  button = createButton("X");
  button.size(bw,bh);
  button.mouseClicked(changeImage);
  x1 = random(windowWidth-410);
  
  slider = createSlider(0, 255, 100);
  slider.position(18, 40);
  slider.style('width', '80px');
  
  setInterval(timeIt, 1000);
}

//which screen to display
function draw() {
  let val = slider.value();
  background(val);
  
  if (screen === 0) {
    startScreen();
  }
  if (screen === 1) {
    startGame();
  }
  if (screen === 2) {
    endGame();
  }
}

//what happens when you tap on the canvas 
function mousePressed() {
  if (screen === 0) {
    screen = 1;
  }
  if (screen === 2) {
    screen = 0;
  }  
}


//what to display at the start
function startScreen() {
  background(69);
  fill(255);
  textAlign(CENTER);
  textSize(20);
  text("IMAGE FALLING GAME", width / 2, height / 2);
  text("Click To Start", width / 2, height / 2 + 30);

  restart();
}

//Function for the game
function startGame() {
  
  if (timerValue >= 10) {
    text("0:" + timerValue, width / 2, height / 2);
  }
  if (timerValue < 10) {
    text('0:0' + timerValue, width / 2, height / 2);
  }
  if (timerValue == 0) {
    text('game over', width / 2, height / 2 + 15);
  }
  
  //score text
  fill(255);
  noStroke();
  textSize(20);
  textStyle(NORMAL);
  text("Score: " + score, 60, 30);

//change the y value
  y += speed;
  image(img, x1, y-ih, iw, ih);
  // button.position(iw-bw,y);
  button.show();
  // button.position(x1+iw-bw,y-ih);
  button.position(x1+iw-bw,y-ih);  

  if (y > height) {
    screen = 2;
  }
}

//mouseCkicked event
function changeImage() {
    for (let i = 0; i < 1; i++){
      img = random(ads);
    }
  
    y = 0;
    score++;
    // speed += 0.5;
    speed += 0.1;
  
    let xpos = random(width);
    // let xpos = random(x);
    x1 = xpos;
    button.position(xpos, y);
}

function timeIt() {
  if (timerValue > 0) {
    timerValue--;
  }
}

//endgame screen 
function endGame() {
  background(255, 0, 0);
  noStroke();
  textAlign(CENTER);
  textSize(20);
  text("You Lost", width / 2, height / 2);
  text("Score :" + score, width / 2, height / 2 + 20);
  text("Click To Play Again", width / 2, height / 2 + 40);
  button.hide();
  timerValue = 60;
}

//restart function 
function restart() {
  y = 0;
  speed = 1.5;
  score = 0;
}

function reSet() {
  score = 0;
}



how do i make a random number in python using intervals of 10 [duplicate]

I am currently using random.randint to generate random numbers, but I would like that it will print out numbers in the intervals of 10

eg. 10, 20, 30, 40, 50...

how would I do this?

I have tried: random.randint()

how do I make it generate in multiples of 10 like this?




mercredi 22 mars 2023

How to generate a list of random numbers between -1 and 1 with sum 0 in Julia?

I'm currently working on implementing a simple genetic algorithm in Julia, and I need a way to generate n random numbers between -1 and 1 with a sum of 0. Ideally, the distribution would be uniformly random, but it would still work as long as it's a reasonable approximation. A search on Google returns these two posts (1, 2) which were related but not exactly what I'm looking for.

I've reduced the problem to generating n numbers in the range [0, 1] with sum n/2, but I'm not sure where to go from there.




Random yet balanced assignment of a binary variable with a map function

i am quite new to R and struggle with assigning a binary variable (domain; which can either be "social" or "analytical") to every row in my dataframe. I need it to add another column called domain and randomly assigned a value to every row. Furthermore, the assignment needs to be balanced in total and especially in the rows mentioned in Neutral. I came up with this code, which does randomly assign the values, but not in a balanced way. The idea was that it creates a score and if this reaches the maximum (for the neutral condition 6, for the rest 12), only the other condition is applied. However, as apparent by the resulting data, this approach does not work. I believe the issue is somehow, that the scores are not updated within the map function. Can anybody guide me how to solve this.

#Assign analytical or social task
Neutral <- c(1, 2, 5, 10, 11, 14, 19, 20, 23, 28, 29, 32)
merged_df <- merged_df %>%
  mutate(domain = NA) %>%
  { social_score <- 0
  analytical_score <- 0
  social_score_C <- 0
  analytical_score_C <- 0
  mutate(., domain = map(1:36, ~{
    if(.x %in% Neutral){
      A <- sample(c("social","analytical"), 1)
      while((A == "social" & social_score >= 6) || (A == "analytical" & analytical_score >= 6)){
        A <- sample(c("social","analytical"), 1)
      }
      if(A == "social"){
        social_score <- social_score + 1
      } else {
        analytical_score <- analytical_score + 1
      }
    } else {
      A <- sample(c("social","analytical"), 1)
      while((A == "social" & social_score_C >= 12) || (A == "analytical" & analytical_score_C >= 12)){
        A <- sample(c("social","analytical"), 1)
      }
      if(A == "social"){
        social_score_C <- social_score_C + 1
      } else {
        analytical_score_C <- analytical_score_C + 1
      }
    }
    return(A)
    print(analytical_score)
    print(analytical_score_C)
  }))
  }

I expected it to randomly assign the values "social" or "analytical" to my dataframe while making sure, that both the total number as well as the number in the "neutral" lines is balanced. However, I was not capable of coming up with a balanced way.




How can I make it so a global variable with "math.random()" will give me a new number every time? (Lua)

Every time I use a variable (eggs, spam, hams, and yams) and use a random function from the math library (math.random(100)) in Lua, it keeps giving the same exact number it randomized the first time. How can I edit the code so it will give a new randomized integer every time it is run?

spam = math.random(100)
eggs = math.random(100)
yams = math.random(100)
hams = math.random(100)

if eggs > spam then
  print("eggs are better than spam")
end

if spam > eggs then
  print("spam is better than eggs")
end

if yams > hams then
  print("yams are better than hams")
end

if hams > yams then
  print("hams are better than yams")
end

print(spam)
print(hams)
print(eggs)
print(yams)

I Tried using a goto function to a label, but Lua didn't recognize Label. Like this:

:: Label ::
--further code
goto Label



mardi 21 mars 2023

Generate random 2D polygons

I would like to generate some random shapes that are regular polygons with right angled (Like a floor plan) only.

I'm not sure how to approach this problem. One approach is to train a GAN model to do it but is there a algorithm to do that? I was thinking to generate as follows

enter image description here

Any help is appreciated.




Trying to create a list of random floating number sums

I am trying to create a list of numbers, which are created as follows: A sum of 12 random numbers between 0 and 1 and subtract 6 from it. This counts as 1 random value which I will call y. I'm trying to create a list of random y values, which once I succeed in making, will create a histogram from this list to check the mean value theorem. However, when I try running the code I have pasted below, I get a list of 10 repeated values for y, when I'm trying to get 10 random values. How can I fix this code?

import numpy as np
import math
import random

def makelist(x,minnum,maxnum):
    l = []
    for col in range(x):
        l.append(random.uniform(minnum,maxnum))
    return l

def ysum(x,minnum,maxnum):
    m = makelist(x,minnum,maxnum)
    n = []
    n.append(math.fsum(m)-6)
    return n

def yhist(x,y,minnum,maxnum):
    h = []
    f = ysum(x,minnum,maxnum)
    for i in range(y):
        h.append(f)
    return h

print(yhist(12,10,0,1))

Attempted to create random number generation values appended to list, however resulted in repeated numbers.




lundi 20 mars 2023

Looping over a dictionary of random values... not pulling random values

Making a memory game for a class. Saved a dictionary of random shapes and colors for users to memorize. Each "round" is supposed to add on an additional shape. Wanted to give option to repeat a round, but I didn't realize if you loop over a dictionary with random.choice values, they would not be random every time. Is there a way around this? Or should I not give an option to play the same round...

def play_rounds(rounds_dict):
  user_name = intro()
  print()
  i = 1
  total_score = 0
  while i<=len(rounds_dict):
    round_score = 0
    print()
    print(f"Round {i}")
    print()
    time.sleep(1)
    for index, word in enumerate(rounds_dict[i]):
      if (index == 0) or (index % 2 == 0):
        make_shape(rounds_dict[i][index],rounds_dict[i][index+1])
    x=1
    for index, word in enumerate(rounds_dict[i]):
      if (index == 0) or (index % 2 == 0):
        added_score = user_input_check(rounds_dict[i][index],rounds_dict[i][index+1], place[x], round_score)
        x = x+1
        round_score = added_score
        print(f"Your current score is {added_score} out of {int(len(rounds_dict[i])/2)} in round {i}!")
    time.sleep(.5)
    total_score = total_score + round_score
    print()
    print(f"The correct sequence for Round {i} was: {rounds_dict[i]}")
    if added_score == len(rounds_dict[i])/2:
      print()
      print(f"Wow, {user_name}! You got them all right! That's impressive. If I were you, I would go to the next round. ")
    elif added_score > 0.5*(len(rounds_dict[i])/2) and added_score < len(rounds_dict[i])/2:
      print()
      print("Not too shabby, but you can do better!")
    elif added_score <= 0.5*(len(rounds_dict[i])/2):
      print()
      print(f"Don't be mad, {user_name}... but there's room for improvement... maybe you should try this round again!")
    # print(f"You have scored {total_score} points total!")
    while True:
      print()
      play_again = input("Do you want to play the same round, play the next round, or quit? Enter 'same', 'next', or 'quit'. > ")
      if play_again.lower() != "same" and play_again.lower() != "next" and play_again.lower() != "quit":
        print("That wasn't an option... please select the same round, the next round, or quit by entering 'same', 'next', or 'quit'.")
      elif play_again.lower() == "next":
        i = i+1
        break
      elif play_again.lower() == "same":
        break
      elif play_again.lower() == "quit":
        print(f"Goodbye {user_name}! Thanks for playing.")
        break
    if play_again.lower() == "quit":
      break

Tried restructuring and redoing loops. Not sure there is a way around this. Please help.




How do I generate a random number between min and max?

  1. I only have information on the minimum, maximum and median values. Can this be used to generate random numbers that satisfy a normal distribution?

  2. There is only information on the minimum, maximum, and median values ​​of PMA, WT, and SCR, respectively. Each random number is generated and used as a value for one patient. However, there seems to be a correlation of PMA, WT and SCR. Is it possible to generate a random number that satisfies all of the above conditions in the absence of information about correlation?

i have no idea




Smart Python random hexadecimal in Rust?

Python has a very convenient way to get cryptographically secure random hexadecimal; secrets.token_hex(n)

So by running secrets.token_hex(8) you get 16 hexadecimal, secrets.token_hex(12) gives 24 hexadecimal and so on. There is basically no upper lever. The number in the parentheses is in bytes.

My question, as recently started to learn Rust, is if there is a similar smart way to get a very high randomized hexadecimal output?

In Python:

import secrets


for x in range(1):
    xxx = secrets.token_hex(8)
   



dimanche 19 mars 2023

The sorted out put is not correct. It didn't perform ascending sort

I don't know what is wrong with my code. can some help me correct it. The sorted out should be in ascending order

#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>

using namespace std;

void slowSort(vector<int>& a, int i, int j) {
    if (i >= j)
    return;
    int m = (i + j) / 2;
    slowSort(a, i, m);
    slowSort(a, m + 1, j);
    if (a[i] > a[j] && i < j)
    swap(a[i], a[j]);
}

int main() {
    srand(time(0));
    vector<int> a(500);
    for (int i = 0; i < 500; i++) {
        a[i] = rand() % 500; // generate random integers between 0 and 999
    }
    int i = rand() % 500; // generate random index i
    int j = rand() % 500; // generate random index j
    cout << "Before sorting:" << endl;
    for (int x : a) {
        cout << x << " ";
    }
    cout << endl;
    slowSort(a, 0, 999);
    if (i < j && a[i] > a[j]) swap(a[i], a[j]); // swap i and j if necessary
    cout << "After sorting:" << endl;
    for (int x : a) {
        cout << x << " ";
    }
    cout << endl;
    return 0;
}

I don't know what is wrong with my code. can some help me correct it. The sorted out should be in ascending order




I can't randomize numbers for my numerical memory test

I am doing a program similar to the numeric memory test in Human Benchmark. Everything is alright except for the sequence randomization. It keeps displaying one single number, although it randomizes every new test, and adding onto that. Here's my code:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class numerical extends Thread implements ActionListener {
    Random random = new Random(); 
    ArrayList<Integer> number = new ArrayList<Integer>();
    StringBuffer string = new StringBuffer();
    int length = 1;
    boolean gameEnded = false, wait = true;

    JFrame frame = new JFrame("Numerical Memory");
    JPanel top = new JPanel();
    JPanel bottom = new JPanel();
    JLabel title;
    JLabel output = new JLabel();
    JTextField input;
    JButton button1 = new JButton(), button2 = new JButton();

    public numerical() throws InterruptedException {
        while (gameEnded == false) {
            wait = true;
            for (int i = 0; i < length; i++) {
                number.add(Math.abs(random.nextInt() % 9)); 
                System.out.println(number.get(i));
                string.append(number.get(i)); 
            }

            frame.setLayout(null); 
            frame.setSize(500, 300); 
            frame.setVisible(true); 
 
            title = new JLabel("Remember the number:"); 
            input = new JTextField(string.toString()); 
            input.setEditable(false);

            top.add(title);
            top.add(input);
            top.setLayout(new GridLayout(2, 1));
            top.setBounds(0, 0, 500, 200);

            bottom.setLayout(new GridLayout(1, 3));
            bottom.setBounds(0, 210, 500, 40);

            frame.add(top);
            frame.add(bottom);

            frame.revalidate();
            frame.repaint();

            Thread.sleep(length*1500);

            title.setText("What was the number?"); 
            
            input.setText("");
            input.setEditable(true);

            button1 = new JButton("Submit");
            button1.addActionListener(this);
            button1.setActionCommand("submit");

            output.setVisible(false);
            button2.setVisible(false);

            bottom.add(output);
            bottom.add(button1);
            bottom.add(button2); 

            frame.revalidate();
            frame.repaint();

            while (wait == true) {
                System.out.print("");
            }
            
            top.remove(title);
            top.remove(input);
            bottom.remove(output);
            bottom.remove(button1);
            bottom.remove(button2);
            frame.remove(top);
            frame.remove(bottom);

            frame.revalidate();
            frame.repaint();
        }
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand() == "submit") {
            int x = Integer.parseInt(input.getText());
            int y = Integer.parseInt(string.toString());
            System.out.println("Input: " + x);
            System.out.println("Number: " + y);
            if (x == y) {
                output.setText("CORRECT!");
                button1.setText("Next");
                button1.setActionCommand("next");
            }
            else {
                button2.setVisible(true);
                output.setText("INCORRECT!");
                button1.setText("Retry");
                button1.setActionCommand("retry");
                button2.setText("Back");
            }
        }
        if (e.getActionCommand() == "next") {
            wait = false;
        }
        if (e.getActionCommand() == "retry") {
            wait = false;
            length = 0;
        }
        if (e.getSource() == button2) {
            wait = false;
            frame.dispose();
        }

    }

    public static void main(String[] args) {
        try {
            new numerical();
        }
        catch (InterruptedException exception) {
            exception.printStackTrace();
        }
    }
}

I tried thread.sleep at first but later found out it was incompatible with swing so I had to change it, and it resulted to this. Before changing it, it wasn't any better. The numbers were just stacking. How can I randomize my numbers?




I have a problem with using Random in a for loop

I have this code

self.savage_ite = ["Can't live without it", "out for the night", "Creepin"," My choppa hate niggas", "Rich nigga shit", "Slidin","Umbrella", "rockstar"]

for i in range(6):
            element = random.choice(self.savage_ite)
            self.savage_set.append(element)
            self.savage_ite.remove(element)

And I keep getting this error

  File "c:\Users\Edwin\Desktop\caca.py", line 8, in <module>
    savage = setlist.create_savage_set()
  File "c:\Users\Edwin\Desktop\real.py", line 37, in create_savage_set
    element = random.choice(self.savage_ite)
  File "C:\Users\Edwin\anaconda3\lib\random.py", line 346, in choice
    return seq[self._randbelow(len(seq))]
IndexError: list index out of range

Is the problem with my code or without the random module?




vendredi 17 mars 2023

I have two exponential functions, how can I generate any exponential function within the range of the two functions?

I have two exponential function like: A1(1/λ)^k1, and A2(1/λ)^k2 how can I find any exponential function within the range of the two functions? The function we need also follow this form. For example: Ax(1/λ)^kx, which Ax and kx are the value I want to know.

enter image description here

Here is my pseudo code:

def fun_random_gen(fun_upper_bound, fun_lower_bound)
    generate Ax(1/λ)^kx within fun_upper_bound, fun_lower_bound
    return Ax, kx

Appreciate !




jeudi 16 mars 2023

Conditional random sampling: annual to monthly

I have a bunch of annual numbers for X[, 1], X[, 2], ..., X[, numberAssetClasses].

I want to generate random identically distributed conditional multi-normal monthly numbers Y that (summed) match the annual numbers (of each year) but are based on an unconditional distribution.

I think my trouble stems from not knowing how to set the unconditional covariance between the monthly Y[, i]s, derived from the covariance matrix for the annual Xs. (Marked "This seems suspect".)

Here is my code. I hope it would yield similar correlation matrices. It doesn't. Any ideas?

library(mvtnorm)

numberPeriods <- 1000
numberAssetClasses <- 5
numberSubs <- 12

set.seed(42)

X <- matrix(rnorm(numberAssetClasses*numberPeriods, 10, 15*sqrt(12)),
           nrow = numberPeriods)

meanX <- c(rep(0, numberAssetClasses))
for (i in 1:numberAssetClasses){
  meanX[i] <- mean(X[, i])
}

covX <- cov(X)

covX

meanY <- c(rep(0, (numberSubs-1)*numberAssetClasses))
for (i in 1:numberAssetClasses){
  meanY[((i-1)*(numberSubs-1)+1):((i)*(numberSubs-1))] <-
    meanX[i]/numberSubs
}

covY <- covX
for (i in 1:numberAssetClasses){
  for (j in 1:numberAssetClasses){
    if (i == j){
      covY[i, j] <- covX[i, j] / numberSubs
    } else {
      covY[i, j] <- covX[i, j] / numberSubs # This seems suspect
    }
  }
}

bigSigma <- matrix(0.0, nrow = (numberAssetClasses)*(numberSubs-1),
                   ncol = (numberAssetClasses)*(numberSubs-1))
for (i in 1:numberAssetClasses){
  for (j in 1:numberAssetClasses){
    if (i == j){
      bigSigma[((i-1)*(numberSubs-1)+1):((i)*(numberSubs-1)),
               ((j-1)*(numberSubs-1)+1):((j)*(numberSubs-1))] <-
        covY[i, j]*(diag(numberSubs-1)-matrix(1/numberSubs, numberSubs-1, numberSubs-1))
    } else {
      bigSigma[((i-1)*(numberSubs-1)+1):((i)*(numberSubs-1)),
               ((j-1)*(numberSubs-1)+1):((j)*(numberSubs-1))] <-
        covY[i, j]*diag(numberSubs-1)      
    }
  }
}

Y <- matrix(0.0, nrow = numberSubs*numberPeriods, ncol = numberAssetClasses)
for (m in 1:numberPeriods){
  for (n in 1:(numberSubs-1)){
    Y[((m-1)*numberSubs+1):((m)*numberSubs-1),
      (1:numberAssetClasses)] <-
      matrix(rmvnorm(1, meanY, bigSigma), ncol = numberAssetClasses)
  }
  for (i in 1:numberAssetClasses){
    Y[m*numberSubs, i] <- numberSubs*meanY[(i-1)*(numberSubs-1)+1] -
      sum(Y[((m-1)*numberSubs+1):((m)*numberSubs-1), i])
  }
}

cor(X)
cor(Y)



Is it possible to create a exponential distribution in netlogo with maximum and minimum values?

Suppose I have X patches, and patches have a patch variable called "patch-quality", with values between 0 and 1. I want to generate a random number between 0 and 1 for that variable following an exponential distribution.

When you set up an exponential distribution in NetLogo, you need a mean:

random-exponential mean

The mean of my exponential distribution is 0.13 (I want most patches to be close to 0 quality).

set patch-quality random-exponential 0.13

The problem is that, sometimes, I got few patches with patch-quality above 1.

Is there a way to generate an exponential distribution in NetLogo that wouldn't generate patches with patch-quality above 1?




mercredi 15 mars 2023

Math.random is messing with probablity?

So i wrote this code while tinkering around with async stuff and stumbled on a puzzle. I know i'm just missing something or what ever, but i just want to talk this out and see if my reasoning is sound!

I made a game, basically producing a number from 1-4, and trying to get a 3 or less (represented by the timeout), 7 times in a row (represented by 7 bgColor changes to make it do something).

Here is where the probabilty comes in: probablity of getting 3 or less out of four = 3/4 or .75, 75% whatever you like.

The probablity of that happening 7 times in a row is (3/4)^7 or .13348

I have run this code, as it stands, with a 200 sample rate. Initially, the ratio stays around .13 kinda for about 4 "wins" and then shoots up to leaving off at .26 almost EXACTLY 2(.133)! I'm wondering somewhere in the Math.random code I could find this? Does anyone have any direction for me to think about? This is my first post to SO! Thanks in advance!

const delayColor = (color) => {
    let delay = Math.floor(Math.random()*5)*10;
    return new Promise ((resolve, reject) => {
        if(delay <= 30){
            setTimeout(()=>{
                document.body.style.backgroundColor = color;
                console.log(delay)
                resolve(`${color}`)
                }, delay)}
        else {
            setTimeout(()=>{
                document.body.style.backgroundColor = 'black';
                console.log(delay)
                reject(`${color}`)
            }, delay)
        }
    })
}

let success = 0;
let total = 0;
let restarts = 0;
let wins = 0;

function clearRainbow(){
    success = 0;
    total = 0;
}

async function rainbow(){
    try {
        await delayColor('red');
        success++;
        total++;
        await delayColor('orange');
        success++;
        total++;
        await delayColor('yellow');
        success++;
        total++;
        await delayColor('green');
        success++;
        total++;
        await delayColor('blue');
        success++;
        total++;
        await delayColor('indigo');
        success++;
        total++;
        await delayColor('violet');
        success++;
        total++;
        console.log('7 In a ROW!');
        wins++;
        console.log(`Your ratio: ${success} / ${total} (${success/total}) requiring ${restarts} for a total ratio of: ${wins/restarts}`)
        console.log(`wins: ${wins}, Restarts: ${restarts}`)
        clearRainbow();
        if (wins<=200){
            rainbow();
        }
        else {
            clearRainbow();
        }
    }
    catch (e){
        console.log('Timed Out, Starting Again!')
        total++;
        restarts++;
        rainbow()
    }

    
}

I tried to run it a bunch and was expecting the "total ratio" or the overall probability of getting 3 or less out of 4, 7 times in a row to be the calculated value of .13 and am getting consistent .26 from Math.random()...

I would like to know about it and don't know where to look.




Create Column of Bernoulli Probability (0-1) from data in matrix Using R

The first I was create RNG with Additive then using the column 2 for the next get Bernoulli probability with "Xi" Value to Runif it.

#Create RNG with Additive
Additive_RNG<-function(a,z0,c,m,n,p) {
  {
    a = readline("Masukkan Nilai a: ")
    z0 = readline("Masukkan Nilai z0: ")
    c = readline("Masukkan Nilai c: ")
    m = readline("Masukkan Nilai m: ")
    n = readline("Masukkan Nilai n: ")
    p = readline("Masukkan Nilai p: ")
  }
  {
    a = as.integer(a)
    z0 = as.integer(z0)
    c = as.integer(c)
    m = as.integer(m)
    n = as.integer(n)
    p = as.integer(p)
  }
  xi<-matrix(NA,n,3)
  colnames(xi)<-c("aZ(i-1)+c","Xi","Ui")
  for (i in 1:n)
  {
    xi[i,1]<-(a*z0+c)  #membuat nilai pada kolom petama (Zi = aZ0+c)
    xi[i,2]<-xi[i,1]%%m #mmembuat nilai kolom kedua Zi*mod
    xi[i,3]<-xi[i,2]/m #membuat nilai uniform pada kolom ketiga
    z0<-xi[i,2] #z0 akan ke replace sampai perulangan berikutnya
  }
  #Generate probability of Bernoulli
  {
    p<-p
    tes<-matrix(NA,n,2)
    colnames(tes)<-c("X","Y")
    for (k in 1:n)
    {
      tes[k,1]<- runif(xi[i,2])
      tes[k,2]<- (X<=p)+0
      (tabel<-table(tes[k,2])/length(tes[k,2]))
    }
  }
}
Additive_RNG(a,z0,c,m,n,p)

So I want the ouput have a probability 0 and 1 from data "Xi" to Uniform like the pictures.

example expected output




mardi 14 mars 2023

Multiple random outputs from same pool

I need to have 3 output variables with values from 1 to x, and I need them all to equal 3+y.

If my variables are called "A, B, C" my code is as follows:

A=1
B=1
C=1

while y>0:
A=A+randint(0,y)
y=y-A+1
B=B+randint(0,y)
y=y-B+1
C=C+randint(0,y)
y=y-C+1

This had the problem that it doesn't give all 3 outputs a fair chance, and i also have not found a way to check for x.

Any ideas, even incomplete ones will be welcome, thanks a lot.




Can some one explain the functionality of random.randint(0, num_items -1) [closed]

import random
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")

#Get total number of items in list
num_items = len(names)


random_choice = random.randint(0, num_items -1)

person_who_will_pay = names[random_choice]
print(person_who_will_pay + " is goin to by the meal today.")

random_choice = random.randint(0, -1)



Haskell Random: Same code, different machines, different result

I'm testing my code with pseudo-random number generator with the same seed on my PC (Ubuntu) and on remote server (FreeBSD) and these are the results.

My PC (ghci 8.8.4):

> Prelude> import System.Random
> Prelude System.Random> let (elemIdx, newGen) = randomR (0, 199) (mkStdGen 40)
> Prelude System.Random> elemIdx
94

Server (ghci 7.6.3):

> Prelude> import System.Random
> Prelude System.Random> let (elemIdx, newGen) = randomR (0, 199) (mkStdGen 40)
> Prelude System.Random> elemIdx
43

Strangely enough I'm getting different results (94 my PC, 43 server) with same seed. What could be causing this behavior?




lundi 13 mars 2023

How to generate random number from 0 to 122 using RandomNumberGenerator Class c#

byte[] rngBytes = new byte[4];
RandomNumberGenerator.Create().GetBytes(rngBytes);
int mynum= BitConverter.ToInt32(rngBytes, 0);

i have been getting bigger numbers from above code, which can be -ve or +ve numbers.

need help on how to generate random number from 0 to 100 using RandomNumberGenerator Class c#




NumPy Creating two matrices that results in third that calculates diagonal

I am rather new to coding in python but familiar with matlab and Mathematica.

In python, I created two 4x4 matrices (A and B) that have random number elements which in turn creates a third C matrix like:

Matrix C

The diagonal elements should then be presented in 4x2 matrix but I can not construct it right.

This is what I have so far:

import numpy as np
A = np.random.rand(4,4)
B = np.random.rand(4,4)
C = np.array([[A[0,0], A[0,1], B[0,2], B[0,3]],
              [A[1,0], A[1,1], B[1,2], B[1,3]],
              [A[2,0], A[2,1], B[2,2], B[2,3]],
              [A[3,0], A[3,1], B[3,2], B[3,3]]])

My question is, how do I print out the diagonal from Matrix C from here? The output checked in other software should be something like:

C = [[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], [13, 14, 15, 16]]

and then the diagonal

Diagonal = [[1, 6], [10, 15], [3, 8], [12, 16]]




Increase entropy pool by writing to /dev/random (macOS)?

I know there's rng-tools for Linux, but haven't found a port for macOS, so I'm trying to do it manually. I understand you can write to /dev/random to fill the entropy pool (at least in Linux, probably same applies to macOS?). So what happens when you read from /dev/random after writing to it? Is it something like a fifo/lifo-buffer? Will the data read from /dev/random be a mix of system generated pseudo random numbers and what I fed it with? Can something be done so that /dev/random only supplies random numbers from an external source in macOS (I guess rng-tools will do this on Linux)?




dimanche 12 mars 2023

Extremely off output in a random number generating program

I am trying to make a rng program with three players mediator, user, and a computer. A User choses a word and a key to use within the game and the number of sides to each of the three sided dice. They all throw a dice which is ramdonly generated. Whichever players sum of their dice roll is less than the number rolled by the mediator, they accumulate a letter of the chosen word where they have the opportunity to not gain a character towards their word if they roll high enough. The game loops until whichever player accumulates enough letters that equal the chosen word. Then, the losing players word then gets "ciphered" and the game ends.

This is my code

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


void update_key(char* key, int key_len, char* word, int word_len) {
    // Create a new key by repeating the original key until it matches the word length
    int num_repetitions = word_len / key_len + 1;
    char* new_key = malloc(num_repetitions * key_len + 1);
    for (int i = 0; i < num_repetitions; i++) {
        strcat(new_key, key);
    }
    // Trim the new key to match the word length
    new_key[word_len] = '\0';
    strncpy(key, new_key, key_len);
    free(new_key);
}

void cipher(char* word, int word_len, char* key, int key_len) {
    // Update the key if necessary
    if (key_len != word_len) {
        update_key(key, key_len, word, word_len);
    }
    // Initialize the modified alphabet and get its length
    char alphabet[] = "abcdefghijklmnopqrstuvwxyz ";
    int alphabet_len = strlen(alphabet);
    // Iterate over each character in the word
    for (int i = 0; i < word_len; i++) {
        // Convert uppercase characters to lowercase
        char c = word[i];
        if (c >= 'A' && c <= 'Z') {
            c += ('a' - 'A');
        }
        // Get the indices of the character in the word and the key
        int word_idx = strchr(alphabet, c) - alphabet;
        int key_idx = strchr(alphabet, key[i]) - alphabet;
        // Calculate the shift amount and wrap it if necessary
        int shift_amount = (word_idx + key_idx) % alphabet_len;

        // Encrypt the character using the shift amount
        word[i] = alphabet[shift_amount];
    }
}

int is_valid_seed(char* seed) {
    int seed_len = strlen(seed);
    if (seed_len < 1 || seed_len > 6) {
        return 0;
    }
    for (int i = 0; i < seed_len; i++) {
        if (seed[i] < '0' || seed[i] > '9') {
            return 0;
        }
    }
    int seed_value = atoi(seed);
    if (seed_value < 1 || seed_value > 999999) {
        return 0;
    }
    return 1;
}


int roll_dice(int dice_sides) {
    return rand() % dice_sides + 1;
}

int validate_dice_sides(char* dice_sides) {
    // Remove any whitespace characters from the input
    int j = 0;
    for (int i = 0; dice_sides[i] != '\0'; i++) {
        if (dice_sides[i] != ' ') {
            dice_sides[j++] = dice_sides[i];
        }
    }
    dice_sides[j] = '\0';
    
    // Parse the three integers from the input string
    int sides[3];
    int num_sides = sscanf(dice_sides, "%dx%dx%d", &sides[0], &sides[1], &sides[2]);
    if (num_sides != 3) {
        return 0;
    }
    
    // Check that all sides are within the range [1, 11]
    for (int i = 0; i < 3; i++) {
        if (sides[i] < 1 || sides[i] > 11) {
            return 0;
        }
    }
    
    return 1;
}
int is_valid_name(const char* player_one_name) {
    int length = strlen(player_one_name);
    if (length < 2 || length > 8) {  // check if name length is valid
        return 0;
    }
    for (int i = 0; i < length; i++) {
        if (!(player_one_name[i] >= 'a' && player_one_name[i] <= 'z') && !(player_one_name[i] >= 'A' && player_one_name[i] <= 'Z')) {
            // check if name contains non-alphabetic characters
            return 0;
        }
    }

    return 1;  // name is valid
}

int is_valid_word(const char* word){
    int length = strlen(word);
    if (length > 7) {  // check if name length is valid
        return 0;
    }
    for (int i = 0; i < length; i++) {
        if (!(word[i] >= 'a' && word[i] <= 'z') && !(word[i] >= 'A' && word[i] <= 'Z')) {
            // check if name contains non-alphabetic characters
            return 0;
        }
    }

    return 1;

}

int is_valid_key(const char* key, const char* word) {
    int key_length = strlen(key);
    int word_length = strlen(word);
    if (key_length < 1 || key_length > word_length) {
        return 0;
    }
    for (int i = 0; i < key_length; i++) {
        if (!((key[i] >= 'a' && key[i] <= 'z') || (key[i] >= 'A' && key[i] <= 'Z'))) {
            return 0;
        }
    }
    return 1;
}

    
    // Main game loop
void game_logic(char* player_one_name, int seed, int dice_sides, char* word, char* key) {
    // Seed the random number generator
    srand(seed);
    
    // Initialize player scores
    int player1_word_count = 0;
    int player2_word_count = 0;
    
    int player1_word_index = 0;
    int player2_word_index = 0;

    
    // Get the length of the word and key
    int word_length = strlen(word);
    int key_len = strlen(key);
    
    int player1_loses = 0;
    int player2_loses = 0;
    int i;
    // Play rounds until a winner is determined
    int round = 1;
    while (!player1_loses && !player2_loses) {
        // Roll the dice
        int mediator_roll = roll_dice(dice_sides);
        int player_one_roll = roll_dice(dice_sides);
        int player_two_roll = roll_dice(dice_sides);

        if (player_one_roll < player_two_roll) {
            player1_word_count++;
            player1_word_index++;
            if (player2_word_index > 0) {
                player2_word_count--;
                player2_word_index--;
            }
        } else if (player_one_roll < player_one_roll) {
            player2_word_count++;
            player2_word_index++;
            if (player1_word_index > 0) {
                player1_word_count--;
                player1_word_index--;
            }
        } else {
        }
        if (player1_word_count == word_length) {
            player1_loses = 1;
        }
        if (player2_word_count == word_length) {
            player2_loses = 1;
        }
        
        printf("Round %d:\n", round);
        printf("Mediator dice roll: %d\n", mediator_roll);
        printf("%s dice roll: %d\n", player_one_name, player_one_roll);
        printf("Computer dice roll: %d\n", player_two_roll);
        
        for (i = 0; i < player1_word_index; i++) {
            printf("%s's word is currently: %s", player_one_name, word[i] + key);
        }
        for (i = 0; i < player2_word_index; i++) {
            printf("Computer's word is currently: %s", word[i] + key);
        }
        printf("\n\n");

        round++;
    }

    if (player1_loses){
        printf("%s has lost the game...their word will now be ciphered!\n", player_one_name);
        printf("New key is being created to match the length of the word...");
        printf("%s's orginal word was %s\n", player_one_name, word);
        cipher(word, word_length, key, key_len);
        printf("%s's encrypted word is now %s\n", player_one_name, word);
        }
    if (player2_loses){
        printf("Computer has lost the game...their word will now be ciphered!\n");
        printf("New key is being created to match the length of the word...");
        printf("Computer's orginal word was %s\n", word);
        cipher(word, word_length, key, key_len);
        printf("Computer's encrypted word is now %s\n", word);
        }
        
}
int main() {
    // Initialize variables
    char player_one_input[51], player_one_name[50], dice_sides_input[21], dice_sides[20],word_input[51], word[50], key_input[51],key[50];
    int seed_input[8], seed[7]
    
    // Get input from user
    printf("Welcome to the game of HorseDiceCipher!\n");

    printf("Please enter in your name player one: ");
    fgets(player_one_input, sizeof(player_one_input), stdin);
    sscanf(player_one_input, "%[^\n]", player_one_name);
    while (!is_valid_name(player_one_name)){
        printf("Invalid name value. Please enter a valid name value (2-8 letters, no numbers): ");
        fgets(player_one_input, sizeof(player_one_input), stdin);
        sscanf(player_one_input, "%[^\n]", player_one_name);
    }
    
    
    printf("Please enter a seed value: ");
    fgets(seed_input, sizeof(seed_input), stdin);
    sscanf(seed_input, "%[^\n]", seed);
    while (!is_valid_seed(seed)) {
        printf("Invalid seed value. Please enter a valid seed value: ");
        fgets(seed_input, sizeof(seed_input), stdin);
        sscanf(seed_input, "%[^\n]", seed);
    }
    srand(atoi(seed));

    printf("Please enter the sides of the dice to use: ");
    fgets(dice_sides_input, sizeof(dice_sides_input), stdin);
    sscanf(dice_sides_input, "%[^\n]", dice_sides);
    while (!validate_dice_sides(dice_sides)) {
        printf("Invalid dice sides. Please enter the sides of the dice to use: ");
        fgets(dice_sides_input, sizeof(dice_sides_input), stdin);
        sscanf(dice_sides_input, "%[^\n]", dice_sides);
    }
    
    printf("Please enter a word to use for the game: ");
    fgets(word_input, sizeof(word_input), stdin);
    sscanf(word_input, "%[^\n]", word);
    while (!is_valid_word(word)) {
        printf("Invalid word. Please enter the word to use(7 characters and must only contain alphabetical characters): ");
        fgets(word_input, sizeof(word_input), stdin);
        sscanf(word_input, "%[^\n]", word);
    }



    printf("Please enter a key to use for the game: ");
    fgets(key_input, sizeof(key_input), stdin);
    sscanf(key_input, "%[^\n]", key);
    while (!is_valid_key(key, word)) {
        printf("Invalid key. Please enter a key between 1 and %d characters: ", strlen(word));
        fgets(key_input, sizeof(key_input), stdin);
        sscanf(key_input, "%[^\n]", key);
    }

    cipher(word, strlen(word), key, strlen(key));
    printf("----------------------------------------------------\n");
    printf("The game of HorseDiceCipher is beginning now!\n");
    game_logic(player_one_name, seed, dice_sides, word, key);

    return 0;
}

Everything went well until I entered the input which was: Scooby 86578 3x3x3 tacocat dogZ

the output should look like this:

Round 6 of dice rolls is starting now!

 Mediator has rolled all three dice... their sum is 7

 Scooby has rolled all three dice... their sum is 5

 Computer has rolled all three dice... their sum is 7

 Scooby's word is currently t

 Computer's word is currently ta

 Round 7 of dice rolls is starting now!

 Mediator has rolled all three dice... their sum is 6

 Scooby has rolled all three dice... their sum is 8

 Computer has rolled all three dice... their sum is 5

 Scooby's word is currently

 Computer's word is currently tac

but mine looks like this

Round 3:

Mediator dice roll: 1457

Scooby dice roll: 25237

Computer dice roll: 12608


Round 4:

Mediator dice roll: 11245

Scooby dice roll: 971

Computer dice roll: 28850

Scooby's word is currently:

it used to put gibberish that is not even part of the word before, but it doesn't even produce anything now.

What is wrong with my code? Thank you.




NameError: name 'setupterm' is not defined??? How can I solve it?

NameError: name 'setupterm' is not defined ??

How can I solve it?

File "c:\Users", line 5, in screen=curses.initscr() ^^^^^^^^^^^^^^^^




Issues with seed value output of randomized values Java

I am trying to build a program in java that a user inserts a value and with the numbers up to that value, a seed is used to pseudo-randomize the table of values. For example, if the user inputs 5, the program creates a 5x5 table that has every number up until one duplicated e.g

this is the example

After this, the table should be pseudo-randomized by another value the user is prompted to enter. My issue is that the values that are being randomized are incorrect, as per the below image where the numbers range from 1-5. as the user inputted 5,and is pseudo-randomized by the seed value of 22. Can someone please help? Thank you.

Output of my program versus expected output

This is my code:

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

public class LabProgram {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        System.out.println("Please enter the number of elements to be paired.");
        int input = scnr.nextInt();
        // Initialize a 1D Array
        int i = 0;
        // Append duplicates of pair values 1-input 
        List<Integer> pairs = new ArrayList<>();
        for (i = 1; i <= input; i++) {
            // Adds value twice to the array
            pairs.add(i);
            pairs.add(i);
        }

    // Prints pairs into a table and creates a new line every fifth value
    int count = pairs.size();
    int newLine = 0;
    for (i = 0; i < count; i++) {
        int pair = pairs.get(i);
        System.out.printf("%4d", pair);
        System.out.print("");
        newLine = newLine + 1;

        if (newLine == 5) {
            System.out.println("");
            // Reset lineCount back to 0 to allow for new calc to occur
            newLine = 0;
        }
    }
    System.out.println();

    System.out.println("Please enter a seed number for testing purposes.\n");
    int seed = scnr.nextInt();
   // Collections.shuffle(pairs, new java.util.Random(seed));
   Random randomGeneratorName = new Random(seed);

    // Print the pairs in a table with a max of 5 numbers per row
    count = pairs.size();
    newLine = 0;
    int[] usedNumbers = new int[input];
    int unusedNumbers = input * 2;
    for (i = 0; i < count; i++) {
        int index = pairs.get(i) - 1; // change index to start at 0
        int number = index + 1; // change number to start at 1
        if (usedNumbers[index] == 0) {
            System.out.printf("%4d", number);
            usedNumbers[index] = 1;
            unusedNumbers--;
            newLine++;
            if (newLine == 5) {
                System.out.println();
                newLine = 0;
            }
        }
    }
    System.out.println();

}

}




samedi 11 mars 2023

Python Random Int Generation returning 'None' instead of a integer [closed]

I have a very simple dice rolling program, with the main body of the program here.

def roll():
 rollOne = random.randint(1,6)
 rollTwo = random.randrange(1,6)
 if rollOne == rollTwo:
   score = (rollOne + rollTwo) * 2
 else:
   score = rollOne + rollTwo
   return score


for i in range(rounds):
 playerOneRoll = roll()
 print("Player 1 rolled a",playerOneRoll)
 playerOneScore = int(playerOneScore) + int(playerOneRoll)
 print("Player 1's total score is",playerOneScore)
 print("----------------------------")
 sleep(delay)
 roll()
 playerTwoRoll = roll()
 print("Player 2 rolled a",playerTwoRoll)
 playerTwoScore = int(playerTwoScore) + int(playerTwoRoll)
 print("Player 2's total score is",playerTwoScore)
 print("----------------------------")
 sleep(delay)

It works fine for a couple rounds but then sometimes the player one roll will return as 'None' and the program will end due to an error. Can't figure out why. Attached is an image of the output. output Any comments or ideas about this would help a lot - many thanks.




Keep getting error msg in Chrome console - GET 404 (Not Found)

I'm trying to create a small memory card game as a beginner project.

Page structure + goal:

  • There are 6 cards and 2 buttons in total.
  • Goal: If you click on the reset button, it should change the src of the images.

Problem:

  • When you click on the reset button, sometimes the swapped img disapper, and gives the following error in Chrome's Dev tool / console: GET http://127.0.0.1:5500/Szorgalmi/Projects/undefined 404 (Not Found)
  • When you click on the error, you can see the following: Image (async) RandomizeSrcOfImages@script.js:32

** Here is how my line 32 in the JS file looks like, with the function:**

let resetButton = document.querySelector('reset');
function RandomizeSrcOfImages() {
    /* let revealAllImg = document.querySelectorAll('.images');
     for (let i = 0; i < revealAllImg.length; i++) {
         revealAllImg[i].style.display = "block";
     }*/
    let allImage = new Array();
    allImage[1] = "elephant.png";
    allImage[2] = "octopus.png";
    allImage[3] = "melon.png";

    let randomImage = Math.floor(Math.random() * allImage.length);
    document.querySelector('#img1').src = allImage[randomImage];
    document.querySelector('#img3').src = allImage[randomImage];
}

reset.addEventListener('click', RandomizeSrcOfImages);

What I've tried so far:

  • Relocate all files to a different folder
  • Added script type = "text/javascript" to the HTML
  • Bunch of Googleing

Note: This error does NOT occur all times. I couldn't figure out why, but sometimes when the reset button is clicked it does the job, sometimes the error pops up.

I've looked up several stackoverflow posts, and searched on Google since yesterday, and still didn't find a solution.




Conditional random sampling: n samples must add to Y

How do I sample n numbers X_1 through X_n (in one go?) such that their total is a given Y, and knowing that the unconditional distribution of X_i is (or would be) the normal distribution with parameters mu and sigma?

Just drawing n normally distributed numbers and scaling them to total Y doesn't seem right. If the absolute value of Y is very large, it would tend to produce n outliers (relative to the unconditional distribution) as opposed to - I don't know - 1 outlier. Also: if Y is zero, the result doesn't make sense.




Error While Using Random Module In VS code

Traceback (most recent call last): File "/home/sree/ Desktop/ 1-Python/random.py", line 1, in import random File "/home/sree/ Desktop/ 1-Python/random.py", line 3, in a=random.randint(1,3) ^^^^^^^^^^^^^^ AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import)

I Got This Some Body Please Help Me -_-

How to Install all The Modules and Packages In a Single Line Of Commmand :)




vendredi 10 mars 2023

RNG with Parallel and Thread safe goes magic after refactor

First of all, please be patient with this question because I'm very very new at these scenarios, I don't fully understand the work behind this and I'm asking in order to learn.

I feel I'm trapped in the third law of Arthur Clarke: Any sufficiently advanced technology is indistinguishable from magic.

My scenario:

I'm working with 1 billions of simulations to predict some behavior that not come in case. I made a functional mockup of logic that with some improvements with Parallel.For runs 4500 simulations per second and CPU at 5%.

Then after a deep search in S.O. I found some thing to change and for my surprise, I get 150000 sims/sec with CPU at ~25% with high notes.

Because the change I did is in a fundamental RNG method (previous used locked) and the new uses... magic?

One thing that call my attention is that the ratio, instead of being slower or fixed after some minutes (like the old method) is highly incremental until the end.

My Question:

What I did is really an improvement OR I just wasted my random number generation and now I'm getting repeated values? Or viceversa? It doesn't seems to be repeated values in neither case because I'm getting 700k different values (of course with repetitions of them) because I'm looking for probability of results in my main algorithm. But doesn't seems to be the repeated random values at all.

The results are very different in both ways, but I can't say that the first one was right. The new one seems to be a little more precise at big scale (128 permutations) but the old one seems to be far more precise at micro scale (8192 permutations)

Wich one is right? There are both wrong? Why?

My code

I didn't refactor the For but for the health of the question I'll show it:

                var lockTarget = new object();
                int counter = 1;
                ParallelOptions options = new() { MaxDegreeOfParallelism = Environment.ProcessorCount };
                   Parallel.For(1, totalSIM, options, i => {
                        /* do some stuff with the RNG inside */ 
                        int current = Interlocked.Increment(ref counter);
                        if (current % 500 == 0)
                           {
                             /* just for console report */
                               lock (options) _printConcurrent(++current);
                           }
                    });

The code that call the RNG contains (doesn't change neither):

        bool[] count_sides= new bool[3];
        count_sides[0] = GetRandomSide();
        count_sides[1] = GetRandomSide();
        count_sides[2] = GetRandomSide();

        return count_sides.Count(c => c) 

My old RNG:


at class level:

private static Random seedGenerator = new Random(Environment.TickCount);

and a method inside the class:

    private static bool GetRandomSide()
    {
        int seed;
        lock (locker)
        {
            seed = seedGenerator.Next(int.MinValue, int.MaxValue);
        }
        var random = new Random(seed);
        return random.NextDouble() < 0.5;
    }

My new RNG:


From: https://stackoverflow.com/a/57962385/888472

I replace the same method with:

    private static bool GetRandomSide() {
        return ThreadSafeRandom.Next(0, 2) == 1;
    }

and then just use the answer:

 public static class ThreadSafeRandom
    {
        private static readonly System.Random GlobalRandom = new Random();
        private static readonly ThreadLocal<Random> LocalRandom = new ThreadLocal<Random>(() =>
        {
            lock (GlobalRandom)
            {
                return new Random(GlobalRandom.Next());
            }
        });

        public static int Next(int min = 0, int max = Int32.MaxValue)
        {
            return LocalRandom.Value.Next(min, max);
        }
    }

Thanks for reading and sorry for my english and my little knowledge about this.




Selenium IDE Chrome Extension-Inserting generated random DOB into fields

I've worked out how to generate the dates I need, but I'm not sure how to insert these into the fields I need them to go in on the webpage.

I'm trying the below but it's not inputting the number generated

Command= type
Target= (page field reference i.e. DD digits)
Value= ${myRandomNumber}

Also, as I'm generating day, month and year separately, will I need to annotate myRandomNumber somehow so that it's referencing the correct one, or will it always reference the last one generated?

Thanks




jeudi 9 mars 2023

Pseudo-random bijection

I would like to map a subset of the first integers to itself, so that each access is O(1), and so that the function is pure and does not store the complete mapping. There are no strong requirement like being photographically secure, the bijection must just not be trivial and "look" unpredictable.

Is it possible to create such a function ?

I can shuffle an array, but I would like to know if there a more direct method. I saw the method proposed at Create a random bijective function which has same domain and range, but it is not O(1).




Is there any technics that allowed guess next random number having set of generated numbers?

I have set of random generated numbers. How can I predict next number?

I tried some online tools but without a success. Maybe there some technics or tools that helps with that.




Increase the probability of death with age using Pyhton

Using OOP I want to generate a definition in a class which increase the probability of death every year after the 45 years old and no one can live more than 90 years.

It means that after your birthday 45 the probability of death will increase every year and the oldes age to die is 90.

I tried some functions importing "random", but it creates probabilities randomly every year after the 45 and not in an increasing probability way.

The main idea is that as older you are the probability to die should increse after the 45 years and must be 100% at the age of 90.




What to do when U have a circular import

I'm having an attribute error on my random module

I tried using random module to identify the 'randint' of a particular range of numbers but pycharm is saying that the module 'random' Has no attribute 'randint'. Thank you in advance.




mercredi 8 mars 2023

SFML Snake recreation in C++ - Fruit spawning on Snake's body

I know this is rookie code, but it's the first project I've made. I thought my logic was working, but sadly the fruit still manages to spawn on the snake's body.

Note: The sf::Vector2f 'movement' is what I'm setting the head's position to earlier in the code.

The std::vector<sf::RectangleShape> snake_body is a container that holds all of the snake's body tiles.

The random_location y coordinate has 1 being added to it because at the top of the screen is an extra row of tiles where a score counter is located, and the player cannot go there.

Everything works fine in my game except the spawning of the fruit is on the Snake's body. I know I can fix some things, but this specific problem I've been working on for hours with no success. Here's my function to spawn the fruit:

sf::Vector2f spawn_fruit(sf::Vector2f movement, sf::RectangleShape fruit, std::vector<sf::RectangleShape> snake_body) {

    sf::Vector2f random_location;
    std::srand(time(NULL));

    // flag set to true to loop to see if there is actually collision
    bool collision = true;

    while (collision) {
        // if there is no collision, it will stay false
        collision = false;
        // set spawn location based on time elapsed (cheap way to make random numbers)
        random_location.x = rand() % GRID_WIDTH;
        random_location.y = rand() % GRID_HEIGHT + 1;

        // make sure x and y isn't the same as the snake's current x and y
        if (random_location.x == movement.x && random_location.y == movement.y) collision = true;

        // make sure x and y isn't the same as snake body's current x and y
        for (int i = 0; i < snake_body.size(); i++) {
            if (snake_body[i].getPosition().x == random_location.x && snake_body[i].getPosition().y == random_location.y) {
                collision = true;
                break;
            }

        }
    }

    // return the vector
    return random_location;
}

Any help would be much appreciated. Thanks!




Python weighted random choices from lists with different probability, comparing two Pandas DataFrame from CSVs

Python beginner, here. I am attempting to take a pandas DataFrame (created from a CSV) and use weighted random choices to choose from another DataFrame (created from a CSV). What I have is two pandas DataFrames that read something like this:

Weighted Percentages of codes:

SECTION CODE Final_Per
B1 800 5%
B1 801 65%
B1 802 30%
B2 900 30%
B2 901 70%
B3 600 50%
B3 601 50%

Input pandas DataFrame to run weighted percentages on:

SECTION NUMBER
B1 14
B2 25
B3 12

These are just examples of my tables rather than the entirety of the tables themselves. What I need to do is store these weighted probabilities whether in a dictionary, lists, or pandas dataframes (not sure what's best) - and take my second table above and apply the 'Final_Per' %'s to the 'NUMBER' column and output the result. So B1's result would be 14 values, 5% being code 800, 65% being code 801, and 30% being code 802. Currently, the tables are CSV's and I am turning them into pandas dataframes and attempting to take some lessons learned from this article https://pynative.com/python-weighted-random-choices-with-probability/ to no success. Does anybody have suggestions on how to handle this correctly? Thank you.




How can I extract random samples of spatial points using "sample function" and repeat the process with "for loops" in R

I am working in RStudio for Mac OS and I am struggling with a code. I have a SpatialPointsDataFrame consisting of 128 points with three collumns (ID, Easat, North). I would like to extract a random sample of 10% of these sites (i.e. n = 115). In addition, I would like to repeat this process 10 times, i.e. create 10 iterations of the extraction of random samples. My aim is to obtain 10 separate groups that contain 115 random points extracted from the original 128 points.

I have try several codes unsuccessfully, including for loops, function and lapply. But I either don't get what I am looking for or get different type of erros. The simplest code that has got me closer is this:

nsites <- sites # defining my database
nsim <- 10 # setting the number of simulations
nsamp <- 115 # defining the number of points I want to extract
s90 <- nsites[sample(nrow(nsites), size = nsamp, replace = FALSE, prob = NULL), ]
for(i in 1:nsim) {
        s90r[nsim] <- list(s90) # create a list to store the results
        print(s90r)
}

This result in 10 groups of points, but when I plot each group I realized that they are the same 115 points, and not 10 groups of -different- random 115 points.

Thank you very for any suggestion!

Best,

Eduardo




mardi 7 mars 2023

Function to change random distribution in Swift?

Does Swift have some built in methods to change the distribution of random numbers? I want to use a linear equation to define the distribution, something like y = k * x + m. When k = 0, all numbers should be equally distributed. When k = 1 the distribution should follow the line, so low x-values would be very rare while high x-values would be common. I played around in Excel and tried different strategies and finally came up with this code, which seems to work - but there must be a neater way to do this in Swift?

As a note: First I did use an array of ClosedRange instead of the tuples-approach, then used .contains. Then I changed it to an array of tuples because my code didn't work as expected. Probably another bug, but I stayed with tuples as the code works now.

import Foundation

/* function to create an array of tuples with upper and lower
 limits based on a linear distribution (y = k * x + m) */
func createDistributions(numbers: ClosedRange<Int>, k: Double) -> [(Double, Double)] {
    var dist = [(Double, Double)]()
    let m: Double = 0.5
    let nVal: Int = numbers.count
    var pStop: Double = 0.0

    for x in numbers {
        let t = (Double(x) + 0.5) / Double(nVal)
        let y = (k * (t - 0.5) + m) * 2.0 / Double(nVal)
        let start = pStop
        let stop = y + start
        
        dist.append((start, stop))
        pStop = stop
    }
    
    return dist
}

// create distributions based on k-value of 1.0
var result = createDistributions(numbers: 0...34, k: 1.0)


// loop ten times, creating a Double random number each time
for _ in 0...9 {
    let ran = Double.random(in: 0...1)
    
    // check in which indexed array the random number belongs to by checking lower and upper limit
    for i in 0..<result.count {
        
        // the random number belongs to the i:th element, print i
        if ran >= result[i].0 && ran <= result[i].1 {
            print(i)
        }
    }
}



Weighted shuffle distribution at specific index (formula)

What's the probability of finding element A at index i in array R after shuffling it with a random sampling algorithm? Is there a general formula for that?

Example: Given array ['a', 'b', 'c'] and weights [3, 2, 1]:

p[a at 0] = 50%
p[a at 1] = 35%
p[a at 2] = 15%

I found this by making a simulation with thousands of shuffles.

The weighted sampling/shuffle algorithm: http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf




How to generate a pandas dataframe column with pre-determined values

I have created a pandas dataframe using this code:

import pandas as pd
import numpy as np

ds = {'col1':[1,1,1,1,1,0,0,0]}

df = pd.DataFrame(data=ds)

The dataframe looks like this:

print(df)
   col1
0     1
1     1
2     1
3     1
4     1
5     0
6     0
7     0

I need to create a new column, called col2, subject to these conditions:

  1. when col1 = 1, then we have 5 records. For 3 of those records, col2 must be equal to 2 and for the remaining 2 records col2 must be equal to 3. The location of the 2's and 3's is random.

  2. when col1 = 0, then we have 3 records. For 2 of those records, col2 must be equal to 5 and for the remaining record col2 must be equal to 6. The location of the 5's and 6 is random.

The resulting dataframe would look as follows (obviously the location of the values in col2 is random, so when you try to solve this you might get different record location, but the proportion of the values in col2 should meet the conditions specified above):

enter image description here

Does anyone know how to do this in python?




lundi 6 mars 2023

Randomize items with a filter in R

is there a way to shuffle dataframe's rows based on a filter? For instance, I have this dataframe:

data=data.frame(id=c(3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26),
                name=c("restructuring","restructuring","restructuring","restructuring",
                       "control","control","control","control","clitic filler","clitic filler","clitic filler","clitic filler","clitic filler","clitic filler","clitic filler","clitic filler","action filler","action filler","action filler","action filler","action filler","action filler","action filler","action filler")
               )

In which numbers from 3 to 6 are 'restructuring', 7-10 are 'control', 11-18 are 'clitic filler', 19-26 are 'action filler', and I'd like name column to not have the same value in 2 consecutive rows.

I tried:

shuffled_data= data[sample(1:nrow(data)), ]

But this obviously randomizes with no criteria




dimanche 5 mars 2023

How to make a random function without using any library?

I know that the way to produce random numbers from 0 to 1 (0.0 ≤ n < 0.1) can be done using a code like this in Python:

import random
print(random.random())

But I'm curious about how this function can be made and how it works. Is anyone who can explain how to make a random function from the scratch without using any library?

The result I want:

def getRandom():
  # return float between 0 and 1 (0 ≤ n < 1)

I have found several website sources, but I don't get a good understanding of it.




from django.db.models.functions.math import Random2 ImportError: cannot import name 'Random2' from 'django.db.models.functions.math' [closed]

How can fix this problem ?

Now I am using my Django version is 3.0.7 , I am tried another version but not support this solutions.




samedi 4 mars 2023

random alphanumeric string into hexadecimal in Python [duplicate]

I'm trying to turn an alphanumeric string into a hexadecimal number.

The following code works as intended...

A = "f8g9dsf9s7ff7s9dfg98d9fg97s06s6df5"
B = int(A, 16)

When I try create the alphanumeric dynamically it breaks and doesn't get converted to hexadecimal number...

A = ''.join(random.choices(string.ascii_lowercase + string.digits, k=34))
B = int(A, 16)

Thanks for the help, extremely new to Python.




How To Select all numbers on python [closed]

I want select all the numbers on python not choose a random number

how to do it

while True:
    id = ['407474340', '1950713662', '7993793340', '1606183110', '534649695', '2540710248']

    ran = ''.join(random.choice(id))