mardi 31 octobre 2023

Generating Random numbers following lognormal distribution [closed]

I am generating pseudo random numbers following lognormal distribution using following python but the numbers are not validating against the data I already have. I have mean and standard deviation of the lognormal distribution (Mean=0.198, std=0.0963). Need some help on it. Thanks. Code is as following

import numpy as np

mean = float(input("Enter the mean of the log-normal distribution: "))
std_dev = float(input("Enter the standard deviation of the log-normal distribution: "))

# Generate and display 365 random numbers following the log-normal distribution
for _ in range(365):
    random_number = np.random.lognormal(mean, std_dev)
    print(random_number)



generate random data when they are potentially correlated using copula

I have a task to evaluate companies' pro-environment performance, I have some sample indicators: ['Emissions', 'Energy_Use', 'Waste', 'Water_Use', 'Recycling',......]

some of the indicators may be correlated, for example, if a company has a large number of emissions, then the energe_use will not be low.

I know copula can deal with the dependence between random variables, my aim is to generate random numbers for each indicator (let's say 100 companies) that may be close to realisaion. But I only know the basic way (np.random) to generate isolated indicator numbers, however, indicators may be correlated.




lundi 30 octobre 2023

How do I code a Discord Bot that pulls an option out of a list, and replies it? I have tried some other options

I tried to code a Discord Bot that pulls a joke out of a list. I believe I did it wrong. Does anyone have a fix? My bot won't respond to $joke. My other simple text commands are fine.

const randomJokelist = ['A','B','C']
const random = Math.floor(Math.random() * randomJokelist.length);

client.on('messageCreate', (message) => {
    const randomJokelist = ['A','B','C']
    const random = Math.floor(Math.random() * randomJokelist.length);
    if (message.content === '$joke') {
        message.reply(random, randomJokelist[random]);
    }
});

I tried to code a Discord Bot using client functions and a random number drawer in JS. The bot doesn't respond.




How can I show a random image from the product gallery as the primary product image in the Woocommerce store?

I have 3 color t-shirts in my gallery. I randomly want one of these 3 tshirt images to be the primary image of my product. I want it to appear randomly on both the product page and the store pages.

I think I need a function for this, where I will leave the primary image empty and only upload 3 images to the gallery.

This code snippet shows the first image in the gallery only on the store page, but since it is not the primary image on the product page, it appears empty. But I don't want the first image, I want it randomly.

function modify_woocommerce_product_get_image( $image, $product, $size, $attr ) {
    $image_ids = $product->get_gallery_image_ids();
    if( $image_ids ) {
        $image_ids = array_merge($image_ids, array($product->get_image_id()));
        $key = array_rand($image_ids);
        $id = $image_ids[$key];
        $image = wp_get_attachment_image( $id, $size, false, $attr );
    }
    return $image;
}
add_filter( 'woocommerce_product_get_image', 'modify_woocommerce_product_get_image', 99, 4 );



dimanche 29 octobre 2023

Java get non uniform random numbers [duplicate]

I need to generate random data for a geocaching game. I've a list of QuestMeasurement with QuestId, StageId and measurement value.

How can I generate random numbers that should have a different average per quest. (Right now all the averages are around the median of the boundries.)

Here's the code:

 public static int getValueForMeasurementType(String measurementType) {
        Random random = new Random();
        return switch (measurementType) {
            case HARTSLAG -> (int) (random.nextDouble() * (125 - 60 + 1) + 60) ;
            case ZWEETNIVEAU -> (int) (random.nextDouble() * 101);
            case GELUID -> (int) (random.nextDouble() * (100 - 30 + 1) + 30);
            default -> 0;
        };
    }

When I calculate the average per QuestId:

Average HARTSLAG for quest 06541BCC50F2451EA5088464E6A6CD9C: 89.41176470588235
Average HARTSLAG for quest 08BC162BBC5A456A8BE9E24E76EEBF79: 95.11764705882354
Average HARTSLAG for quest 082DC01CC9D74CF0AEA7C79EAF616EEE: 89.79411764705883
Average HARTSLAG for quest 096AE1335FD648018A95968AFC8FBB12: 91.3529411764706
Average HARTSLAG for quest 0A5C24368F084608B0506ABB61138218: 92.38235294117646
Average HARTSLAG for quest 0A2934DD6996453E84826F7A703BCBC1: 90.13725490196079
Average HARTSLAG for quest 0870A3CAD0754C3DAFA686D202024A36: 90.02941176470588
Average HARTSLAG for quest 05555A33124D4298820C6E40DDF94B4D: 88.8970588235294

As you can see they all seem to be around the average.

Is there a way to manipulate the randomness so that per quest it should generate random numbers in a random range within the provided range?




Optimal CUDA thread/block count for a function with no inputs (random sampling)

There are a lot of questions about optimizing the number of threads and blocks in a CUDA function, but everything I've found is about matching them to the problem size.

I have a task with no problem size. My inputs are random numbers and my output is to be reduced to a single scalar. For simplicity, suppose that I'm computing π by throwing uniformly random points x ∊ (‒1, 1) and y ∊ (‒1, 1) to see how many fall within the unit circle. I'll need a random number generator and an output array as large as my total number of threads so that each thread can increment its count without atomics/contention. Then I'll need to sum the output array to get a single scalar.

I think the optimal way to do this is to use 1024 threads on exactly 1 block, since everything that I read says that an NVIDIA GPU can run no more than 1024 threads at a time. I don't see any advantage to stopping a thread and continuing the random number generation in the next block, and if the random number generator is stateful, it could be better to keep it running in a for loop within the thread, anyway.

Am I missing something? And why isn't this use-case more common (why don't I see more questions about it)? Monte Carlo's a thing...




Generate random table assignments in R

Here's a challenge that I thought would be easier than it is... I'm looking for an algorithm (ideally in R) that can generate random table assignments for a conference workshop I will be hosting. I have a list of participants with an affiliation, such as:

participants <- c(
  person("Rishi", "Sunak", comment = "Conservative"),
  person("Liz", "Truss", comment = "Conservative"),
  person("Boris", "Johnson", comment = "Conservative"),
  person("Theresa", "May", comment = "Conservative"),
  person("David", "Cameron", comment = "Conservative"),
  person("Gordon", "Brown", comment = "Labour"),
  person("Tony", "Blair", comment = "Labour"),
  person("Kier", "Starmer", comment = "Labour"),
  person("Jeremy", "Corbyn", comment = "Labour"),
  person("Ed", "Milliband", comment = "Labour")
  # Plus about 50 more delegates
)

We have a (TBD likely 5ish) number of tables, where the participants will each rotate: n_tables. There will be the same number of rotations, so each participant goes to each table once.

I am looking for a randomisation sequence that does the following:

  1. Randomises each participant to each table once
  2. Ensures the total number of participants on each table is balances - i.e. similar number on each table
  3. Balances the affiliations on each table to be approximately equal to the overall balance (note there will be about 4). So no tables all labour for example.
  4. Attempts to assign participants in such a way that they come into contact with as many of the other participants as possible over the whole session (i.e. not create one assignment then rotate)



samedi 28 octobre 2023

Previously working variables no longer working in C

I was making some changes to my code so it'll randomly give either addition, subtraction, multiplication, division(before it would cycle through each one). But for some reason, previously working variables (question, wrongAnswers, totalQuestions, correctAnswers) are now coming up as undefined. What's causing this and how can I fix it?

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

int addition(void){

    int number1, number2, addAnswer, response;
    srand(time(NULL));
    
    number1 = rand() % 12;
    number2 = rand() % 12;
    
    addAnswer = (number1 + number2);
    printf("%d + %d = ?\n", number1, number2);
    scanf("%d", &response);
    
        if (response == addAnswer){
            return 1;
        }
        else{
            return 0;
        }
}

int subtraction(void){

    int number1, number2, subAnswer, response;
    srand(time(NULL));
    
    number1 = rand() % 12;
    number2 = rand() % 12;
    
    subAnswer = (number1 - number2);
    printf("%d - %d = ?\n", number1, number2);
    scanf("%d", &response);
    
        if (response == subAnswer){
            return 1;
            
        }
        
        else{
            return 0;
        }
    

}

int multiplication(void){

    int number1, number2, multAnswer, response;
    srand(time(NULL));
    
    number1 = rand() % 12;
    number2 = rand() % 12;
    
    multAnswer = (number1 * number2);
    printf("%d * %d = ?\n", number1, number2);
    scanf("%d", &response);
    
        if (response == multAnswer){
            return 1;
            
        }
        
        else{
            return 0;
        }
    

}

int division(void){

    int number1, number2, divAnswer, response;
    srand(time(NULL));
    
    number1 = rand() % 12 + 1;
    number2 = rand() % 12 + 1;
    
    divAnswer = (number1 / number2);
    printf("%d / %d = ?\n", number1, number2);
    scanf("%d", &response);
    
        if (response == divAnswer){
            return 1;
            
        }
        
        else{
            return 0;
        }
}

int main(void) {
    int response, int question = 0, correctAnswers = 0, totalQuestions = 0, wrongAnswers = 0;
    response = 0;
    srand(time(NULL));
    while (response != -1111) {
        
        if (question == 0){
            
            response = addition();
            
        } else if (question == 1){
        
            response = subtraction();
        
        }else if (question == 2){
    
            response = multiplication();
    
        }else {
            
            response = division();
            
        }
        
        if (response == 0){
            wrongAnswers++;
            totalQuestions++;

        }
        
        if (response == 1){
            correctAnswers++;
            totalQuestions++;
        }
    }
    wrongAnswers = (totalQuestions - correctAnswers);
    printf("Out of %d questions, you got %d right and %d wrong.\n", totalQuestions, correctAnswers, wrongAnswers);
    
    return 0;
  }
        



How can I create random names and surnames in c++? [closed]

The problem is I want to make a program which asks for the number of students and after putting the number, the program will create names and surnames. So I'm thinking at first we need to create two structures, one for names the other for surnames, and then it'll choose randomly from there.

I'm new at c++, I'm still learning. I've tried some stuff I've looked for but couldn't get much done so I'd be glad if u could tell me how it'll work. Thank u!!!




Why does section of my code only run some times for no reason?

I have just started learning python and was trying to write a very simple version of Black Jack game. The code seems to be running fine except sometimes it will simply stop after printing "Now dealer moves" with no error message or reason.

from random import choices, choice
import inquirer
new_game = True
while new_game:
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    player_hand = choices(cards,k=2)
    dealer_hand = choices(cards,k=2)
    player_sum = sum(player_hand)
    dealer_sum = sum(dealer_hand)
    print(player_hand)
    print(dealer_hand)

    print(f"Your cards are {player_hand} with a score of {player_sum}.")
    print(f"The dealer's first card is {dealer_hand[0]}.")

    print("\nNow you move first.")
    player_end = False
    while not player_end:
      another_round = input("Type 'y' to deal another card, type 'n' to pass: ").lower()
      if another_round == 'y':
        player_hand.append(choice(cards))
        player_sum = sum(player_hand)

      if player_sum > 21 or another_round == 'n':
        player_end = True
        print(f"Your final hand is {player_hand} with a score of {player_sum}.")
      else:
        print(f"Your hand is now {player_hand} and current score is {player_sum}.")

    if player_sum > 21:
        print("Unfortunately you went over. You lose")
    else:
        print('\nNow dealer moves.')
        dealer_end = False
        while not dealer_end:
            if dealer_sum < 17:
                dealer_hand.append(choice(cards))
                dealer_sum = sum(player_hand)
            else:
                dealer_end = True
        print(f"The dealer's final hand is {dealer_hand} with a score of {dealer_sum}.")

        if player_sum > dealer_sum:
            print("You won!")
        elif player_sum == dealer_sum:
            print("It's a draw")
        else:
            print("You lose.")

    another_game = input("\nDo you like to start a new game? Type 'y' to start and 'n' to exit. ")
    if another_game == 'n':
        new_game = False
    else:
        print("\n")

I have tried running it multple time, but still don't see a clear pattern of when it would stop working.

Can anyone help me to spot the error?




vendredi 27 octobre 2023

Writing a project in EiffelStudio that simulates a dice roll

I am attempting to simulate a dice roll using the RANDOM class in the BASE library. With my current code, it only ever prints out 5.

class APPLICATION

create make

feature make local random_obj: RANDOM do create random_obj.make io.put_integer (random_obj.next_random (random_obj.item) \ 6 + 1) end

end




Is a `std::mt19937` static function variable thread-safe?

I have a function rand_double() which generates a random floating-point value using a static function variable with type std::mt19937. Several threads may use this function concurrently.

#include <random>

auto random_double(double min, double max) {
    static std::mt19937 generator{std::random_device{}()}; // Forgot to seed it, thanks @user4581301
    return std::uniform_real_distribution<>{min, max}(generator);
}

My first question is, is the above code as-is thread safe? I know that since C++11 the initialization of static function variables is always thread-safe, but how about the concurrent use of generator?




How to generate a random directed cyclic graph with a defined "average" number of edges for each node? (in R language)

I want to generate random directed cyclic graphs while defining the number of nodes and the average number of edges for each node. By "average number of edges" i mean that the degree of each node is usually the one i define with lower chances of being lower or higher.

For example i want a DCG with 3 edges per node i will have 80% nodes with degree 3, 15% nodes with degree 2, 5% nodes with degree 1 (note: all nodes should have edges, no disconnected nodes)

I would also like to define the number of cycles in the generated DCG.

I don't know if there is something that is already implemented that does this.

I tried with igraph with the erdos.renyi.game

library(igraph)  
nodes = 20  
edges = 40  
g <- erdos.renyi.game(nodes, edges, type = "gnm",  
          directed = TRUE, loops = FALSE)  
is.dag(g) ##FALSE --> it's a Directed Cyclic Graph  
x = degree(g)  
mean(x)  
table(x)  
names(sort(-table(x)))[1]  
hist(x)  
plot(g)   

with 20 nodes and 40 edges, directed edges and no self loops, i obtain a DCG but i have 2 problems:

First, i cannot define the number of edges per node, here i tried to have a number of edges that is two times the number of nodes in hope to get an average of 2 edges per node but i end up with random degrees ranging up to nodes with degree of 8

Second, i cannot define the number of cycles or the number of nodes that define the cycle, so if i have two nodes pointing at eachother it counts as DCG. It would be better if i could define cycles that involve more than 2 nodes for the tests.




jeudi 26 octobre 2023

_CRT_RAND_S: How does it working in Windows C/C++?

I wrote code like this:

#include <iostream>
#define _CRT_RAND_S  // may this line cause problem
#include <stdlib.h>


int main(void)
{
    unsigned int r;
    rand_s(&r);

    // ...

    return 0;
}

and compiler said, cannot find rand_s(). Then I switched line 1 and 2, it works.

#define _CRT_RAND_S
#include <iostream>
#include <stdlib.h>
// ...

Question is,

  1. Why do I have to define _CRT_RAND_S at the top of code?
  2. Does <iostream> depends on _CRT_RAND_S? It seems not but...

I tried this in Windows x64, Visual Studio 2022. Thanks.




Python: Generate Lists with Random Unique Numbers outside a given Dataset Pattern

I have the following lists (as a simple dataset in a CSV file). Some lists contain consecutive, non-repetitive integer numbers and others contain non-repetitive unique numbers that follow a pattern:

sample-list-1.csv

N = 5

list1 = [1,  2,  3,  4,  5]
list2 = [2,  3,  4,  5,  6]
list3 = [1,  7, 13, 19, 25]
list4 = [7, 13, 19, 25, 31]

and so on... each list is in a separate row and each number is in a separate column - no headers or index in the csv

At a closer look, the numbers in the lists may represent a matrix, which is totally correct, but with N+1... i.e, a 6x6 matrix:

6 x 6 matrix

1   2   3   4   5   6
7   8   9   10  11  12
13  14  15  16  17  18
19  20  21  22  23  24
25  26  27  28  29  30
31  32  33  34  35  36

My goal is to generate another list (or lists) that contain 'N' non-consecutive, non-repetitive, unique/random numbers which do not follow the patterns in the original list Dataset. The N numbers should, of course, be among the 36 numbers from the matrix.
An error margin of maximum 2 consecutive numbers in a row or 2 continuous numbers (column-vice) can also be taken into consideration... but the other numbers in the generated list should follow the above rules.

So far, I'm able to import the CSV file and able to generate a list of random, non-repetitive numbers with the simple Code:

import random
import csv

N = 5
pick = random.sample(range(1, (N*N)+1), N-1)
#print("pick:", pick)

with open('sample-list-1.csv', newline = '') as f:
    reader = csv.reader(f)
    csvdata = list(reader)

csvdata_list = [int(x) for x in csvdata[2]]
#print("csvdata_list:", csvdata_list)

for n in pick:
    for i in csvdata_list:
        if n == i:
            print("n=", n, "i=", i)

And I'm able to do some simple comparisons with the original Dataset and the random number list using for loops...
However, my current method only iterates through a single list/pattern at a time, and I wish to iterate through multiple lists and their patterns to generate uniqueness in the new lists.

Any ideas on how I can achieve true randomness outside the patterns in the original Dataset using Code?
Thanks in advance!




Usage of bitmask in identifier generator

The popular nanoid package uses a bitmask to force random bytes to fit a given alphabet.

const bytes = [145, 94, 92, 130, 74, 86, 7, 30, 139, 223, 44, 36, 29, 134, 59];
const alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";

function nid1() {
  const mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1;

  let id = "";

  for (let i = 0; i < bytes.length; i++) {
    id += alphabet[bytes[i] & mask]; // bytes[i] = 59 returns undefined!
  }

  return id;
}

Sometime, the bitmask method overflows the alphabet, they mitigate it by adding || '' after alphabet[bytes[i] & mask] and asking for extra bytes, here is their full function:

function customRandom(alphabet, defaultSize, getRandom) {
  // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
  // values closer to the alphabet size. The bitmask calculates the closest
  // `2^31 - 1` number, which exceeds the alphabet size.
  // For example, the bitmask for the alphabet size 30 is 31 (00011111).
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
  // Though, the bitmask solution is not perfect since the bytes exceeding
  // the alphabet size are refused. Therefore, to reliably generate the ID,
  // the random bytes redundancy has to be satisfied.

  // Note: every hardware random generator call is performance expensive,
  // because the system call for entropy collection takes a lot of time.
  // So, to avoid additional system calls, extra bytes are requested in advance.

  // Next, a step determines how many random bytes to generate.
  // The number of random bytes gets decided upon the ID size, mask,
  // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
  // according to benchmarks).
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)

  return (size = defaultSize) => {
    let id = ''
    while (true) {
      let bytes = getRandom(step)
      // A compact alternative for `for (let i = 0; i < step; i++)`.
      let i = step
      while (i--) {
        // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
        id += alphabet[bytes[i] & mask] || ''
        if (id.length === size) return id
      }
    }
  }
}

Why did they not simply used the modulus operator ? Is this only for performance or is there cryptographic implications ?

function nid2() {
  let id = "";

  for (let i = 0; i < bytes.length; i++) {
    id += alphabet[bytes[i] % alphabet.length];
  }

  return id;
}



Producing a semi-RNG with a reproducible outcome in C (no random/urandom)

I wish to create a "randomness", or at least a large amount of entropy given certain data sets. The outcome must be predictable/constant, though, based on various factors, what datasets are used, etc. So I'm not looking to just read from random/urandom. I need this to be completely reproducible. I just want the spread to be varied enough across datasets using fairly limited key sizes. I suppose a rough idea:

[Key] --> [DatasetA] --> [Series of reproducible numbers]. Numbers that will significantly change based on a small modification to the key and any additional variable. Please note I'm trying to avoid just hashing as my requirement demands a lookup of datasets from the that will still simulate randomness without being random. It's procedurally-generated, but reproducible. I would prefer it be implementable in C as I want to use it for a (non-school) project. It's a hobby, but essentially I want to in the end be able to know certain criteria will produce very very varied results. Everything must be self-contained (no external dependence, just within the code and datasets, and keys).

If I'm looking at this from the wrong perspective, I'm open to other suggestions, but obviously it'd be preferable to not have to write the rest of the code-base from scratch.

Thanks in advance,

  • Nate

I've already tried several "made-up" "algorithms" based on key size and contents and dataset contents. I'm not getting sufficient entropy, though.




mercredi 25 octobre 2023

Reshuffling a column by group many times and put the results in new columns

I have the following hypothetical data:

district <- c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3)                                       
village <- c(1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,7)                              
status <- c(1,0,1,0,1,1,1,0,0,1,1,1,1,0,0,0)
datei <- data.table(district, village, status) 

I want to reshuffle status based on district and put the results in new columns. I know how to do it once using the following codes:

datei[, randomstat := sample(status), district]

Now, I want to reshuffle status 1000 times and put the results in new columns. I tried the following codes:

n <- 1000
datei[, paste0("randomstat", 1:n) := replicate(n, list(sample(status), district))]

but failed. Can someone help me with this? Thank you.




mardi 24 octobre 2023

How do I test code with randomized Input in Java

I'm writing a Yahtzee-style game and I'm in the stage where I've finished coding the ResultCalculator class, which takes the combination of dice and calculates, which results (Large Straight, Yahtzee...) are valid results.

I can't figure out a good way to test it, since the input is randomized. Sure, I could manipulate the Draw class where the dice are rolled so that I can manually set the dies' values but that doesn't seem very straightforward. Any ideas? How are classes like this getting tested in real life?

public class Die {
    private Value value;
    private int valueAsInt;
    private final Random random = new Random();

    public void rollDie() {
        int result = random.nextInt(1, 7);
        value = switch (result) {
            case 1 -> Value.ONE;
            case 2 -> Value.TWO;
            case 3 -> Value.THREE;
            case 4 -> Value.FOUR;
            case 5 -> Value.FIVE;
            case 6 -> Value.SIX;
        };
        valueAsInt = result;
    }


public class Draw {
    private static final int NUMBER_OF_DICE = 5;
    private final Die[] dice = new Die[NUMBER_OF_DICE];
    private final ArrayList<Integer> dieValuesAsInt = new ArrayList<>();
    private ArrayList<Result> results = new ArrayList<>();

 
    private void rollDice() {
        for (Die die : dice) {
            die.rollDie();
        }
    }


Then a ResultCalculator is called, it gets handed over Draw.dice & Draw.dieValuesAsInt




tms-NET sampling in Python

I have been trying find some pre-implementation of tms-NET sampling in python (as I couldn't implement by myself) for my projects wherein I want to perform sampling on numpy array of shape (num_of_data, embedding_dimensions=100). I couldn't find it.

Can anyone help me with my problem ?

I also try using Latin Hypercube Sampling however the scale of my data in my numpy array is not the with the value sample by pyDOE2 implementation of LHS.

from pyDOE2 import lhs

num_samples = X.shape[0]
num_dimensions = X.shape[1] # 100

lhs_samples = lhs(num_dimensions, samples=5)

The X array has values range from 0 to 1000 while most of the value samples by lhs is around 0.

Additionally, the description of my projects stats that

"If the size of the remaining X is equal to zero, then the selected train sample represents the complete data, and it is considered to be good. Otherwise, the data points are sampled from the remaining X using (t,m,s)-Nets. The samples which are selected using (t,m,s)-Nets are appended to the train sample for improving the representativeness of the data. "

I am not sure if my approach is correct.

If anyone could help, I would be very glad for it.




lundi 23 octobre 2023

Algorithm to repeatedly pseudorandomly select from a set, without frequent repeats

I have an array of things (conceptually a set, but let's implement as an array), say [A, B, C, D, E, F].

I need an algorithm that can pseudo-randomly pick an item from the array such that no item will be picked twice within x iterations.

That is, if x is 3 for this array, this would be ok: F, C, B, D, F, E, A, B,...

This would not be ok: F, C, D, C, ...

Other than this constraint, the selections should be as random as possible. (For instance, simply shuffling the array and selecting within copies of it is not acceptable.)

Ideally, this would achieved without having to record all the previous picks.

So the function would have a structure like:

function pick(options, minspacing, iteration) {...}

(It will be implemented in JavaScript).




How would I assign my random int to the user's input, permanently?

My problem today is How would I assign my random int to the user's input, permanently?

I created the scanner for the user to input their name and a random number generator. When the user enters in their name, the output is the ID number. I have looped users entering their name, but can't get it to print out that same random int once the some name is entered in again.

User input and number gen

I am still a beginner, but what I have tried is setting the user input to the random int, but i set it to the generator, not the output. I would like for the program to store the user input (their name) and the random int together, so that is the same user enters their name again, the same ID would pop up.




dimanche 22 octobre 2023

ACO Implementation: what's the most efficient of these two (hereunder)

I am currently working with Ant Colony Optimization (ACO) in my model. In this model, I have predefined paths, each of which is further divided into edges. In the Ant class, I aim to ensure that all paths are visited. However, I am concerned that by using predefined paths, the exploratory aspect of the model may be compromised. As an alternative, I am considering randomly visiting all edges (ensuring each edge is visited only once in an iteration) and then constructing paths based on certain constraints. I am uncertain which approach is more appropriate: either allowing ants to choose paths(edges on each path are predefined), potentially sacrificing the exploratory aspect, or randomly selecting edges and subsequently constructing paths.




samedi 21 octobre 2023

How to shuffle array of items but allow weights to influence the order

I'm trying to write a TypeScript function to shuffle an array.

By default, I want the shuffle order to be random (but subject to a seed). (I already have access to this function: function random(seed: number): number)

However, I want to also allow influencing the order via weights per item.

In other words, I want the the default item weight to be 1, and if an item has a weight of 10, it should be 10 times more likely to appear sooner in the shuffled order.

Am I even thinking about this correctly? Is this a reasonable goal?

I was thinking that I'd need to use the Fisher-Yates algorithm but adapted to honor a weights array of the same length as the main array, and the main array will be shuffled such that higher weighted items are more likely to appear first.

function removeDuplicates<T>(array: T[]): T[] {
  const uniqueValues = new Set<T>();
  return array.filter((item) => {
    if (!uniqueValues.has(item)) {
      uniqueValues.add(item);
      return true;
    }

    return false;
  });
}

function duplicateItemsBasedOnWeights<T>(array: T[], weights: number[]): T[] {
  const result = [];
  for (const [index, element] of array.entries()) {
    for (let position = 0; position < weights[index]; position++) {
      result.push(element);
    }
  }

  return result;
}

export function shuffleWithWeights<T>(array: T[], weights: number[], seed: number): T[] {
  const arrayWithDuplicateValuesBasedOnWeights: T[] = duplicateItemsBasedOnWeights(array, weights);

  const shuffledArrayWithDuplicateValuesBasedOnWeights = shuffleArrayUsingFisherYates(arrayWithDuplicateValuesBasedOnWeights, seed);

  return removeDuplicates(shuffledArrayWithDuplicateValuesBasedOnWeights);
}

I've looked at empirical results by calling it a bunch of different times with these values (and a different seed each time), and the results don't seem distributed how I'd hoped, so I must have been approaching this problem incorrectly.

const items = [1, 2, 3, 4, 5];
const weights = [1, 1, 1, 200, 1_000];

In my real-world cases, I'll be shuffling 70,000 objects (which would explore to many more than that if I use my current approach of creating duplicate items based on item weight).




TypeError: invalid rect assignment with vectors

I am a novice to programming and wanted to make pong as one of my first projects. I am now trying to get the pong ball to bounce to a random location but i got a TypeError: invalid rect assignement. Here is my code:

import pygame
import os
import random

vec = pygame.math.Vector2

WIDTH, HEIGHT = 640, 480
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("PongX")

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = ()

FPS = 60
VEL = 5
ball_vel = 1

PONG_WIDTH, PONG_HEIGHT = 30, 10
LEFT_PONG_IMAGE = pygame.image.load(os.path.join("Pong", "Pong.png"))
RIGHT_PONG_IMAGE = pygame.image.load(os.path.join("Pong", "Pong.png"))
BALL_WIDTH, BALL_HEIGHT = 10, 10
PONG_BALL_IMAGE = pygame.image.load(os.path.join("Pong", "Pong_Ball.png"))


UP_BORDER = pygame.Rect(0, 640, -2, 2)
DOWN_BORDER = pygame.Rect(0, 640, 478, 482)

def draw_window(left, right, ball):
    WIN.fill(BLACK)
    pygame.draw.rect(WIN, WHITE, UP_BORDER)
    pygame.draw.rect(WIN, WHITE, DOWN_BORDER)
    WIN.blit(PONG_BALL_IMAGE, (ball.x, ball.y))
    WIN.blit(LEFT_PONG_IMAGE, (left.x, left.y))
    WIN.blit(RIGHT_PONG_IMAGE, (right.x, right.y))
    pygame.display.update()

def ball_handle_movement(ball):
    if ball.y == 0 or 480:
        ball.y = vec(random.randint(0, 480), random.randint(0, 480))
    if ball.x == 0 or 640:
        ball.x = vec(random.randint(0, 640), random.randint(0, 640))


def left_handle_movement(keys_pressed, left):
    if keys_pressed[pygame.K_w] and left.y - VEL > 0:
            left.y -= VEL
    if keys_pressed[pygame.K_s] and left.y + VEL + left.height < HEIGHT - 15:
            left.y += VEL

def right_handle_movement(keys_pressed, right):
    if keys_pressed[pygame.K_UP] and right.y - VEL > 0:
            right.y -= VEL
    if keys_pressed[pygame.K_DOWN] and right.y + VEL + right.height < HEIGHT - 15:
            right.y += VEL

def main():
    left = pygame.Rect(30, 210, PONG_WIDTH, PONG_HEIGHT)
    right = pygame.Rect(600, 210, PONG_WIDTH, PONG_HEIGHT)
    ball = pygame.Rect(WIDTH/2, HEIGHT/2 ,BALL_WIDTH, BALL_HEIGHT)

    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False



        keys_pressed = pygame.key.get_pressed()
        ball_handle_movement(ball)
        left_handle_movement(keys_pressed, left)
        right_handle_movement(keys_pressed, right)
        draw_window(left, right, ball)

    pygame.quit()

if __name__ == "__main__":
    main()

Code leading to the problem:

if ball.y == 0 or 480:
    ball.y = vec(random.randint(0, 480), random.randint(0, 480))
if ball.x == 0 or 640:
    ball.x = vec(random.randint(0, 640), random.randint(0, 640))

I tried switching the values around and trying different methods but couldn't solve this issue.




Synchronizing LFSRs Fibonacci vs Galios

When discussing the advantages and disadvantages of Fibonacci vs Galois LFSRs, I often see mentioned that using the Fibonacci topology allows loading the received bit stream to the shift register to initialize it to the same state and achieve synchronization. Why can't it be done the same way with Galois ? I.E: when the Rx side receives the word it simply loads it to become the seed for the next values to come.




Why is the "random.randit" function not working [closed]

When I try to preform the "random.randit" function it gives a Attribute Error.

import random

fcon = random.randit ("Rich", "Poor", "Royalty")

car = random.randit("Lamborgini", "BMW", "Tesla", "Jeep",
                    "Mercedes", "Ford", "Nissan", "Chevrolet")

Unrelated edit: who just downvoted my post




vendredi 20 octobre 2023

Random sampling of n lists of m elements in python

I wrote this code which creates all combinations of n lists of m elements in python, samples a given number of unique combinations (max possible or 1000) and outputs it in excel. It basically works, but the problem is that when product(m_i) becomes very large, it is extremely slow.

A realistic use case could be that I have 32 lists with each 2-3 elements in each, from which I would need to sample 1000 unique combinations. That could be 10 billion combinations, but it is slow to create all these combinations, when I actually only need 1000 unique combinations.

I did consider just creating random samples and checking whether I already created this one, but that would become slow when numbers of samples approach number of possible permutations.

Image of data

import pandas as pd

df = pd.read_excel('Variables.xlsx',sheet_name="Variables" ,index_col=0)
df_out = pd.DataFrame(columns=df.index)

df.shape[0]
def for_recursive(number_of_loops, range_list, execute_function, current_index=0, iter_list = []):
    if iter_list == []:
        iter_list = [0]*number_of_loops
    
    if current_index == number_of_loops-1:
        for iter_list[current_index] in range_list.iloc[current_index].dropna():
            execute_function(iter_list)
    else:
        for iter_list[current_index] in range_list.iloc[current_index].dropna():
            for_recursive(number_of_loops, iter_list = iter_list, range_list = range_list,  current_index = current_index+1, execute_function = execute_function) 
            
def do_whatever(index_list):
    df_out.loc[len(df_out)] = index_list
    
for_recursive(range_list = df, execute_function = do_whatever , number_of_loops=len(df))

df_out = df_out.sample(n=min(len(df_out),1000))

with pd.ExcelWriter("Variables.xlsx", engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
    df_out.to_excel(writer, 'Simulations', index=False)



Let R randomly create a vector within specific requirements

I want R to create a vector for me that has length 15, each of the 15 values being in the range 0-100 and together adding up to 100. So an example outcome could be:

`[12, 25, 2, 0, 6, 17, 2, 4, 1, 8, 11, 3, 5, 0, 4]`

or

`[0, 0, 0, 1, 0, 4, 0, 0, 2, 0, 92, 0, 0, 1, 0]`

I would like to be able to change the length, the sum and the range of values of the vector for later use. Also I want the outcome to be 'random' so that I can repeat it multiple times and getting a different vector every time. (I have been searching for similar questions on some forums but without success unfortunately, but I feel it should not be too difficult)

I got this from someone else asking a similar question:

rand.vect.with.total <- function(min, max, total) {   
  x <- sample(min:max, total, replace=TRUE)       #generate random numbers  
  sum.x <- table(x)                               #count numbers   
  out = vector()   
  for (i in 1:length(min:max)) {     
  out[i] <- 
  sum.x[as.character(i)]   
  }   
  out[is.na(out)] <- 0   
  return(out) 
}

But then found out that it gives a vector with different length every time. I want the length of the vector to be constant and set by the function but I can't seem to make it work.




Randomizing 1s and 0s by groups while specifiying proportion of 1 and 0 within groups

First, I want to create a column that randomize 1s and 0s by group while maintaining the same proportion of 1s and 0s in another column.

Second, I want to repeat the above procedure many times (say 1000) and calculate the expected value.

Let me clarify with hypothetical data.

library(data.table) 

district <- c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3)                                       
village <- c(1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,7)                              
status <- c(1,0,1,0, 1,1,1,0,0,1,1,1,1,0,0,0) 

datei <- data.table(district, village, status) 

What I want to do is I want to create a column that randomize 1s and 0s within a district while maintaining the same proportion of 1s and 0s in status; the proportions of 1:0 are 2:2, 3:2 and 4:3 in district 1, 2 and 3 respectively.

Second, I also want to repeat this randomization many times (say 1000 times) and calculate the expected value for each row.

I know how to randomize 1s and 0s based on district.

datei[, random_status := sample(c(1,0), .N, replace=TRUE), keyby = district]

However, I do not know how to have the same proportion of 1s and 0s as in status and how to repeat and calculate the expected values for each row.

Many thanks.




jeudi 19 octobre 2023

If a variable has two values, how do I add the different values together? [closed]

So, I have one variable that has a random.randint, and I run it twice. Obviously both times have a different number (unless you get lucky lol). And I'm trying to add two separate numbers together with only one variable.

The variable is called start, and so I do something that looks like this:


Sum = (start + start)

Print(sum)

I put this inside of a for loop that runs twice.

When I run it, the result I get is the first number added to itself, and then the second number added to itself. What I'm trying to do is get the separate numbers added. This is part of a much larger thing and so I can't be bothered creating two separate variables so is there a way to make it so that it adds the first number and the second number together without having to make two distinct variables?




mercredi 18 octobre 2023

Why can I use `rng.gen()` but not `rng.gen_range()` when idiomatically initializing array with `core::array::from_fn()`?

In short: Why can I use

let array: [[f64; width]; length] = core::array::from_fn(|_| rng.gen());

but not

let array: [[f64; width]; length] = core::array::from_fn(|_| rng.gen_range(0.0..1.0));

It's not terribly that it doesn't work, but I don't understand the reason here.




mardi 17 octobre 2023

Dynamically create a fake dataset based on the subset of another (real) dataset

I've got a few datasets and for each, I'd like to create a fake dataset that is kind of a representative of that dataset. I need to do it dynamically, only based on the type of data (numeric, obj)

Here's an example

import pandas as pd
import random

# Create a dictionary with columns as lists
data = {
    'ObjectColumn1': [f'Object1_{i}' for i in range(1, 11)],
    'ObjectColumn2': [f'Object2_{i}' for i in range(1, 11)],
    'ObjectColumn3': [f'Object3_{i}' for i in range(1, 11)],
    'NumericColumn1': [random.randint(1, 100) for _ in range(10)],
    'NumericColumn2': [random.uniform(1.0, 10.0) for _ in range(10)],
    'NumericColumn3': [random.randint(1000, 2000) for _ in range(10)],
    'NumericColumn4': [random.uniform(10.0, 20.0) for _ in range(10)]
}

# Create the DataFrame
df = pd.DataFrame(data)

enter image description here

Let's say the above dataset has m (=3) object columns and n (=4) numeric columns. the dataset has x (=10) rows. I'd like to create a fake dataset of N (=10,000) rows, so that:

  1. ObjectColumn1, ObjectColumn2, ..., and ObjectColumn_m in the fake dataset are random selections of entries in ObjectColumn1, ObjectColumn2, ..., and ObjectColumn_m of data respectively
  2. ExtraObjectColumn in the fake dataset is an added fake column, which is a random selection of a list(e.g. list = [ran1, ran2, ran3])
  3. all NumericColumns in the fake data are a randomly generated number that is between the minimum and median of each of those columns in data respectively. for example, NumericColumn1 in the fake data would be a randomly generated data between (3 and 71.5)
  4. I don't want columns to be hard-coded. imagine m and n and x and N are all dynamic. I need to use this on many multiple datasets and the function needs to detect the object and numeric columns and do the above dynamically. The only column that is NOT dynamic is the ExtraObjectColumn, which needs to be given a list to be created from.
  5. Obviously, I need this to be reasonable performance. N is usually a large number (at least 10,000)

here's how fake_data should look like if N = 4

enter image description here




Get random AD user from certain group where user needs to be active and lastlogintimestamp greater than 14 days

I need to get the name and SamAccountname of one random user that is in a specific group.

So far ive got the randomizer working as intented, but ass soon as i try to filter get-AdUser im sol.

this is what i have as of now:

$date = (Get-Date).AddDays(-14)

$randomUser = (Get-ADGroupMember GROUP) |Sort-Object{Get-random} | select -first 1 | Get-Aduser -Properties name,SamAccountName #-filter {name -and SamaccountName -and LastLogonTimestamp -gt $date -and enabled -eq $true}

As soon as i uncomment the bold part it stops working.

Any ideas and help would be apriciated.

I think its because i cannot filter on that output, but i dont know how to otherwise do it. The reason im using lastlogontimestamp is because lastLogon is not replicated.




How do I use math to calculate the percentages of events happening

I'm creating a mod that will list the percent chance of an event happening. I know how to get individual percentages, but not a total percentage of the events.

So there is this pool, or an array of possible outcomes. Classic is always in this pool.

Bifurcated has a 15% chance of being added to that pool
Golden has a 0.3% chance of being added
Meaty has a 10% multiplied by the amount of X upgraded to be added. X=(max 3, min 0)
Caramelized has a 2% chance to be added.

And if another upgrade has been bought, all bought Classic get their checks done again, so there is a chance that there is : two, one, or none of being added to the pool.

Now the game takes this pool, and chooses one randomly from it. They have equal chances once in the pool. But not equal chances to enter the pool.

I'm having a hard time figuring out how to write the math to automatically calculate the chances are for each item. For example, if it was just Classic and Bifurcated a 15% chance to be added then a 50% chance to be selected would be 7.5% chance while classic has a 92.5% chance. But once I get to the possibility of a third being added, how do I calculate that?

After a lot of thinking, I came up with this system of adding them to the pool.

//chances of just ADDING bifurcated to the pool.
//RAN ONCE
let ranOnce_addOne = 0.15;
let ranOnce_addNone = 0.85;
//RAN TWICE
let ranTwice_addNone = 0.7225;
let ranTwice_addTwo = 0.0225;
let ranTwice_addOne = 0.225;

I had this, and didn't know where to go from here. For example if we only checked to add bifurcated to the pool once, I could figure it out, but the fact there are times when the amount in the pool could go from 1 to 9 (though statistically unlikely).

Now I have access to the amount of X and whether the checks get ran twice or not. But I have no idea how to code something that will tell me what is the chances of all this?




lundi 16 octobre 2023

Random Positive Definite matrix and Cholesky decomposition

I was interested in generating the correlated random data set and found some example of the solution here. But I've faced some interesting problems.

The solution consists from the next steps:

  1. Generate random uncorrelated data points (maybe from normal destribution)
  2. Calculate their covariance matrix (it must be positive definite)
  3. Find Cholesky decomposition of the covariance matrix

But the realization failing, if I am generating random points in the non-square form. For example:

X = np.random.rand(1000, 140)
Omega = X@X.T 
# or 
# Omega = np.dot(X_uncorr, X_uncorr.transpose())
# or 
# Omega = np.corrcoef(X.T, X.T, rowvar=False)

than the functions scipy.linalg.cholesky() and np.linalg.cholesky() will rise an errors 'LinAlgError: 101-th leading minor of the array is not positive definite' and 'LinAlgError: Matrix is not positive definite' correspondingly.

If the original data symmetric:

X = np.random.rand(1000, 1000)

there will be no errors. Is it some math fact, that the Cov matrix of nonsymmetric data set is negative definite? Or is it an error in code realization?




collect2: error: ld returned 1 exit status; ld error; gcc

I use ArchLinux! my code:

#include <iostream>
#include <random>

int main(){
    std::default_random_engine generator;
    std::uniform_int_distribution dice_roll(1,6);
    std::cout << dice_roll(generator) << std::endl;
    return 0;
}

The Error when i tried to compile the above code:

Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /build/gcc/src/gcc/configure --enable-languages=ada,c,c++,d,fortran,go,lto,objc,obj-c++ --enable-bootstrap --prefix=/usr --libdir=/usr/lib --libexecdir=/usr/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=https://bugs.archlinux.org/ --with-build-config=bootstrap-lto --with-linker-hash-style=gnu --with-system-zlib --enable-__cxa_atexit --enable-cet=auto --enable-checking=release --enable-clocale=gnu --enable-default-pie --enable-default-ssp --enable-gnu-indirect-function --enable-gnu-unique-object --enable-libstdcxx-backtrace --enable-link-serialization=1 --enable-linker-build-id --enable-lto --enable-multilib --enable-plugin --enable-shared --enable-threads=posix --disable-libssp --disable-libstdcxx-pch --disable-werror
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 13.2.1 20230801 (GCC)
COLLECT_GCC_OPTIONS='-o' 'random' '-v' '-mtune=generic' '-march=x86-64'
 /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/cc1plus -quiet -v -D_GNU_SOURCE programming/c_/random.cpp -quiet -dumpbase random.cpp -dumpbase-ext .cpp -mtune=generic -march=x86-64 -version -o /tmp/ccWzNenH.s
GNU C++17 (GCC) version 13.2.1 20230801 (x86_64-pc-linux-gnu)
    compiled by GNU C version 13.2.1 20230801, GMP version 6.3.0, MPFR version 4.2.0-p12, MPC version 1.3.1, isl version isl-0.26-GMP

warning: MPFR header version 4.2.0-p12 differs from library version 4.2.1.
GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
ignoring nonexistent directory "/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../x86_64-pc-linux-gnu/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../include/c++/13.2.1
 /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../include/c++/13.2.1/x86_64-pc-linux-gnu
 /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../include/c++/13.2.1/backward
 /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/include
 /usr/local/include
 /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/include-fixed
 /usr/include
End of search list.
Compiler executable checksum: 5a490a353c29b926850bca65a518c219
COLLECT_GCC_OPTIONS='-o' 'random' '-v' '-mtune=generic' '-march=x86-64'
 as -v --64 -o /tmp/cclCVfKY.o /tmp/ccWzNenH.s
GNU assembler version 2.41.0 (x86_64-pc-linux-gnu) using BFD version (GNU Binutils) 2.41.0
COMPILER_PATH=/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/:/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/:/usr/lib/gcc/x86_64-pc-linux-gnu/:/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/:/usr/lib/gcc/x86_64-pc-linux-gnu/
LIBRARY_PATH=/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/:/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../lib/:/lib/../lib/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../:/lib/:/usr/lib/
COLLECT_GCC_OPTIONS='-o' 'random' '-v' '-mtune=generic' '-march=x86-64' '-dumpdir' 'random.'
 /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/collect2 -plugin /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/lto-wrapper -plugin-opt=-fresolution=/tmp/ccNY4IFq.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr --hash-style=gnu -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -o random /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../lib/Scrt1.o /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../lib/crti.o /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/crtbeginS.o -L/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1 -L/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../lib -L/lib/../lib -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../.. /tmp/cclCVfKY.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/crtendS.o /usr/lib/gcc/x86_64-pc-linux-gnu/13.2.1/../../../../lib/crtn.o
/usr/bin/ld: /tmp/cclCVfKY.o: warning: relocation against `_ZSt4cout' in read-only section `.text'
/usr/bin/ld: /tmp/cclCVfKY.o: in function `main':
random.cpp:(.text+0x51): undefined reference to `std::cout'
/usr/bin/ld: random.cpp:(.text+0x59): undefined reference to `std::ostream::operator<<(int)'
/usr/bin/ld: random.cpp:(.text+0x60): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
/usr/bin/ld: random.cpp:(.text+0x6b): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status

kernel - 6.5.6-arch2-1 gcc version - 13.2.1

I was learning about the random module in C++. But Suddenly i stumbled across this error!




samedi 14 octobre 2023

Uncaught (in promise) TypeError: globalThis?.crypto?.randomUUID is not a function (Chrome)

I just started getting the Uncaught error today in Chrome (maybe after a Chrome update). Firefox doesn't give me the same error. It reads:

VM2540:2610 Uncaught (in promise) TypeError: globalThis?.crypto?.randomUUID is not a function
    at Messaging.request (<anonymous>:2610:44)
    at ClickToLoad.init (<anonymous>:11216:59)
    at ClickToLoad.callInit (<anonymous>:3180:18)
    at <anonymous>:11424:33
    at Array.forEach (<anonymous>)
    at Object.init (<anonymous>:11422:26)
request @ VM2540:2610
init @ VM2540:11216
callInit @ VM2540:3180
(anonymous) @ VM2540:11424
init @ VM2540:11422
await in init (async)
apply @ VM2540:11490

(anonymous) @ VM2558:3 (anonymous) @ VM2558:5 inject @ inject.js:114 (anonymous) @ inject.js:208

Thoughts?

Works in Firefox and Edge.




vendredi 13 octobre 2023

how do i choose randomly items from two different lists and display them together?

I want to generate new animals composed from elements from list1 and list2, e.g.: Sea-rat, Fire-horse, Nile-cat The mix should be generated randomly. Can someone point out, what Im doing wrong and why?

def new_animal():
    list1 = [ "Nile", "Sea", "Land", "Fire" ]
    list2 = [ "-rat", "-lion", "-cat", "-horse" ]
    list1 + list2
    return new_animal()
        
    import random
    random.choice(list1) + (list2)

    return new_animal()
    
def Zoo():
    new_animal = animal()
    print = "What animal is this?"
    answer = "That animal is a" + new_animal
    print(answer)

I believe i do something wrong with the part where i add lists, but i need only one element of each list... otherwise i believe my information flow is correct?




Shuffling a vector in Matlab with constraints (a specific number of 2-back repetitions)

I'm setting up a Matlab program where people will see a series of 15 words (e.g., 'dog', 'cat', 'fish', 'goat', etc.). One word will be presented per trial, and the full series of words will repeat 40 times (total = 600 trials; 40 unique appearances of each of the 15 words).

I want to arrange the trial order such that it's pseudorandom: on 50% of trials (starting from trial 3 onwards), the word should be the same as the word that was presented two trials previously. For example, a valid trial order (on a much smaller scale) would be:

  • Trial 1: dog (too early to be a 2-back repeat)
  • Trial 2: cat (too early to be a 2-back repeat)
  • Trial 3: dog (2-back repeat)
  • Trial 4: fish (not a 2-back repeat)
  • Trial 5: goat (not a 2-back repeat)
  • Trial 6: fish (2-back repeat)
  • Trial 7: goat (2-back repeat)
  • Trial 8: cat (not a 2-back repeat)

The above is valid because each of the 4 words appears equally often (here, twice each), with an equal number of 2-back repeats and non-repeats from trial 3 onwards.

I would also be ok with the number of 2-back repeats not equalling 50% exactly, but it should be close (e.g., somewhere between 40% and 60%). But, I'm not sure how to maintain this constraint while still ensuring that each of the 15 words repeats an equal number of times (40 times) across the full set of trials (600 trials).

Any help is greatly appreciated! Thanks in advance.

I've tried the brute force approach of reshuffling the full set of trials until the constraint is met by chance, but that takes much too long to process.




jeudi 12 octobre 2023

Create an N by 1 Function Handle of All Zeros Except at one Desired Location MATLAB

I have the following function handle:

f = @(t)f_0.*sin(alpha.*t).*cos(beta.*t);

I want to create an N by 1 function handle "array" called F (I know that you can't have an array of function handles in MATLAB) that places f at any random index position within the function handle "array." All other entries should be zero. N is any integer value.

For example, if N = 3, the correct solution is:

F = @(t) [f(t); 0; 0]

What is the best way to do this for any arbitrary N?




Is there a more efficient way to choose randomly in c other than using rand() srand()? [closed]

recently i started learning C , ive been working in some simple projects calculator,calendar,tempreture converter,rock paper scissors... Now im trying to build my own password generator,this program is based on random picking (numbers,letters,symbols...) to make a strong password. so i looked for a function that picks randomly , and i found rand() and srand() with time(0)

i was dissapointed after i learnd how these functions work that it wasnt as good as random.randint() in python , and that the function would return the same value over and over if you execute in the same second (as u can see from the exemple IMAGE) is there any other function or algorithme i could use to solve this problem ?enter image description here




Why is visual studio only generating 28 numbers with this code? [closed]

So today I wrote this simple code:

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int num = 0;
            bool ans = false;
            for (int i = 0; i < 100; i++)
            {
                num = random.Next(700,801);
                Console.WriteLine(num);
                if (num == 777)
                {
                    ans = true;
                }
            }
            Console.WriteLine("Was 777 generated?" + " " + ans);

            Console.ReadLine();
        }
    }
}

And when I tried running it I have noticed that when I use Ctrl+F5 to run it, it only generates 28 numbers instead of 100, but when I use the 'Run' button it does generate 100 numbers a expected. the last lines of the output

I have tried to restart Visual Studio, which did not work. I have tried to rewrite the program, which did not work. For some reason running it using Ctrl+F5 still only generated 28 numbers.




mercredi 11 octobre 2023

Good way to reload React UseState

So I need a useState() to change in order to rerender a certain component and it works. But I have to use a very ressource intensiv script for it. Is there a better way?

I want it like:

  const restartClick = (): void => {
    setDivClass("reload");
    setDivClass("loaded")
  };

This Worked but its not really good:

  const restartClick = (): void => {
    r = (Math.random() + 1).toString(36).substring(7);
    setDivClass(r);
  };

I tried using diffrent Values increasing an integer paralel but this is also kinda unclean. I really would appreciate a simple solution.




mardi 10 octobre 2023

i used random.choice(words) earlier in my code and need to use the answer later how can i express it since i dont know which word it will generate yet [closed]

in my code i am using print(random.choice(words)) and need to compare whatever word it ends up being with another word however i do not know how to do this as i don't know what the randomly generated word will be yet, how can i out this into a new function? if i just input (random.choice(words) again will it be a different word? should i use a random variable to be equal to this but then will it not print my word?

i have not tried much yet as i am very new to code and afraid i will break whatever working code i have so far




Problem with pyroot and C: dataframe changing everytime I use "Filter"

I am experiencing an unexpected issue while working with DataFrame filtering using the ROOT library in Python. Below is a simplified version of my code:

... df.Define("shift", "getShift()") ...

where:

getShift = """ #include <ctime> #include "TRandom3.h" float getShift() {     // smear vertices with a gaussian (interaction region of  2*sigma_beam = 126 mm)     auto now = std::chrono::system_clock::now();     auto timeSeed = now.time_since_epoch().count();     auto rnd = TRandom3(timeSeed);     auto shift =  rnd.Gaus(0, 63.) ;     return shift; } """ R.gInterpreter.Declare(getShift)

...

df_Fil = df.Filter("nHits \> 0 && PZ_pip0 \> 0 && PZ_pip1 \> 0 && PZ_pim0 \> 0 && \
std::isnan(theta_pvtv) == 0 && std::isnan(theta_fh) == 0 && std::isnan(theta_TRUE) == 0")

nBhits = (df_Fil.Filter('nHits_mother \> 0')).Count().GetValue()
print(f"stage1: {df_Fil.Count().GetValue()}")
noBhits = (df_Fil.Filter('nHits_mother == 0')).Count().GetValue()
print(f"stage2: {df_Fil.Count().GetValue()}")
ntauhits = (df_Fil.Filter('nHits_daughter \> 0')).Count().GetValue()
print(f"stage3: {df_Fil.Count().GetValue()}")
notauhits = (df_Fil.Filter('nHits_daughter == 0')).Count().GetValue()
print(f"stage4: {df_Fil.Count().GetValue()}")
notauhits = (df_Fil.Filter('nHits_daughter == 0')).Count().GetValue()
print(f"stage5: {df_Fil.Count().GetValue()}")
nr_Fil = df_Fil.Count().GetValue()
eff = nr_Fil / 10000000
print(f"nrFil = {nr_Fil}, nBhits = {nBhits}, ntauhits = {ntauhits}, noBhits = {noBhits}, notauhits = {notauhits}")

However, the output is not as expected:

stage1: 484 stage2: 510 stage3: 499 stage4: 483 stage5: 500 nrFil = 498, nBhits = 36, ntauhits = 493, noBhits = 465, notauhits = 18

(check: it should be nBhits+ntauhits = nrFil, notauhits=nBhits, noBhits=ntauhits"

The issue is that the counts of the DataFrame df_Fil seem to change unexpectedly after applying filters. I expected the count to remain consistent, but it appears to fluctuate after each filter is applied.

I am quite sure the problem depends on the generation of a random number "shift" that is re-generated everytime I use the Filter method, therefore changing the number of counts in nrFil (it's dependent on the exact shifts").

Anyone can help me understanding how to avoid this issue?

I've tried using TRandom3(42) for initialization and the counts at every stage are consistent, but it's because the shift value remains constant.




How do I detect a running WSL distro using C

So I'm trying to implement a RNG on Windows and as part of creating the seed I'm checking for installed and currently active WSL distros to get some random bits from /dev/random.

Afaik there is no API in C that directly connects to the WSL Distro, so I'm running the wslconfig /l /running command from my C script, storing and parsing the output to check for running WSL distros, and if one is detected then fetch the bits from /dev/random.

Here's my code:

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

int WSLGetEntropy(unsigned char* randBuf, size_t randBufSize) {
    wchar_t buffer[128];
    
    FILE* pipe = _wpopen(L"wslconfig /l /running", L"rb");
    if (!pipe) return 0;

    size_t bytesRead = fread(buffer, sizeof(wchar_t), sizeof(buffer) / sizeof(wchar_t), pipe);

    if (bytesRead == 0) {
        printf("No data received\n");
        _pclose(pipe);
        return 0;
    }

    /* Convert the wide character buffer to a regular C string */
    char* bufferStr = (char*) malloc(bytesRead + 1);
    if (bufferStr == NULL) {
        perror("malloc");
        return 0;
    }
    wcstombs(bufferStr, buffer, bytesRead);
    bufferStr[bytesRead] = '\0';
    /* parse the command output to get the name of any active wsl distro */

    char* start = strstr(bufferStr, "Windows Subsystem for Linux Distributions:\r\r\n");
    if (start == NULL) {
        free(bufferStr);
        _pclose(pipe);
        return 0;
    }

    start += 45;
    char* end = strstr(start, " (Default)");
    if (end == NULL) {
        free(bufferStr);
        _pclose(pipe);
        return 0;
    }

    size_t length = end - start;
    char* wslDistroName = (char*) malloc(length + 1);
    if (wslDistroName == NULL) {
        perror("malloc");
        free(bufferStr);
        return 1;
    }
    
    strncpy(wslDistroName, start, length);
    wslDistroName[length] = '\0';
    
    /* Get randBufSize bytes from /dev/random if a running WSL2 distro is detected */
    char *loc = malloc(12 + 17 + length + 1);
    strcpy(loc, "\\\\wsl.localhost\\");
    strcat(loc, wslDistroName);
    strcat(loc, "\\dev\\random");
    FILE *file = fopen(loc, "rb");

    if (file == NULL) {
        perror("Error opening random");
        return 0;
    }

    bytesRead = fread(randBuf, 1, randBufSize, file);

    if (bytesRead != randBufSize) {
        perror("Error reading from random");
        fclose(file);
        return 0;
    }

    fclose(file);
    free(wslDistroName);
    free(bufferStr);
    _pclose(pipe);
    return 1;
}

int main() {
    unsigned char buf[64];
    if (WSLGetEntropy(buf, 64)){
        for (int i = 0; i < 64; i++) printf("%02x ", buf[i]);
        printf("\n");
    }
    return 0;
}

However the string parsing and indirectly running the command like this makes this very inefficient. Is there a better and faster method to achieve this? Speed and memory are very important factors for my use case.




lundi 9 octobre 2023

How do you ask the user for the English translation? [closed]

I have created two lists, one with 10 Maori words and one with 10 English words (the translations). I need to generate a random Maori word and have the program ask the user for its English translation.

Here's what I have so far:

MaoriWords = [motu, awa, wai, ihu, kai, kanikani, mahi, waiata, ako, moe]
EnglishWords = [island, river, water, nose, food, dance, work, song, learn, sleep]

from random import randint
import random

x = random.MaoriWords(0,9)
print(x)



I am trying to make a random shuffle of a deck of cards with an array but I need the answer to be reversed [duplicate]

I am trying to make a random shuffle of a deck of cards with an array but the answer that is printed out, I need to be reversed. The base code itself is fine and runs without error, but how do i reverse my result. For example, if it printed out 31, 42, 12, 26 right now, I need it to be reversed, so, 26, 12, 42, 31. Could someone help with this? Heres my code. Thanks much!

private static void randomShuffle(int[] cards, Random random)
    {
        // TODO implement
        random.nextInt(cards.length);
        for (int i = cards.length - 1; i > 0; i--)
        {
            int j = random.nextInt(i + 1);
            int temp = cards[i];
            cards[i] = cards[j];
            cards[j] = temp;
        }
    }

I really have no clue how to reverse it. I'm assuming there is a function to do so, but I dont know what it is and how to implement it.




is there a particular way to randomly generate items based on two different options? [closed]

I am creating a program where it randomly generates hairstyles which I made a list for based on the gender you pick, male or female. Basically it starts with what is your gender, then asks what category of hairstyle do you want then it's supposed to then randomly generate a hairstyle from my list.

this is my code for now

import random

Male_natural_hairstyles=['afro', 'buzzcut', 'fade', 'waves', 'bald', 'classic haircut']


def blk_hairstyles():
    
    gender=""
    while gender=="":
        gender= input("What is your gender, male or female? ")
        
    if gender=="male":
        
        category=""
        
        category=input("what category do you want: natural or protective? ")
        
    if gender=="male" and category=="natural":
        
        blk_hairstyles= random.choices(Male_natural_hairstyles)
    
    
        
        
print (blk_hairstyles())



dimanche 8 octobre 2023

Is it possible that the distribution of std::mt19937 gets "better" with some "unused generations"?

I'm developing a program for Monte Carlo integration and using std::mt19937 as the generator.

Sorry I cannot paste my code here, but it's something like:

long long result = 0;
std::mt19937 rng(std::random_device()());
while (/*continue*/) {
    result += f(rng()); // do some calculation
    // for (int i = 0; i < 30; i++) rng(); // unused generations
}
// some other calculations

With a fixed number of samples, the Monte Carlo estimation seems to be more accurate if I uncomment the "unused generations" line. Further, if I increase the number of unused generations (say 30 -> 50), error seems to get even lower.

The unused generations indeed change the internal state of generator, but is it possible to yield better distribution by doing this?

Changing the seed didn't change this phenomenon.

(I know my question is somehow vague) I'm wondering if anyone has similar experience.

Anything could be helpful. Thank you in advance!




samedi 7 octobre 2023

How do I flag duplicates in my random question/answer generator loop?

I'm working on a program that's supposed to be like a trivia quiz. It picks a random question and answer from a list of strings for each. But I'm not sure how to prevent it from displaying that same question/answer again after it's already been displayed. I'm guessing I'd have to flag it, but don't know how to implement that.

Here's a snippet of the question generator:

srand(time(0));
    questionGenerated = rand() % 6 + 1; // picks a num 1-6 and looks for matching case 
    switch (questionGenerated)          // containing the question and correct answer strings
{
    case 1:
        cout << question1String;
                correctAnswer = answer1String;
                break;
// ...and so on with cases 2-6
}

I also made a thing to display the answers next to numbers in ascending order, so it can be a menu you can pick from while still having the answers randomized. Having the same issue.

// find out the correct answer int first,
// so incorrect answer int can be compared to it:

correctAnswerInt = rand() % 3 + 1;

    while (reroll > 0)
    {       // pick the number the incorrect answer will go next to:

        incorrectAnswerInt = rand() % 3 + 1;

                // determine where it and correct answer will go in the ascending order:

        if (incorrectAnswerInt > correctAnswerInt)
        {
            cout << correctAnswerInt << " " << correctAnswer << "\n";
            reroll -= 1;
        }
        else if (incorrectAnswerInt < correctAnswerInt)
        {
            cout << incorrectAnswerInt << " " << incorrectAnswer << "\n";
            reroll -= 1;
        }
                // or if it's equal to correct answer int, roll again:

        else
            reroll += 1;
    }

Example of intended output, for reference:

Question 3

1 Incorrect Answer
2 Correct Answer
3 Incorrect Answer

It's not working as intended right now but I'm mainly worried about flagging duplicates. Like, not getting 2 or "What is the capital of Belgium?" twice in a row.

I thought about adding an if/else with a bool that if true, rerolls the question. My fear is that something like this would cause an infinite loop:

while (questionHasBeenDisplayed = true)
{
       switch (questionGenerated)
       {
       case 1:
               questionHasBeenDisplayed = true;
           if (questionHasBeenDisplayed)
           // not sure how to send it back to start of loop from here,
               // but imagine some code here that does that
    else
            cout << question1String;
            correctAnswer = answer1String;
       // etc.
       }
}

I could also try adding a flag for each question, but that seems like a lot of variables.

For my answer code, the only thing I can think of is this:

while (reroll > 0)
{
    incorrectAnswerInt = rand() % 3 + 1;
    if (incorrectAnswerInt == incorrectAnswerInt && incorrectAnswerInt > correctAnswerInt)
// etc...
}

Which would always fail and cause an infinite loop.

I'm wondering now if there's a way to check the previous value of the variable (from the last loop) and compare it to the current value of the variable in the loop. Which would probably just mean making another variable, again, and reworking the code.

I'll guess I'll look into that now, but in the meantime any advice is appreciated. Thanks.




Random Number Generator Cofirmation

I just wanted to know if the following code actually include the value 3.0? (I know rand() is not the best, but I just wanted to try this out)

//function returns random double value between specificed range, inclusively.
double randomDouble (double minVal, double maxVal) {
    return double(rand()) / RAND_MAX * (maxVal - minVal) + minVal;
}

My logic was that

  1. double(rand()) / RAND_MAX gives random numbers in range 0.0 to 1.0, inclusive
  2. (maxVal - minVal) then turns that into 0.0 to MaxVal, inclusive
  3. adding minVal finally gives us random double values from minVal to maxVal, inclusive.

So, I tried to test if they really include maxVal by running this code:

int cnt = 0;
for (int i = 0; i < 999999999; i++) {
    if (randomDouble(1.0, 3.0) == 3.0) {
        cnt++;
    }
}
cout << cnt << endl;

But the cnt was zero always.

So I wasn't sure if my function was right?




vendredi 6 octobre 2023

how to use order_by RAND with my code below in codeigniter

i have this code :

$select = ['account_access_token','account_config_id'];       
$where = ['where'=>['enable_marketing' => '1', 'account_config_id.id!=' => $account_table_id]]; 
$join
=['account_user_info'=>'account_config_id.account_user_info_id=account_user_info.id,left'];       
$pages_info = $this->basic->get_data('account_config_id',$where,$select,$join);

so as you see i want to load an account into my target page

my question is : how to load the $pages_info results randomly ?

i tried to add : RAND(), $order_by='RAND()' but its dosen't work
every time the account id=$id is loaded with no change thanks a lot in Advanced

no luck with search




Does FusionAuth use a random salt for each password in Salted PBKDF2 HMAC SHA-256?

I am trying to find if FusionAuth uses a random salt for hashing algorithm in Salted PBKDF2 HMAC SHA-256




How to create multiple sizes of square box polygon within another polygon using bigquery

I am trying to create sequeries of random polygon of square shapes (the red box) that sits within a larger polygon (the blue polygon), given the larger polygon's geometries. How can I achieve this in big query. I als

enter image description here

I tried the ST_MAKEENVELOP() but it's no found in BQ, as well as ST_XMIN and ST_XMAX




How to Create a Virtual Phone Number using python

I have a question. I want to create my own virtual phone number using py but I don't know how to use it.




jeudi 5 octobre 2023

Problems with mt19937 random number generator in quicksort function

I'm trying to write a quicksort function that sorts within a range using a start and end parameter. The problem is, I need to use a random pivot in the quicksort and my random number generator is throwing an exception. I have looked everywhere to see what I'm doing wrong but cannot figure it out at all.

Here is my function(s)

    static random_device rd;
    static mt19937 rng(rd());

    template <typename T>
 int partition(T array[], const int start, const int end){
     uniform_int_distribution<int> distribution(start, end);
     int randIndex = distribution(rng); 

      swap(array[randIndex], array[end]);
      auto pivot = array[end];
      int i = start + 1;
     for (int j = start; j < end; j++)
     {
         if (array[j] < pivot)
         {
             i++; 
             swap(array[i], array[j]);
         }
     }
     swap(array[i + 1], array[end]);
         return i + 1; 
 }
 template <typename T>
 void quickSort(T array[], const int start, const int end) {
     if (start < end) 
     {
         int pivotIndex = partition(array, start, end);
         quickSort(array, start, pivotIndex - 1);
         quickSort(array, pivotIndex + 1, end);
     }

 }

I want the pivot index to be created using the RNG but it breaks before the pivot index can be initialized. Any ideas as to why this is occurring?




Name of this sorting algo [closed]

from numpy import random
leng = random.randint(1,25)
x = list(random.randint(100, size=leng))
a = sorted(x)

for i in range(int(len(x)/2)):
    mini = min(x[i:len(x)-i])
    maxi = max(x[i:len(x)-i])
    #insert mini to the beginning of the list
    x.pop(x.index(mini))
    x.insert(i,mini)
    #insert maxi to the beginning of reverserd list a.k.a the ending of the unreversed list
    x.reverse()
    x.pop(x.index(maxi))
    x.insert(i, maxi)
    x.reverse()
    
if sorted(x) == a:
    print('I DON\'T KNOW HOW I DID IT BUT IT WORKS')
    print(x)
    print(len(x))`

I am very new to codeing and I recently found out that interviewers often ask about sorting algos and I tried one out myself. I don't know any specifics about it though. I would like to request help in analyzing it. Is it any good? What's it called? How do I calculate time and memory efficieny?

Any help is welcommed!!!




mercredi 4 octobre 2023

How to map a signed integer in range A..B into a subrange C..D?

I have a signed random integer in range A..B. What is the formula to map from A..B into a subrange C..D where C >= A and D <= B?

For unsigned integers, I can use A + (num % (B - A)). What's the equivalent of this for signed?




Retrieving the same value from multiple arrays

so I have two arrays each has 3 values. I need 2 random values ​​from each array. For example: From arr1 "red", "blue" and from arr2 "red", "blue". I need to randomly get the same keys from two arrays. and change the keys every time the page is updated. If you get keys 1 and 2 from arr1, then from arr2 you should also get keys 1 and 2, or from arr1 3 and 2, and from arr2 also 3 and 2. everything is random.

Code:
$arr1 = ['green', 'red', 'blue'];
$arr1 = ['green', 'red', 'blue'];
for ($i = 0; $i < 2; $i++){
echo $arr1[$i];
echo $arr2[$i];
}

I don't know how to implement this. I used the shuffle and rand functions but they don't work. shuffle gives incorrect results.




Importing a random number from another module is returning the same random number

I am going to give a simple but reproducible example here (and not from my project).

I have 2 modules at the same level:- test_rand.py and test_import.py

test_rand.py has the below code:

from numpy import random
random_number = random.randint(0,1000)

test_import.py has the below code:

for i in range(5):
    from test_rand import random_number
    print(random_number)

Running test_import.py results in the same number getting printed 5 times. The behaviour I want is to print a different number every time I import random_number.

I know one option here is to import just the randint method in test_import.py and then execute it in test_import.py itself - this option is going to require a big change in the project
But is there another way where in the imported namespace can get deleted automatically while a second import happens (in the for loop)




How to convert a very long random binary characters to decimal fraction numbers between 0 and 1 with a specified number of decimal places

Suppose we possess a text file containing a sequence of millions of randomly generated 0's and 1's, all placed on a single line, like so:

101001011010010011110010001011101010000110101110...

Now, the objective is to utilize this file to generate random decimal fraction numbers, each with precisely 12 decimal places and within the range of 0 to 1:

0.961327557844 0.896041313452 0.144702102262 0.579717079181 0.489590501513 0.116786593965 ... However, this seemingly straightforward task presents a challenge. Each digit must be produced with the same probability without using random functions!

What would be the correct and efficient solution to address this issue and generate random decimal numbers with the desired properties?

I recieved a solution from somebody but it did not work! Step 1: Start by reading the binary data from the file in reasonably sized chunks. Step 2: Convert each binary chunk into an integer. Step 3: Normalize the integer value to obtain a floating-point number between 0 and 1. Step 4: Round the resulting floating-point number to 12 decimal places.




mardi 3 octobre 2023

Inconsistent Execution Time of RAND_bytes in OpenSSL during Benchmarking

I'm benchmarking the RAND_bytes function from the OpenSSL library in C for cryptographic operations. However, I've encountered an issue where the execution time for this function is highly inconsistent. Every time I run the benchmark, the elapsed time varies significantly. This variability makes it challenging to obtain a consistent benchmark result. Is this variability in execution time an expected behavior for RAND_bytes?

Here's a simplified version of my code that measures the time taken:

#include <stdio.h>
#include <openssl/rand.h>
#include <sys/time.h>

// Function to get the current time in microseconds
long long current_time_microseconds() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (long long)tv.tv_sec * 1000000LL + tv.tv_usec;
}

int main() {
    unsigned char buffer[128];
    long long start_time, end_time;

    start_time = current_time_microseconds();
    if (RAND_bytes(buffer, sizeof(buffer)) != 1) {
        // Handle error
        fprintf(stderr, "Error generating random bytes.\n");
        return 1;
    }
    end_time = current_time_microseconds();

    printf("Time taken (microseconds): %lld\n", end_time - start_time);
    return 0;
}

Is there an inherent reason within the RAND_bytes function or its implementation in OpenSSL that might cause such variability in execution time? And is there any way to mitigate this inconsistency to get more stable benchmark results?




php to generate random links not working - WordPress

Let me explain - I made a PHP that SORTA works, but it could be better - basically, the PHP is assigned to an image module on WordPress that when clicked; is supposed to take the user to a random PROJECT on the site. The problem is; while the function works, I keep getting the same projects repeated over and over; we have probably about 12 projects and I can't click the module more than 4 times before getting the same project that I saw previously. I need to generate a php that takes the user to a portfolio PROJECT without there being an overlap (i.e. being able to rifle randomly all 12 without overlapping). See below for the code

THANK YOU VERY MUCH, CHEERS!

<?php
class ICE_CREAM_CONE extends ET_Builder_Module {
    // Module slug (also used as shortcode tag)
    public $slug = 'ice_cream_cone';


    // Full Visual Builder support
    public $vb_support = 'on';


    /**
     * Module properties initialization
     *
     * @since 1.0.0
     */
    function init() {
        $this->name = esc_html__( 'Ice Cream Cone', 'ak-text-domain' );
    }


    /**
     * Module's specific fields
     *
     * @since 1.0.0
     *
     * @return array
     */
    function get_fields() {
        return array(
            'image' => array(
                'label'             => esc_html__( 'Image', 'ak-text-domain' ),
                'type'              => 'upload',
                'toggle_slug'       => 'ice_cream_cone'
            )
        );
    }


    function get_settings_modal_toggles() {
        return array(
            'content' => array(
                'toggles' => array(
                    'ice_cream_cone' => array(
                        'priority' => 0,
                        'title' => 'Ice Cream Cone'
                    )
                )
            )
        );
    }


    function getProjects() {
        $output = '';
        $currentPost = get_post();


        $args = array(
            'post_type' => 'project',
            'orderby' => 'rand',
            'posts_per_page' => 1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'project_category',
                    'field' => 'slug',
                    'terms' => 'ice_cream_cone'
                )
            )
        );


        if ( is_singular( 'project' ) ) {
            $args['post__not_in'] = array( $currentPost->ID );
        }


        $query = new WP_Query($args);


        if ( $query->posts ) {
            foreach( $query->posts as $p ) {
                $output = get_permalink( $p->ID );
            }
        }


        return $output;
        $can_visit_pages = array_diff($all_page_links,$visited_page_links);




    }
    


    /**
     * Render module output
     *
     * @since 1.0.0
     *
     * @param array  $attrs       List of unprocessed attributes
     * @param string $content     Content being processed
     * @param string $render_slug Slug of module that is used for rendering output
     *
     * @return string module's rendered output
     */
    function render( $attrs, $content = null, $render_slug ) {
        // Module specific props added on $this->get_fields()
        $image = $this->props['image'];


        // Render module content
        $output = sprintf(
            '<div class="ice-cream-cone-container"><a href="%2$s"><img src="%1$s" /></a></div>',
            esc_html( $image ),
            $this->getProjects()
        );


        // Render wrapper
        // 3rd party module with no full VB support has to wrap its render output with $this->_render_module_wrapper().
        // This method will automatically add module attributes and proper structure for parallax image/video background
        return $this->_render_module_wrapper( $output, $render_slug );
    }
}


new Ice_Cream_Cone;```


Crafting a code to generate random projects - the projects genreate but overlap frequently



C# using a picture box to get a randomized picture

I have imported 5 images into the resources folder on my project. The image names are Blackcar, Redcar, Bluecar, Yellowcar, Greencar. When I run this program I want the picturebox to randomly display one of these images so it is different everytime I run this program.

    private void Form1_Load(object sender, EventArgs e)
    {
        String[] imgs = { "Blackcar", "Bluecar", "Greencar", "Yellowcar," "Redcar" };
        int randomIndex;
        Random r = new Random();

        randomIndex = r.Next(imgs.Length);
        pictureBox1.Image = imgs[randomIndex];
    }

I know i cannot convert the string array to the picture box, but Im not sure how to make this work.




How to test distribution of the random class

When a user gets a random number within a certain range through a random class, the distribution of the number obtained will be very even if the test is ran very much. In short, the distribution is flat. I want to make a code that proves this content in Java. Simply running the code indefinitely is not very practical. What ideas could there be?




lundi 2 octobre 2023

C-Sharp -- Generating random integers from nonrandom seeds

I'm making a game, and every now and then a number of objects in the game need to know whether or not the player has moved. Because of the large numbers of objects involved, instead of alerting every object every frame, I've sorted them into bins with corresponding events. Bin 1 is alerted the first frame the player moves, then bin 2 the second frame, etc, up to some finite number.

However, I need some consistent way to assign each object a bin. Just using the object ids isn't working, as the way that the objects are generated gives patterns in their ids that may result in some bins being filled more or less than others, which decreases the gains in efficiency. If all the ids are even and so is the bin size, then only the even bins will be filled.

In short, the problem is this:

Given a sequence of non-random, unknown, unique integers S that may or may not have a pattern, how can I choose a hashing algorithm H and number of bins p so that H(S[i]) % p forms a roughly uniform distribution?

Simply choosing a prime number as the number of bins seems to be a good start, but I'm wondering if there's a hashing algorithm I can use to "scramble" the patterns of the input sequence and improve uniformity. Ideally, one already included in .Net.

Edit:

I've found some promising results in this answer. I'm still curious about this problem though, both from a mathematical perspective and whether there are tools to do this included in .NET.




Stop function random number

i want stop this function with a button, what can i do for that working ?

Thanks

var module = angular.module('numberApp', []);

module.controller('NumberController', function($scope, $timeout) {
    (function update() {
    $timeout(update, 1000 * 15);
    $scope.randomNumber = Math.floor(Math.random()*($scope.max-$scope.min+1)+$scope.min);
  }());

please help me to stop this function with a button ;-)




dimanche 1 octobre 2023

How can I generate a Bernoulli random integer array in rust?

I am trying to create a random 2D array in which each entry is 0 with probability p and 1 otherwise. In python, numpy makes it simple:

rand_arr = (np.random.rand(nrows, ncols) < p).astype(np.dtype('uint8'))

In rust, I wrote something like this

use rand::Rng;
use rand::distributions::Bernoulli;
use ndarray::{Array2};

// Create a random number generator
let mut rng = rand::thread_rng();

// Create a Bernoulli distribution with the given probability
let bernoulli = Bernoulli::new(p).unwrap();

// Generate a 2D array of random boolean values using the Bernoulli distribution
let rand_arr: Array2<bool> = Array2::from_shape_fn((nrows, ncols), |_| {
    rng.sample(bernoulli)

// convert bools to 0 and 1
let rand_arr = data_round_errors.mapv(|b| if b { 1 } else { 0 });
});

This is awfully slow. About 30 times slower than the python version! Which tells me I am doing something wrong. How can I write a faster implementation of this?




Determine different seeds for which random shuffling list generates the same output

It is pretty intuitive that when shuffling a small enough collection, results will repeat themselves, even using different seeds each time, as it is just a matter of exhausting all unique combinations.

However, I can't find such information in the Python documentation. I am especially curious if there is any formula or algorithm to determine the different seed values for which the output would be identical. Is it possible to somehow forecast or calculate these seeds?

At first sight, I couldn't see any pattern or regular offset, and now it intrigues me if it's possible to find one 😁

I'm pasting the snippet of the code that I reproduced several times on my machine and within the online REPL.

import random

a = ["a", "b", "c", "d", "e"]
b = list(a)
c = list(a)

random.seed(0)
random.shuffle(a)
random.seed(344)
random.shuffle(b)
random.seed(496)
random.shuffle(c)

print(a == b == c == ["c", "b", "a", "e", "d"])  # True



how to compare user input for a password that matches a randomized challange response password?

im creating a code that asks the user to input their password as digits from a randomly generated string of digits between 1 and 3 that is beneath.

for example,

pin: 0 1 2 3 4 5 6 7 8 9

ran: 1 2 2 3 1 2 1 3 2 1

if the user's password is 56789, they would need to enter 21321

import random

# Store the actual PIN as a list of integers
pin = [5, 6, 7, 8, 9]

# Generate random numbers for digits 0 to 9
randNumbers = [random.randint(1, 3) for x in range(10)]

# Create lists to map random numbers to digits
random_to_digit = [None, '0', '1', '2']

# Output digits 0-9 in a single line
print("PIN:", end=' ')
for i in range(10):
    print(i, end=' ')

# Output the corresponding random digits below in a single line
print("\nNUM:", end=' ')
for i in range(10):
    print(random_to_digit[randNumbers[i]], end=' ')

# Request and get the input response from the user
pwdEntry = input("\nPlease enter your converted password: ")

if pwdEntry[0] == randNumbers[5] and pwdEntry[1] == randNumbers[6] and pwdEntry[2] == randNumbers[7] and pwdEntry[3] == randNumbers[8] and pwdEntry[4] == randNumbers[9]:
    print("success")
else:
    print("failure")

i tried comparing each item the user entered to the position in the list that the correct digit they would need to enter since the password 56789 is constant but it always results in failure.




Why does the range element in my code have problems when is uses the last number?

I am using the following code, which just selects a random number from a range and uses it as chance for other elements to be selected, and it works fine with no errors, but occasionally the number that it selects from the range(usually the last number like 16 or 20) does not work, and I don't know why.

Code:

import random

# List used for Age Classifications
ageClass = ["Newborn", "Young", "Aged", "Old", "Ancient", "Timeless"]
randAgeClass = ""
randAge = 0

# Probability of age classes
# Newer classes are much more likely to be selected than the older classes
chance = random.randrange(1, 20)
# Chance Debug
print(chance)

if chance in range(1, 5):
    randAgeClass = "Newborn"
elif chance in range(6, 10):
    randAgeClass = "Young"
elif chance in range(11, 13):
    randAgeClass = "Aged"
elif chance in range(14, 16):
    randAgeClass = "Old"
elif chance in range(17, 18):
    randAgeClass = "Ancient"
elif chance in range(19, 20):
    randAgeClass = "Timeless"
else:
    print("error")

# If statements for age classes
if randAgeClass == "Newborn":
    randAge = random.randrange(1, 20)
elif randAgeClass == "Young":
    randAge = random.randrange(21, 80)
elif randAgeClass == "Aged":
    randAge = random.randrange(81, 250)
elif randAgeClass == "Old":
    randAge = random.randrange(251, 500)
elif randAgeClass == "Ancient":
    randAge = random.randrange(501, 1000)
elif randAgeClass == "Timeless":
    randAge = random.randrange(1001, 6000)
else:
    print("error")

print("Vampire Name: Steve")
print("Age Classification:", randAgeClass)
print("Age:", randAge)

Here is how a successful output looks like: enter image description here

And here is how an unsuccessful output looks like: enter image description here

This only seems to be happening if the random number in the range that is chosen is the last number in the range like 5, 10, 16... Why is this happening and how do I fix this?

I tried using a list and that didn't work, so I would rather just use a range for this.




Generating unique random numbers from non-unique random numbers

The following function converts a list of non-unique random numbers into a list of unique random numbers using a helper list of sequential integers:

def get_d(rlist):
    # t[] is a list of ints 0..n-1 where n is big
    # enough not to cause issues when deleting items
    t  = list(range( len(rlist) + max(rlist) ))
    d  = []            # the output list we will populate
    for r in rlist:
        d.append(t[r]) # add r'th remaining item in t[] to d[]
        t.pop(r)       # delete that item from t[]
    return d

e.g.
get_d([3, 2, 3, 1, 5]) = [3, 2, 5, 1, 9]

I would like to get the same output using a counting method or other method. This is my attempt, which has some edge case or perhaps more fundamental issues:

def get_e(r):
    e = []
    for i,t in enumerate(r):
        c = 0
        # track numbers <= the current one
        for j in range(i):
            if r[j] <= t:
                c+=1
        # track numbers <= the current one when virtual deletions are accounted for
        for j in range(i):
            if r[j] > t and r[j]-c <= t:
                c+=1
        e.append(t+c)
    return e

Here is a test:

for r in [ [3,2,3,1,5], [0,0,1,0,0]]:
    d = get_d(r)
    e = get_e(r)
    print('match:   ' if d==e else 'mismatch:', r, '  : ',  d, '  ', e)


Output: 
match:    [3, 2, 3, 1, 5]   :  [3, 2, 5, 1, 9]    [3, 2, 5, 1, 9]
mismatch: [0, 0, 1, 0, 0]   :  [0, 1, 3, 2, 4]    [0, 1, 3, 3, 4]