vendredi 31 décembre 2021

Randomly Assign Value

I am working on a program that is supposed to assign a female dancer partner to a male dance partner. The user selects a male dancer and the program should randomly assign a female dancer, and then remove both of the chosen dancers from the original list. In my coding class, I was never taught how to randomly assign like this. Here is the code that I have so far:

import random


maledancers = {"Maciek", "Marek", "Marcel", "Carson", "Brett", "Connor"}
femaledancers = {"Renata", "Karolina", "Maja", "Natalia", "Olivia", "Meghan"}



print("You will be pairing the male dancers with the female dancers.")
print("You will select one of the male dancers and it will get paired with a female dancer randomly")

dancer = input("Out of the male dancers, please select one to be paired: ")

if dancer not in maledancers:
    print("Your choice is not in the list of dancers, please re-enter a dancer from the list")
if dancer in maledancers:
    print("Great we will now randomly give " + dancer + " a partner to dance with")
if dancer.isdigit():
    print("The dancer can't have any numbers in their name. Try again please!")

If anyone has any input as to what I can do here, I'd really appreciate any help. If you answer this question, please show the change in code. Thanks in advance!




Randomize two csv files but with the indexes in the same order

I have two csv files, with multiple columns with text. They both have the same text, but in different languages. So for example csv1 would look like:

header1               header2
How are you           Good
What day is it        Friday
Whats your name       Mary

And csv2 would be:

header1               header2
Qué tal estás         Bien
Qué dia es            Viernes
Cómo te llamas        María

Now I want to randomize them both, but I need the translations to still be in the same order. In other words, I need the order of the indexes to be the same: if index 1 is ramdomized to be the last in csv1, I want the same for csv2:

header1               header2
What day is it        Friday
Whats your name       Mary
How are you           Good


header1               header2
Qué dia es            Viernes
Cómo te llamas        María
Qué tal estás         Bien

This is what I have done:

import pandas as pd

df = pd.read_csv('train.csv')

data = df.sample(frac=1)

However with this code, both csv files end up with different orders. Is there a way to randomize the files but fixing the order of the indexes?

I apologize if something is not well explained, it's my first time both in this website and coding.




Why doesn't rand() function work the second time i call my own function?

I was planning to make a snake game on CMD by using arrays in C language, i've coded the parts of board creating and the game, it wasnt done totally yet, but i have to create also the snake and the food in the table.

I was trying to debug the program, and i've found out that rand() function doesnt work the second time i use my function, also it crashes when i try to call those functions more than once. I couldn't solve why.

int main()
{

int row,column;
create_snake(row,column,2);
create_snake(row,column,3);
}
void create_snake(int row,int column,int x){

srand(time(NULL));

row=rand()%25;
column=rand()%64;
}

here is the full code (not fully done yet but it crashes)

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

int board[25][64];

void create_snake(int,int,int);


int main()
{

int row,column;

for(int i=0;i<25;i++){   //creating board
        for(int a=0;a<64;a++){
              if(i == 0 || i == 24){
            board[i][a]=1;
            }else if(a == 0 || a==63){
            board[i][a]=1;
            }else{
                board[i][a]=0;
            }
        }
    }

create_snake(row,column,2); //creating snake



/*for(int i=0;i<25;i++){
        for(int a=0;a<64;a++){
        printf("%d",board[i][a]);
}
printf("\n");
}
*/
create_snake(row,column,3); //creating food

}



void create_snake(int row,int column,int x){

srand(time(NULL));

row=rand()%25;
column=rand()%64;

printf("%d   %d",row,column);
printf("\n");
/*if(board[row][column]==1){
  // create_snake(row,column,x);

}else if(board[row][column]==0){
    board[row][column]=x;

}else{
    //create_snake(row,column,x);
}
*/
}
v



Generate random string using regular expression condition using Java [closed]

I want to generate random string using this regular expression

[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}

and generate the string like this eg: 66912e1b-7cae-49e4-a342-211223133628. using Java i need to implement, can you suggest best way to achieve this.




jeudi 30 décembre 2021

Multithreading in c++ as a random number generator

I was reading up on multithreading in c++ and found out that if you'd run code like

#include <isostream>
#include <thread>

void function1(){
    for(int i = 0; i<200; i++){
        std::cout << '+';
    }
}
void function2(){
    for(int i = 0; i<200; i++){
        std::cout << '-';
    }
}
int main() {
    std::thread worker1(function1);
    std::thread worker2(function2);
    
    system("pause>nul");
}

The plusses and minusses are in random order as this is dependent on what thread is finishing first, my question is then if this form of racing between threads could be a good random number generator and why (not).
Thanks in advance




Is it possible to get a random value within a group in a group by query?

I would like to get random values within a group-by query, something like this:

SELECT city
  , SOME_RANDOMIZER_FUNC(latitude) as "RANDOM_LATITUDE_IN_CITY"
  , SOME_RANDOMIZER_FUNC(longitude) AS "RANDOM_LONGITUDE_IN_CITY"
FROM some_table
GROUP BY city

Where the function SOME_RANDOMIZER_FUNC returns a random value within the group.




Generate truly random numbers with C++ (Windows 10 x64)

I am trying to create a password generator. I used the random library, and after reading the documentation, I found out that rand() depends on an algorithm and a seed (srand()) to generate the random number. I tried using the current time as a seed (srand(time(0))), but that is not truly random. Is there a way to generate truly random numbers? Or maybe get the current time very accurately (like, in microseconds)? My platform is Windows 10 x64.




Random sample from specific rows and columns of a 2d numpy array (essentially sampling by ignoring edge effects)

I have a 2d numpy array size 100 x 100. I want to randomly sample values from the "inside" 80 x 80 values so that I can exclude values which are influenced by edge effects. I want to sample from row 10 to row 90 and within that from column 10 to column 90.

However, importantly, I need to retain the original index values from the 100 x 100 grid, so I can't just trim the dataset and move on. If I do that, I am not really solving the edge effect problem because this is occurring within a loop with multiple iterations.

gridsize = 100
new_abundances = np.zeros([100,100],dtype=np.uint8)
min_select = int(np.around(gridsize * 0.10))
max_select = int(gridsize - (np.around(gridsize * 0.10)))
row_idx =np.arange(min_select,max_select)
col_idx = np.arange(min_select,max_select)

indices_random = ????? Somehow randomly sample from new_abundances only within the rows and columns of row_idx and col_idx set.

What I ultimately need is a list of 250 random indices selected from within the new_abundances array.




mardi 28 décembre 2021

R: Selecting Rows Based on Conditions Stored in a Data Frame

I am working with the R programming language.

I have the following dataset:

num_var_1 <- rnorm(1000, 10, 1)
num_var_2 <- rnorm(1000, 10, 5)
num_var_3 <- rnorm(1000, 10, 10)
num_var_4 <- rnorm(1000, 10, 10)
num_var_5 <- rnorm(1000, 10, 10)

factor_1 <- c("A","B", "C")
factor_2 <- c("AA","BB", "CC")
factor_3 <- c("AAA","BBB", "CCC", "DDD")
factor_4 <- c("AAAA","BBBB", "CCCC", "DDDD", "EEEE")
factor_5 <- c("AAAAA","BBBBB", "CCCCC", "DDDDD", "EEEEE", "FFFFFF")

factor_var_1 <- as.factor(sample(factor_1, 1000, replace=TRUE, prob=c(0.3, 0.5, 0.2)))
factor_var_2 <-  as.factor(sample(factor_2, 1000, replace=TRUE, prob=c(0.5, 0.3, 0.2)))
factor_var_3 <-  as.factor(sample(factor_3, 1000, replace=TRUE, prob=c(0.5, 0.2, 0.2, 0.1)))
factor_var_4 <-  as.factor(sample(factor_4, 1000, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))
factor_var_5 <-  as.factor(sample(factor_4, 1000, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))

my_data = data.frame(id,num_var_1, num_var_2, num_var_3, num_var_4, num_var_5, factor_var_1, factor_var_2, factor_var_3, factor_var_4, factor_var_5)


> head(my_data)
  id num_var_1 num_var_2 num_var_3 num_var_4  num_var_5 factor_var_1 factor_var_2 factor_var_3 factor_var_4 factor_var_5
1  1  9.439524  5.021006  4.883963  8.496925  11.965498            B           AA          AAA         CCCC         AAAA
2  2  9.769823  4.800225 12.369379  6.722429  16.501132            B           AA          AAA         AAAA         AAAA
3  3 11.558708  9.910099  4.584108 -4.481653  16.710042            C           AA          BBB         AAAA         CCCC
4  4 10.070508  9.339124 22.192276  3.027154  -2.841578            B           CC          DDD         BBBB         AAAA
5  5 10.129288 -2.746714 11.741359 35.984902 -10.261096            B           AA          AAA         DDDD         DDDD
6  6 11.715065 15.202867  3.847317  9.625850  32.053261            B           AA          CCC         BBBB         EEEE

Based on the answer provided from a previous question (R: Randomly Sampling Mixed Variables), I learned how to randomly take samples from this data:

library(dplyr)
 library(purrr)

# calc the ratio of choosing variable
var_num <- ncol(my_data) - 1
var_select_ratio <- sum(1:var_num) / (var_num^2)

num_func <- function(vec, iter_num) {
  random_val = runif(iter_num, min(vec), max(vec))
  is_select <- sample(c(NA, 1), iter_num, 
                      prob = c(1 - var_select_ratio, var_select_ratio), replace = TRUE)
  return(random_val * is_select)
}

fac_func <- function(vec, iter_num) {
  nlevels <- sample.int(length(levels(vec)), iter_num, replace = TRUE)
  is_select <- sample(c(0, 1), iter_num, 
                      prob = c(1 - var_select_ratio, var_select_ratio), replace = TRUE)
  out <- map2(nlevels, is_select,  # NOTE: this process isn't vectorized
              function(nl, ic){
                if(ic == 0) NULL else sample(vec, nl)
              })
  return(out)
}

integ_func <- function(vec, iter_num) {
  if(is.factor(vec)) fac_func(vec, iter_num) else num_func(vec, iter_num)
}


# if you want to paste factor_var
res2 <- res %>% 
  mutate_if(is.list, function(col) map_chr(col, function(cell) paste(sort(cell), collapse = " "))) %>%   # paste
  mutate_if(is.character, function(col) na_if(col, ""))  # replace "" to NA

This produces the following results:

 > res2 = data.frame(res2)

> res2
   num_var_1 num_var_2  num_var_3 num_var_4  num_var_5 factor_var_1 factor_var_2    factor_var_3             factor_var_4             factor_var_5
1   8.251683 27.791314  30.525573  33.95768   2.388074            B         <NA>             AAA                     AAAA                     DDDD
2   9.012602        NA         NA        NA  20.236515            A        AA BB            <NA>                     <NA>                     BBBB
3         NA 16.778085  28.097324   5.69020         NA            B           BB     CCC DDD DDD                     <NA> AAAA BBBB CCCC CCCC CCCC
4  12.838667 -3.694075  13.411877  -2.20004         NA         <NA>     AA AA BB     AAA BBB CCC                     <NA> AAAA AAAA BBBB CCCC DDDD
5         NA        NA  11.922439  17.63757         NA          A B     AA AA BB            <NA>                AAAA AAAA                     BBBB
6  12.768595        NA  28.507646        NA         NA            C           AA     BBB DDD DDD      AAAA AAAA CCCC DDDD AAAA AAAA BBBB EEEE EEEE
7         NA        NA -20.424906        NA  20.147004         <NA>        AA AA            <NA> AAAA AAAA AAAA CCCC EEEE                     <NA>
8         NA  6.299722   8.569485  24.82825 -17.715862         <NA>           BB AAA AAA BBB CCC                     <NA>                BBBB EEEE
9  10.846757        NA         NA        NA         NA        A B C     AA BB CC            <NA>                     <NA>                BBBB BBBB
10        NA  4.663916  22.335404        NA         NA        B B C        AA BB AAA AAA AAA DDD AAAA AAAA CCCC EEEE EEEE                     <NA>

My Question: Is it possible to take conditions from different rows in "res2" and use them to perform operations on "my_data"? For example:

  • If you take the 6th row and 10th row from "res2" : res2[c(6,10),]

  • In Row 6: num_var_2 = NA, num_var_4 = NA and num_var_5 = NA

  • In Row 6: num_var_1 = 12.768595 , num_var_3 = 28.507646, factor_var_1 = C, factor_var_2 = AA, factor_var_3 = BBB DDD DDD, factor_var_4 = AAAA CCCC DDDD, factor_var_5 = AAAA BBBB EEEE EEEE

  • In Row 10: num_var_1 = NA, num_var_4 = NA num_var_5 = NA, factor_var_5 = NA

  • In Row 10: num_var_2 = 4.663916, num_var_3 = 22.335404 , factor_var_1 = B C, factor_var_2 = BB CC, factor_var_3 = AAA DDD, factor_var_4 = AAAA CCCC DDDD, factor_var_5 = AAAA CCCC EEEE

I want to perform the following operation:

Step 1: where my_data$num_var_1 = 12.768595 , my_data$num_var_3 = 28.507646, my_data$factor_var_1 = C, my_data$factor_var_2 = AA, my_data$factor_var_3 = BBB DDD DDD, my_data$factor_var_4 = AAAA CCCC DDDD, my_data$factor_var_5 = AAAA BBBB EEEE EEEE

Step 2 (using the data from Step 1): Take columns "my_data$num_var_2 , my_data$num_var_4 and my_data$num_var_5" and replace a random 30% of elements in these columns with 0

Step 3 (using the data from Step 2): where my_data$num_var_2 = 4.663916, my_data$num_var_3 = 22.335404 , my_data$factor_var_1 = B C, my_data$factor_var_2 = BB CC, my_data$factor_var_3 = AAA DDD, my_data$factor_var_4 = AAAA CCCC DDDD, my_data$factor_var_5 = AAAA CCCC EEEE

Step 4 (using the data from Step 3): Take columns "my_data$num_var_1 , my_data$num_var_4 and my_data$num_var_5, my_data$factor_var_5" and replace a random 35% of elements in these columns with 0

Is it possible to directly perform Step 1 - Step 4 using "my_data" and "res2"?

Currently, I can do this manually (R: Randomly Changing Values in a Dataframe).

Can someone please show me how to do this?

Thanks!




lundi 27 décembre 2021

Question Regarding Random Number Generation in Lua

I was playing around with the lua interpretor and made this little program that generates two numbers and compares them. The program runs until the numbers match. The first number is randomly generated using math.random(), and is set to 1, and 100000. The second value that is generated to compare is between 1 and 100. It also keeps track of how many times the program loops. The program works as intended, but something strange happens when I run it.

The values that come up are always either 1, 31, 62, or 92. I've run the program many times, but it keeps generating these numbers. I have some understanding of how random numbers are generated, but this just seems weird. I'll paste the code in below. If someone can explain what's going on here, I would appreciate it greatly. Thanks!

counter=0;
a=0;
b=1;
while(a~=b)do
    a=math.random(1,1000000);
    b=math.random(1,100);
    counter=counter+1;
    if(a==b)then
         print(a..", "..b..", and it took "..counter.." times")
    end
end



dimanche 26 décembre 2021

Can you help me to create 4 unique numbers from 1-10 in C#?

I have a problem with a Script in my Game. I have 6 Lanes in my Game and 4 Enemys at the moment. If an Enemy reaches the end of a lane, he respawns in a new lane. I want that no Enemy ever gets the same lane as above.

I did it like this

                    Randomlane = rnd.Next(1, 7);
                    Enemy1_Lane = Randomlane;

                    if (Enemy1_Lane == Enemy2_Lane)
                    {
                        if (Enemy1_Lane == 6)
                        {
                            Enemy1_Lane -= 1;
                        }
                        else
                        {
                            Enemy1_Lane += 1;
                        }
                    }

But this only works with 2 Enemys. Now I have 4. Maybe you can help me.




vendredi 24 décembre 2021

How to determine if one digit in the user's lottery pick matches a digit in the lottery number?

Problem: Write a c program that will allow the user to play Lottery for as long as he/she wanted to. The program randomly generates a lottery of a two-digit number, prompts the user to enter a pick of two-digit number, and determines whether the user wins according to the following rules:

  1. If the user’s pick matches the lottery number in the exact order, the prize at stake is P8,000.
  2. If all digits in the user’s pick match all digits in the lottery number, the prize at stake is P5,000.
  3. If one digit in the user’s pick matches a digit in the lottery number, the prize at stake is P2,000.

Required knowledge: Generating random numbers, comparing digits, using Boolean operators, selection and looping structures.

I'm stuck on the third requirement — can you help?

This is my code so far...

#include <stdio.h>
#include <stdlib.h>
int main()
{
    srand((unsigned)time(0));
    int guess, guess2, lottoNum2, lottoNum3, lottoNum4, ones;
    int lottoNum = rand() % 100;

    printf("The lottery number is %d\n", lottoNum);

    printf("Enter your lottery pick (two digits): ");
    scanf("%d", &guess);

    if (guess == lottoNum)
        printf("\nExact match: you win P8,000");

    while (lottoNum != 0)
    {
        ones = lottoNum % 10;
        lottoNum2 = lottoNum2 * 10 + ones;
        lottoNum /= 10;
    }
    if (guess == lottoNum2)
        printf("\nMatch all digits: you win P5000\n");

    while (lottoNum != 0)
    {
       

    if (guess != lottoNum)
    printf("\nSorry, there is no digit match!");
}



jeudi 23 décembre 2021

Conditionally sample unique IDs on column value = 1 and first date condition

Background

I've got a dataset d:

d <- data.frame(ID = c("a","a","b","b", "c","c"),
                event = c(0,1,0,0,1,1),
                event_date = as.Date(c("2011-01-01","2012-08-21","2011-12-23","2011-12-31","2013-03-14","2015-07-12")),
                entry_date = as.Date(c("2009-01-01","2009-01-01","2011-09-12","2011-09-12","2005-03-01","2005-03-01")),
                stringsAsFactors=FALSE)

It looks like this:

current

As you can see, it's got 3 ID's in it, an indicator of whether they had the event, a date for that event, and a date for when they entered the dataset.

The Problem

I'd like to do some sampling of ID's in the dataset. Specifically, I'd like to sample all the rows of any distinct ID who meet the following two conditions:

  1. Has any event=1
  2. The date of their first (chronologically earliest) event_date row is greater than 365 days but less than 1095 days (3 years) from their entry_date.

Desired result

If you look at each of the 3 ID's, you'll see that only ID= a meets both of these criteria: this person has an event=1 in their second event record, and the date of their first event record is between 1 and 3 years from their entry_date (2011-01-01 is exactly two years from their entry date).

So, I'd like a dataframe that looks like this:

enter image description here

What I've tried

I'm halfway there: I've managed to get the code to meet my first criterion, but not the second. Have a look:

d_esired <- subset(d, ID %in% sample(unique(ID[event == 1]), 1))

How can I add the second condition?




Get a random id from an array that does not exist in two other arrays

I am trying to generate a random ID on a very explicit set of requirements.

There are 3 arrays itemsAvailable, itemsSeen, and itemsTaken.

itemsAvailable looks like this: [{ id: 1, ... }, ...] an array of objects with various fields, the other fields don't matter for the purposes of this functionality, we are only concerned with the id field. It is a number that is 1 -> X, X increasing by 1 for each item present.

itemsSeen is just an array of the ids that a user has seen, so if they saw ids for 1, 7, 16 it would look like itemsSeen = [1, 7, 16].

itemsTaken is also just an array of the ids they have seen that they chose to take, for example, itemsTaken = [1, 16]. They can only take items that have been present in itemsSeen.

At the start of the function, a random id is generated based on the length of itemsAvailable. Each item's id will match its index position.

If itemsSeen or itemsTaken includes the random id, generate a new one in the bounds of the length of itemsAvailable until it is not present in either array.

When a number is generated and shown to the user, it should be added to itemsSeen array. If that item is picked it should be added to itemsAvailable array. Then get a random item from itemsAvaialbe again.

code sandbox of what I have.




how to correct Error in mmer(y = y, Z = ETA, method = "EMMA") : unused arguments (y = y, Z = ETA) in MMER function?

Good Afternoon I am trying to reproduce the scenario1 of your SOMMERs package tutorial in R version 4.1.2 before applying to my data to Case1:Genotypic and phenotypic data for the parents is available and we want to predict performance of the possible crosses assuming a purely additive model (species with no heterosis) with below code

library(sommer)
data(wheatLines)
write.table(wheatLines,"wheatlinesgsdata.csv")
X <- wheatLines$wheatGeno;
X[1:5,1:5];
 dim(X)
Y <- wheatLines$wheatPheno
dim(Y)
rownames(X) <- rownames(Y)

#### select environment 1 and create incidence and additive #### relationship matrices
y <- Y[,1] # response grain yield
Z1 <- diag(length(y)) # incidence matrix
K <- A.mat(X) # additive relationship matrix

#### perform the GBLUP pedigree-based approach by ### specifying your random effects (ETA) in a 2-level list ### structure and run it using the mmer function
ETA <- list(add=list(Z=Z1, K=K))
ans <- mmer(y=y, Z=ETA, method="EMMA") # kinship based
names(ans)
summary(ans)
[/CODE]

after running above code i am getting error like in my question even after declaration of y and ETA
**Error in mmer(y = y, Z = ETA, method = "EMMA") : unused arguments (y = y, Z = ETA)**

Can anyone please help me where it went wrong and how to rectify it for my future work.
Thanking you very much



mercredi 22 décembre 2021

randcase called twice and return same value

In my Systemverilog TB I make 2 instance of module called "dcg_top":

    logic[0:1] cfi_clkreq;
    initial begin
        cfi_clkreq = '0;
            #1us;
            cfi_clkreq = 2'b11;
            #1us;
            cfi_clkreq = 2'b00;
        end

    dcg_top #(
       )cfi0(
        .clk_req('{cfi_clkreq[0]})
        );

    dcg_top #(
    )cfi1(
        .clk_req('{cfi_clkreq[1]})
        );

Each instance gets one bit of cfi_clkreq array as input. when clk_rek changed from 0 to 1 this task is called:

task clock_vc_dcg::wait_before_clk_ack();
        randcase
            20: async_delay_ps(20, 1);
            35: async_delay_ps(2500, 20);
            15: async_delay_ps(10000, 2500); 
            15: async_delay_ps(30000, 10000);
            10: async_delay_ps(30000, 10000);
            8 : async_delay_ps(100000, 30000);
            2 : async_delay_ps(200000, 100000);
        endcase
endtask : wait_before_clk_ack

As you can see in my TB I change clk_req from 00 to 11 so this task should be called twice, in the two instance. My problem is that in the both task call, the randcase returns the same value, even it called from separate instance. How can I fix it? I want randcase to return different value in each call. thanks!




Randomly generating a string of letters (C and S) and numbers in c# [closed]

I tried using 1 single random generator with the logical or | but for some reason it kept giving me the wrong outcome so i had this idea for now still it takes a bit to much to make it work is there is a better code in c# that would be very helpful.

using System;
namespace Potato
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int b = 0; b < 20; b++)
            {
                int[] pic1 = new int[3];
                Random charcters1 = new Random();
                Random charcterss1 = new Random();
                Random charctersss1 = new Random();
                Random Pic20 = new Random();
                int number10 = (charcters1.Next(48, 58)) ;
                pic1[0] = number10;
                int number20 = (charcterss1.Next(65, 91));
                pic1[1] = number20;
                int number30 = charctersss1.Next(97, 123);
                pic1[2] = number30;
                int number1 = Pic20.Next(0,3);
                int chosen1 = pic1[number1];
            Console.Write((char)chosen1);
            }
        }
    }
}



Wikipedia random articles, but only high quality ones?

I want to view random Wikipedia articles that are of high quality. E.g. featured, a-class, good, etc.

How?





generate a birthday date randomly in c

int nombreAlea(int min, int max){
    return (rand()%(max-min+1) + min);
}

int main () {
    srand(time(0));
    int annee=nombreAlea(1940,2003),mois=nombreAlea(1,12),jour;
    /// le traitement de la date
    if((mois==1)||(mois==3)||(mois==5)||(mois==7)||(mois==8)||(mois==10)||(mois==12)) jour = nombreAlea(1,31);
    if((mois==4)||(mois==6)||(mois==9)||(mois==11)) jour = nombreAlea(1,30);
    if(mois==2)
    {if (annee % 4 == 0 )
            jour = nombreAlea(1,28);
        else
            jour = nombreAlea(1,29);
    }
    
    /// the format of the date is  jj/mm/aaaa
    signed char Date[20];
    signed char jour_c[3],mois_c[3],annee_c[6];
    itoa(jour,jour_c,10);
    itoa(mois,mois_c,10);
    itoa(annee,annee_c,10);
    Date[0]=jour_c[0];
    Date[1]=jour_c[1];Date[2]='/';
    Date[3]=mois_c[0];Date[4]=mois_c[1];Date[5]='/';
    Date[6]=annee_c[0];Date[7]=annee_c[1];Date[8]=annee_c[2];Date[9]=annee_c[3];Date[10]='\0';
    printf("%s",Date); 
    
    return 0 ;
}

i want to generate a birthday day randomly , but the problem is that sometimes i get the half of the date , and smetimes i get only 2 caracters , and i don't understand where s the problem , any help !




generate a name in c randomly

 signed char *tab_alphabet[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","\0"};

int nombreAlea(int min, int max){
      return (rand()%(max-min+1) + min);
    }
void generer_name(int length,signed char* n){
  int i ;
  signed char *j;
  for (i=0;i<length;i++){
    int k = nombreAlea(1,26);// from the table of the alphabet
    j = tab_alphabet[k-1];
    strcat(n,j); 
  }
}

here s the main :

int main () {
    int a = nombreAlea(4,30);
   signed char *nn;
    generer_name(a,nn);
    return 0 ;
}

The problem is that the result always is preceeded with "a!!@" , any help , i have a doubt on the strcat




How to add random numbers on a numpy array?

I want to add random numbers between my numpy array. I want 2000 new numbers on a index in my numpy array. The numbers should be added over the second axis. The old random numbers should not be overwritten, they should stay and the new numbers should be added on a random place between them. Could you please help me with that?

That is what I have so far:

z = np.random.randint(40, 200, (40, 24))
for index_i, i in enumerate(z):
    for index_j, j in enumerate(i):
        #if the index is the first 6 (0-6) or the last 2 (22 and 23) make it random between 0 and 50
        if index_j in [0, 1, 2, 3, 4, 5, 6, 22, 23]:
            z[index_i][index_j] = np.random.randint(0, 50)



mardi 21 décembre 2021

Why am I getting this syntax error? (Python)

Python noob here. Took a swing at the 'guess the number game' this afternoon. It all looks fine to me but i keep getting a syntax error on line 26:

else player_number >= secret_number:

I've tried everything but I can't figure it out at all. Thanks for your help.

import random, sys
secret_number = random.randint(1, 99)
countdown_timer = 7

print("This is a number guessing game.")
print("You have to guess a number between 1 and 99!")
print("You have 7 attempts to guess the correct number")
print("Good luck!")
print("\n")
print("Your first guess is: ")

while countdown_timer != 0:
    player_number = int(input())
    countdown_timer = (countdown_timer - 1)
    if player_number == secret_number:
        print("\n")
        print("That's it!! The number was: " + secret_number)
        print("\n")
        print("Congratulations!")
        print("Please try again.")
        quit()
    elif player_number <= secret_number:
        print("Higher!")
        print("You have " + int(countdown_timer) + "guesses left.")
        print("Please enter your next guess: ")
    else player_number >= secret_number:
        print("Lower!")
        print("You have " + int(countdown_timer) + "guesses left.")
        print("Please enter your next guess: ")
        
print("You are out of guesses, sorry.")
print("The correct number was: " + secret_number)
print("Please try again.")



Notion API Pagination Random Database Entry

I'm trying to retrieve a random entry from a database using the Notion API. There is a page limit on how many entries you can retrieve at once, so pagination is utilized to sift through the pages 100 entries at a time. Since there is no database attribute telling you how long the database is, you have to go through the pages in order until reaching the end in order to choose a random entry. This is fine for small databases, but I have a cron job going that regularly chooses a random entry from a notion database with thousands of entries. Additionally, if I make too many calls simultaneously I risk being rate limited pretty often. Is there a better way to go about choosing a random value from a database that uses pagination? Thanks!




Random changing weight

I need to implement a class where I am able generate random element based on their weight. The tricky part is that I also need to be able to change the weight.

Here is an example output

set_weight("A", 4.0)
set_weight("B", 6.0)
get_random() # return "A" 40% probability, "B" 60%
set_weight("A", 3.0)
get_random() # return "A" 33% probability, "B" 66%

My approach to solving is to find the prefix sum every time a weight is added and append the (element, current_sum_weight) tuple into the list. For set_weight("A", 4.0) and set_weight("B", 6.0), the array would be [("A", 4.0), ("B", 10.0)] Then I generate a random number between 0 and the current sum then iterate through the array to find the first sum weight that is less than the random number and return that element.

However, I don't know how to update the sum weight, because then I would have to iterate through the array and then find the element and update all the weight of elements after. What is a way that I can implement an update for the weight?

I don't know if using dictionary is better, or maybe I should use an ordered dictionary.




Random number function python that include 1 but not include 0

I need to generate a number from 0 to 1 that include 1 but not include 0

The random.uniform(0,1) function include 0 but not include 1

How is it possible to do that?




dimanche 19 décembre 2021

how would I go about getting rid of the square brackets and quote marks when printing a shuffled list [duplicate]

import random

alphabet = ["R","G","B","Y"]
random.shuffle(alphabet)

code = alphabet[0:3]

this is my code and when I print "code" It returns something like this ['B','G','R']. I want to make it so that it only displays BGR for example.




Choose three emails at random from an indefinite group of emails

it's the first time I'm writing here, sorry for any mistakes. I'm not a programmer, I usually try to study the advice you give on this site and find a way to apply it to my needs but this time I just can't find a solution. I use an email plugin for wordpress that allows me to put a tag like this [emails-group] in the "Bcc" field, this tag can contain one or more email addresses separated by commas. with the code I wrote below (I don't know if it's written in the best way) I can send an email to two random email addresses when the email addresses are three. (this code works in my tests)

add_filter( 'wpcf7_mail_tag_replaced',
  function( $replaced, $submitted, $html, $mail_tag ) {
    if ( 'emails-group' == $mail_tag->field_name() ) {
    foreach($submitted as $value){
        $expl = explode(",", $value);
        $list = array("$expl[0]","$expl[1]","$expl[2]");
        $rand_keys = array_rand($list, 2);
        $first = $list[$rand_keys[0]];
        $second = $list[$rand_keys[1]];
         $result = array("$first","$second");
    $replaced = implode(",",$result);
    }
    }
    return $replaced;
  },
   10, 4
);

what I would need is a new code for:

if the email addresses are one or two or three then send everyone the email, but if the email addresses are more than three choose only three email addresses at random and send them the email.

I thank anyone who can put me on the right way to find the solution. Greetings, Raffaele.




vendredi 17 décembre 2021

How to generate random number and print shiny if equals

I am learning to code and I am currently stuck on JavaScript object methods. I am trying to write a code to print 'shiny' if the random number generates = 5. How can I achieve that? Also, is it printing undefined which I do not know where it is coming from. Thank you for reading.

const pokemonGoCommunityDay = {

  wildEncounters: ['machop','roselia','swablu','gible','snivy','fletchling'],

  currentEncounter() {

    while (this.currentEncounter) {
      this.currentEncounter = this.wildEncounters[Math.floor(Math.random() * 6)];
      console.log(this.currentEncounter);

      if (/* How to make it generate a certain number and if =5 log shiny*/ === 5){
        console.log('Shiny!');
      }break;
    }
  }
}  
console.log(pokemonGoCommunityDay.currentEncounter());



What is the PRNG algorithm used in Rust's `rand` crate?

I'm writing a web app that will do some financial model simulations. Just for fun and an opportunity to learn new things, I have decided to offload all the math and simulations to a WebAssembly and implement that wasm in Rust.

I am therefore looking at PRNGs for Rust. I found a Mersenne Twister crate and MT is obviously a well-established algorithm (even used by default in several languages), but this particular crate does not seem to be very popular. I also understand that Rust has a rand crate "built-in" (if that's even a thing) but I haven't found any info as to:

  • What is the algorithm used in rand?
  • How does that algorithm stack up to others (e.g. MT) in terms of randomness quality?

To be clear: I'm evaluating algorithms for statistical randomness (simulating stochastic processes), not cryptographic security.




jeudi 16 décembre 2021

Finding the optimal combination from a list of lists that maximally disperses repeating elements

I have a list of lists, where each individual list represents which people are available to take a work schedule shift. My actual data is for a list of 50 shifts:

[['P3', 'P2', 'P4', 'P5'], ['P1', 'P3', 'P2', 'P4'], ['P1', 'P3', 'P2', 'P4'], ['P1'], ['P5'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P3', 'P2', 'P4', 'P5'], ['P3', 'P2', 'P4', 'P5'], ['P2', 'P5'], ['P1', 'P2', 'P5'], ['P1', 'P2', 'P5'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P5'], ['P2'], ['P1', 'P3', 'P4', 'P5'], ['P1', 'P3', 'P4', 'P5'], ['P1', 'P3', 'P4', 'P5'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P2', 'P4'], ['P1', 'P3', 'P2', 'P4'], ['P1', 'P3', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P4'], ['P1', 'P3', 'P2', 'P4'], ['P1', 'P2', 'P4'], ['P1', 'P2', 'P4', 'P5'], ['P1', 'P2', 'P5'], ['P1', 'P3', 'P2', 'P5'], ['P1', 'P3', 'P2', 'P5'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P2'], ['P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P5', 'P2', 'P4'], ['P1', 'P3', 'P2', 'P4'], ['P1', 'P3', 'P2', 'P4']]

I am trying to end in a final list of 50 (i.e., ['P3', 'P2', 'P4', 'P1', 'P5', 'P2', ...] with either one of two criteria:

Option A: Repeating elements are maximally dispersed

Option B: Each repeating element is at a minimum spaced apart by 2 index spaces, i.e. that ['P1', 'P1'] or ['P1', 'P2', 'P1] are not acceptable, but ['P1, 'P2', 'P3', 'P1'] is ok.

I don't know how to approach Option A tbh. For Option B, here is what I have so far:

AssignList = []
for ix, x in enumerate(AvailableList):
    randx = random.choice(x)
    if len(AssignList)==1:
        while randx==AssignList[0]:
            randx=random.choice(x)
    if len(AssignList)>1:
        while (randx==AssignList[-1]) | (randx==AssignList[-2]):
            randx=random.choice(x)
    AssignList.append(randx)
print(AssignList)

But the problem with my approach is I think it reaches some lists where there is one choice that causes an infinite loop. Any tips for either approach much appreciated!




How to generate random pattern of data with specific probability?

I don't know how to change my code to generate a random pattern of alive cells. numpy is not allowed. (CellType(True) = "O"

def seed_random(self, confluency, CellType=Cell):
    self.confluency = float(confluency)
    
    x = random.uniform(0,1)
    print(x)
    cu_prob = 0.0
    test_matrix = list()
    for i in range(self.rows):
        test_matrix.append([])
        for j in range(self.cols):
            test_matrix[i].append(CellType(False))
            cu_prob += confluency
            if x < confluency:
        
                test_matrix[i][j]=CellType(True)
            else:
                test_matrix[i][j]=CellType(False)

    self.matrix = test_matrix

I want my output look like this when confluency is 0.5.

O..OOO..OO.O.OO.O..OO..OOOOOOOOOOOOO...O

..OO...O..O.....OO.OO...OO...OOOO...OO..

...O...OO..O.......OO..O.OOO...OOOO.....

O..OOO.OO.OOO.OO.OOOOOOOO..O..OOO.O...O.

..O.O.O.OO..O.O..OOO.O...O....OOO.OOO.OO

O..OOO..OO...O..O.O.OO.O...OOO....O.OOO.

..O..O.OOO...OO..O.OO.OO.OOOO.O.O..OOOO.

OO.O.OOO...OO.....O.OOOO.O...OOOO..OO...

OOOO.OO.O.O.O..O.O...OO..O.O.OO......OOO

..OO.....OOOOO.O.OOOOO.OO.OO...O..OOOOO.

but my output is either this or circles

........................................

........................................

........................................

........................................

........................................

........................................

........................................

........................................

........................................

........................................




Inizialize random array in C with MPI

I'm new to MPI and wanted to ask if it was possible to initialize an array randomly with MPI without having to go and re-copy the various elements following a Send and Recive, what I was thinking of doing was via a Gather and Scatter process, but I don't know if that's feasible. This is the test with Send and Recive, unfortunately, the rank 0 has to re-copy all the elements.

Can this copy be avoided?

void generateArrayParallel(int arr[], int n, int rank, int nprocs)
{
    int size;
    if (nprocs == 1)
        size = 0;
    else
        size = n / (nprocs - 1);                 
    int leftElements = n - (size * (nprocs - 1)); 

    MPI_Bcast(&size, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Status status;

    if (rank == 0)
    {
        int *arrRicv = (int *)calloc(size, sizeof(int *));
        srand(rank);

        for (int i = 1; i < nprocs; i++)
            MPI_Send(&arr[(i - 1) * size], size, MPI_INT, i, 1, MPI_COMM_WORLD);

        for (int i = n - leftElements; i < n; i++)
            arr[i] = (int)rand() % 100000;

        for (int i = 1; i < nprocs; i++)
        {
            MPI_Recv(arrRicv, size, MPI_INT, i, 2, MPI_COMM_WORLD, &status);
            for (int j = 0; j < size; j++)
            {
                arr[((i - 1) * size) + j] = arrRicv[j];
            }
        }
        free(arrRicv);
    }
    else
    {
        int *arrRicv = (int *)calloc(size, sizeof(int *));
        MPI_Recv(arrRicv, size, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
        srand(rank);
        for (int i = 0; i < size; i++)
            arrRicv[i] = (int)rand() % 100000;

        MPI_Send(arrRicv, size, MPI_INT, 0, 2, MPI_COMM_WORLD);
        free(arrRicv);
    }

    }
}





mercredi 15 décembre 2021

My probability program is returning different results when I run the code on different IDES

I have a program that takes a number of colored balls and puts them into a hat.

I then pick N amounts of balls to be drawn out of the hat X amounts of times.

I have a specific combination of colored balls that I am testing for(expected_balls). for example: {'blue': 2, 'green': 3}

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    matches = 0

    for experiment in range(num_experiments):
        result = hat.draw(num_balls_drawn)
        result = Counter(result)
        chk = True

        for k, v in expected_balls.items():
            if result[k] < v:
                chk = False
                break

        if chk:
            matches += 1

return (matches/num_experiments)

This code is for a project for class. I wrote the code on Atom and the answer probability matches what the project is looking for. However when I run it on replit, where I submit the project the answer comes out totally different.

Why is the answer different when I run it on two different programs.




Js Math.random not random [duplicate]

I can't generate a multidimensional array and fill it with random values, I tried to use for loops, forEach, and map with Math.random, but all arrays are identical.

function mat(a=5,b=5,max=2){
  
  let mt = new Array(a).fill(
    new Array(b).fill(0)
  )
  
  mt.map( (x,xk)=>{ 
    x.map( (y,yk)=>{ 
      mt[xk][yk] = Math.round(
        Math.random()*max
      )
    })
  })
  
  return mt
}
console.log(JSON.stringify(mat()))

output example

[[0,0,2,2,0],
 [0,0,2,2,0],
 [0,0,2,2,0],
 [0,0,2,2,0],
 [0,0,2,2,0]]

why?? does not make sense!




How to build unique random couple from a single list

I want to find random couples on a single list with different members.

Here is my code:

import random

def alea_couple(members):
    couples = []
    for p in members:
        possibles = [r for r in members if r!=p and r not in [elem[1] for elem in couples]] 
        couples.append((p, random.choice(possibles)))
    return couples

my_members = ["member1", "member2", "member3", "member4"]
random.shuffle(my_members)
alea_couple(my_members)

[('member2', 'member1'),
 ('member3', 'member4'),
 ('member1', 'member3'),
 ('member4', 'member2')]

I am sure there is a better way and more elegant way to do this with itertools.combinations

do you have a piece of advice ?




Cloudsim with random users

I want to simulate a datacenter with 10 hosts, and a random number of users between 5 to 10, each user has tasks between 30 to 50 which needs 3-5 Virtual machines for them.




Generate random coordinates in different polygons

I'm new into Python. I want to generate random coordinates inside a set of polygons.

To generate random coordinates inside one Polygon I found this code on Stackoverflor, which works:

def polygon_random_points (poly, num_points):
    minx, miny, maxx, maxy = poly.bounds 
    while len(points) < num_points:
        random_point = Point([random.uniform(minx, maxx), random.uniform(miny, maxy)])
        if (random_point.within(poly)):
            points.append(random_point)
    return points

But now I struggle to achieve a for loop for all of my polygons. They have this data type: geopandas.geoseries.GeoSeries.

Maybe someone can help me.




lundi 13 décembre 2021

Random Array Sort Method Javascript

Currently I'm building a quiz app, which displays a verb with a right and 3 wrong answers in a random order. The class is:

class IrregularVerb {
    constructor(verb, right, wrongFirst, wrongSecond, wrongThird) {
        this._verb = verb;
        this._right = right;
        this._wrong = [wrongFirst, wrongSecond, wrongThird];
    }

    randomOrder() {
        return this._wrong.sort(0.5 - Math.random());
    }
}

const irregularVerbList = [
    new IrregularVerb("read", "read", "rode", "ride", "ridden"),
    new IrregularVerb("go", "went", "gone", "got", "god")
]


const randomWrongAnswer = irregularVerbList[randomNumber].randomOrder;

randomWrongAnswer should return an Array with the last 3 object parameters in a random order, but it displays "function randomOrder()". Is the method declaration or its call wrong?




How would I stop an random colour randomise from picking the same colour twice

<script>
      function randomColour(){
        var colour=[];
        colour[0]= '#edf2fb';
        colour[1]= '#d7e3fc';
        colour[3]= '#c1d3fe';
        colour[4]= '#d1d1d1';
        colour[5]= '#e1dbd6';
        colour[6]= '#e2e2e2';
        colour[7]= '#f9f6f2';
        colour[8]='#ffc09f';
        colour[9]='#ffee93';
        colour[10]='#fcf5c7';
        colour[11]='#a0ced9';
        colour[12]='#adf7b6';
        colour[13]='#809bce';
        colour[14]='#95b8d1';
        colour[15]='#b8e0d2';
        colour[16]='#d6eadf';
        colour[17]='#eac4d5';
        colour[18]='#e8d1c5';
        colour[19]='#eddcd2';
        colour[20]='#fff1e6';
        colour[21]='#f0efeb';
        colour[22]='#eeddd3';
        colour[23]='#e8dff5';
        colour[24]='#fce1e4';
        colour[25]='#fcf4dd';
        colour[26]='#ddedea';
        colour[27]='#daeaf6';
        colour[28]='#d3ab9e';
        colour[29]='#eac9c1';
        colour[30]='#ebd8d0';
        colour[31]='#ffe5ec';
        colour[32]='#ffc2d1';
        colour[33]='#ceb5b7';
        colour[35]='#b5d6d6';
        colour[36]='#f2f5ff';
        colour[37]='#efcfe3';
        colour[38]='#eaf2d7';
        colour[39]='#b3dee2';
        colour[40]='#f8ad9d';
        colour[41]='#fbc4ab';
        colour[42]='#ffdab9';
        colour[43]='#cdb4db';
        colour[44]='#ffc8dd';
        colour[45]='#ffafcc';
        colour[46]='#bde0fe';
        colour[47]='#a2d2ff';
        colour[48]='#fdffb6';
        colour[49]='#caffbf';
        colour[50]='#9bf6ff';
        colour[51]='#a0c4ff';
        colour[52]='#ffc6ff';
        colour[53]='#a7bed3';
        colour[54]='#c6e2e9';
        colour[55]='#f1ffc4';
        colour[56]='#ffcaaf';
        colour[57]='#dab894';
        colour[58]='#fec7bc';
        colour[59]='#fcf5ee';
        var pick= Math.floor(Math.random()*60);
        var test = document.getElementById("colorpad");
        test.style.backgroundColor = colour[pick];
        return colour[pick];


      }
    </script>

I would like to know on how I would be able to stop this random colour picker from choosing the same colour twice because it is currently doing this when I want it to pick another random colour. I do not know why this is occurring, what should I implement into my code to stop this from occurring.




samedi 11 décembre 2021

Julia cannot reproduce the rand

I am just reading and practicing the "3.5.2.1 rand" section of https://juliadatascience.io/standardlibrary and found the code below cannot reproduce same random numbers:

$ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.7.0 (2021-11-30)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> using Random: rand, randn, seed!

julia> my_seed = seed!(123)
Random.TaskLocalRNG()

julia> rand(my_seed, 3)

3-element Vector{Float64}:
 0.521213795535383
 0.5868067574533484
 0.8908786980927811

julia> rand(my_seed, 3)
3-element Vector{Float64}:
 0.19090669902576285
 0.5256623915420473
 0.3905882754313441

The snapshot of the book:

enter image description here




Weird stratified random sampling in R at low pool to required sample ratio [duplicate]

I tried to do stratified random sampling from a list with pre-defined elements of roughly the same size by taking 1 sample from each stratum. It seems to be working fine if the sampling pool is at least twice as big as the number of selected samples but something weird happens if this is not the case. Code (small pool):

    library(dplyr)
    a <- 1:10
    n <- 10
    div=length(a)/n
    strata <- split(a, ceiling(seq_along(a)/div))
    set.seed(52)
    set <- sapply(strata, sample, 1)
    set

Outcome:

1  2  3  4  5  6  7  8  9 10 
 1  2  3  3  5  5  6  7  3  1 

The outcome should be 1,2,3,4,5,6,7,8,9,10. But instead 3 and 5 have been selected twice which should not happen. Also 3 and 1 are not in the strata of group '9' and '10' and so on.

If I change

a <- 1:100

Then the outcome:

1  2  3  4  5  6  7  8  9 10 
 2 13 23 38 45 57 63 71 85 99 

And this is what I expect to get. One randomly selected sample from each stratum.

What is going on if the pool is too small compared to the number of desired samples? Why does it not take the remaining one number from each stratum?




How do I resolve swing GUI error due to compile error? [duplicate]

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error on token "void", record expected void is an invalid type for the variable actionPerformed

at GuessingGame.<init>(GuessingGame.java:66)
at GuessingGame.main(GuessingGame.java:78)

This is the error I am getting and I have not had any luck fixing it.

Some context for what I am doing with this project. Full transparency I am using a window builder in the IDE. Though I have gone back into the source and manipulated a lot of the prebuilt code that gets dropped in from the builder. I am trying to learn how to build GUI in Java, and was hoping this builder would allow me to deconstruct the prebuilt code, however, I feel like I may have entered potential bad implimentation and I have not been able to identify. There are only 2 lines in this code throwing this error and I am unsure what the solution is.

```
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GuessingGame extends JFrame {
    private JTextField txtGuess;
    private JLabel lblOutput;
    private int theNumber;
    public void checkGuess() {
        String guessText = txtGuess.getText();
        String message = "";
        int guess = Integer.parseInt(guessText);
        if (guess < theNumber)
            message = guess + " is too low. Try again.";
        else if (guess > theNumber)
            message = guess + " is too high. Try again.";
        else
            message = guess + " is correct. You win!";
        lblOutput.setText(message);;
    }
    public void newGame() {
        theNumber = (int)(Math.random() * 100 + 1);
    }
    public GuessingGame() {
        setBackground(new Color(240, 240, 240));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Arthor's Hi Lo Guessing Game");
        getContentPane().setLayout(null);
        
        JLabel lblNewLabel = new JLabel("Arthor's Hi Lo Guessing Game");
        lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setBounds(10, 43, 414, 37);
        getContentPane().add(lblNewLabel);
        
        JLabel lblNewLabel_1 = new JLabel("Guess a number between 1 and 100:");
        lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
        lblNewLabel_1.setBounds(32, 106, 204, 37);
        getContentPane().add(lblNewLabel_1);
        
        txtGuess = new JTextField();
        txtGuess.setBounds(279, 114, 107, 20);
        getContentPane().add(txtGuess);
        txtGuess.setColumns(10);
        
        JButton btnNewButton = new JButton("Guess!");
        btnGuess.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                checkGuess();
            }
        });

        //btnNewButton.addActionListener(new ActionListener() {
            //public void actionPerformed(ActionEvent e) {
            //}
        btnNewButton.setBounds(172, 169, 101, 39);
        getContentPane().add(btnNewButton);
        
        lblOutput = new JLabel("Enter a number above and click Guess!");
        lblOutput.setHorizontalAlignment(SwingConstants.CENTER);
        lblOutput.setFont(new Font("Tahoma", Font.PLAIN, 8));
        lblOutput.setBounds(133, 219, 192, 14);
        getContentPane().add(lblOutput);
    }
    public static void main(String[] args) {
        GuessingGame theGame = new GuessingGame();
        theGame.newGame();
        theGame.setSize(new Dimension(450,300));
        theGame.setVisible(true);
        // TODO Auto-generated method stub

    }
}
```



How do I generate multiple random lists for a portion of a larger list in Python? I keep getting duplicate lists

Started working with Python today and decided to test my learnings on a small project.

I want to have a "roster" of, lets say 12 people. From this roster, I want there to be "x" number of teams of "y", depending on how many people want to play. I know how to write this, if we assume all names in the roster are going to be used, but where I'm lost is how to generate unique teams for a composition of something like 3 teams of 2. Whenever I try to solve this, I will get 3 of the same teams of 2.

Here is an example of the code I'm attempting

import random

names = ["Tom", "Sam", "Jake", "McKenzie", "Sarah", "Devon", "Brice", "Caleb", "Mitchell", "Scott", "Nick", "Liz"]

teams = int(input("How many teams will there be? "))
players = int(input("How many players will each team have? "))

remaining_teams = teams
item = random.sample(names, k=players)


while remaining_teams > 0:
    print(item)
    remaining_teams = remaining_teams - 1
    if remaining_teams < 1:
        break

Right now, if my input variables were 4 and 2, I would get something returning like:

["Sam", "Tom"]
["Sam", "Tom"] 
["Sam", "Tom"] 
["Sam", "Tom"] 

How can I change this to get random results closer to this?:

["Sam", "Tom"]
["Nick", "Sarah"]
["Devon", "Jake"]
["Mitchell, "Liz"]



vendredi 10 décembre 2021

I'm trying to 'draw' curve of random distribution(Galton board) but it 'avoids' certain positions

I want to simulate behavior of the Galton board getting a dictionary with position in key and frequency in value.

import random

board = {-5:0, -4:0, -3:0, -2:0, -1:0, 0:0, 1:0, 2:0, 3:0, 4:0, 5:0}

for i in range(200):
  num = 0
  for x in range(5):
    num+= random.choice([-1,1])
  d[num]+=1

And then I get something like this: {-5:7, -4:0, -3:35, -2:0, -1:60, 0:0, 1:58, 2:0, 3:29, 4:0, 5:11}

Also when number of positions from 0 to an end is even, the script gives more positions filled but the second and penult ones always remain epmty. Why is it so and how can I get proper realization of the idea?




How to generate a random number from 2 numbers [duplicate]

I've searched a lot for generating a random number but all I got is generating for a range between a or b.

I'm trying to get a number from a or b, i.e. either a or b, none from in between.

This returns the first value only var number = 1 || 9; \\9




jeudi 9 décembre 2021

Laravel : Generate a random url, recover the new url after processing

With laravel I created a function to have an image + a random id from 0 to 30. Unfortunately the image stored in my database is not processed and is listed in my database like this: https://source.unsplash.com/800x800/?portrait=28 How can I solve this I have not found anything yet.

my Factory :

'profile_photo_path' => $this->loadImage(),

my function :

public function loadImage()
    {
        return "https://source.unsplash.com/800x800/?portrait=" . mt_rand(1, 30);
    }

When you click you get a different url.

example : https://images.unsplash.com/photo-1552699611-e2c208d5d9cf?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=800&ixid=MnwxfDB8MXxyYW5kb218MHx8cG9ydHJhaXR8fHx8fHwxNjM5MDU5Njkw&ixlib=rb-1.2.1&q=80&utm_campaign=api-credit&utm_medium=referral&utm_source=unsplash_source&w=800

this is what I want to enter in the database




mercredi 8 décembre 2021

Can anybody help in this poweshell script exercises?

I have two scripting tasks, but I got stuck in them. The first task does not work properly because it prints 1 more number and the consecutive numbers are not correct either. Does anyone have any idea what the mistake might be?

Create a script called a.ps1. The script has one parameter: pieces (pieces are positive integers). Prints a number of random numbers when the script is called. The first random number has a minimum of 0 and a maximum of 9. Subsequent random numbers are a minimum of the previous random number and a maximum of 9.

Param (
 [Parameter (Position = 0, mandatory = $ true)]
 
    [int]$pieces
)
 
$first = Get-Random -Minimum 0 -Maximum 9
 
1..$pieces | % {
 
    Write-output $first
   $random = Get-Random -Minimum 0 -Maximum 9
   $first = $first + $random
 
}

In the second task, the first result should be called using a pipeline, but I don't really understand how it works. Can anyone help me?

Create a Powershell script called b.ps1 that can process the results of the script created in the first task through a pipeline and print as many “#” characters as the number contains.

$input | % {
 
 Write-Output "#"*$_
 
 }



Create Unique random_bytes() for Each Element in an Array

There is a goal to add a unique ID to each of json responses. I'm intended to use random_bytes() PHP function. In my code I set up a variable:

$bytes = random_bytes(20);

Later I tried to add an unique identifier to each element in an array:

$bytes = random_bytes(20);
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
foreach($result['surveys'] as $survey) {
    echo 'ssi=',bin2hex($bytes),' ',$survey['project_id'],'<br>';
}

I got a response with identical IDs instead:

ssi=d409af794aeebabb761dc0ede721a588104718fb 29711156
ssi=d409af794aeebabb761dc0ede721a588104718fb 29600921

Will you please make changes in my code so that it will show different "ssi" for each element in a massive instead of replicating $bytes into every line?




random numbers of a uniform distribution in R

I want to create random numbers of a uniform distribution, but I want to implement them with this function:

funcion.distribucion = function(x)
{
  L = length(x)
  F = vector("numeric",L)
  for (i in 1:L)
  {
    if (x[i]<0) { F[i] = 0}
    else if (x[i] <= 2) {F[i] = (x[i]^3)/8}
    else {F[i] = 1}
  }
  return(F)
}

runif(funcion.distribucion(200),0,1)

How I do it?




Declaring a value to int in arrays

I'm trying to make a deck of cards with only using array and no classes.

How do I declare a value to each and every card? It seems very inefficient trying to write it like this, and then trying to give a value to each index position:

int deckOfcards[52]{ 1,2,3,4,5,6,7,8,9,10.......... };

Also I will then draw 2 random cards and declare a winner. Is it possible to use rand() function in arrays?




Random function not giving an intended output

Random r = new Random();
int n = r.nextInt(101);

The output sometimes give an integer value greater than 100

    System.out.print("Value of n: " + n);
    int status = 1;
    int num=3;
    for(int i=2; i<=n; ){
        for(int j=2; j<=Math.sqrt(num); j++){
            if(num%j==0){
                status = 0;
                break;
            }
        }
        if(status!=0){
            System.out.println(num);
            i++;
        }
        status = 1;
        num++;
    }

can somebody explain the problem mentioned above?




mardi 7 décembre 2021

How to store values to a file in shell script when executing the shell script from python file?

I need to trigger a shell script from a python file. That shell script needs to execute a few commands and store the data in another file.

Problem: I'm able to trigger the shell script from python but the commands getting executed inside the shell script is giving empty response and storing "Cg==" in respective file.

Shell script: randscript.sh

Generating random value and storing it to newfile.

echo Pass = $(echo $RANDOM | base64 | head -c 20)>>newfile

Python: randfile.py

Executing python file to trigger the shell script.

import os
import subprocess
def rand_func():
  try:
    path = '/home/ubuntu/execution'
    os.chdir(path)
    script_exec = subprocess.call(['sh','./randscript.sh'])
    print(script_exec)
    return True
  except Exception as err:
    print("Exception")
    return False
func_exec = rand_func()

Note: When the command was executed manually, it is returning the expected value (giving random value). But via python script, it is returning "Cg=="(which is a newline character). Could anyone please help me to understand this?




C SRAND - First random value not random [duplicate]

I'm working on a group project where I need to generate a set of random numbers, however, the values are staying the same. The values should be between 0 and 1 in a float value.

The code is as follows:

srand((unsigned int) time(0));

float randNumber = (float) rand() / (float) (RAND_MAX) * (float) 1;
if (randNumber < 0.05) {
    state = STATE_HEALTHY;
} else if (randNumber > 0.05 && randNumber < 0.15) {
    state = STATE_INFECTED;
} else {
    state = STATE_HEALTHY;
}
printf("[%i][%i] Generated Number: %.2f  |  State: %i\n", X_INDEX, Y_INDEX, randNumber, state);

If I put the rand() in a printf at the end underneath the last printf the number returned is always random.

The end goal for this is the output below should have a randomly generated number for each index (of x and y)

[0][0] Generated Number: 0.20  |  State: 0
[0][1] Generated Number: 0.20  |  State: 0
[1][0] Generated Number: 0.20  |  State: 0
[1][1] Generated Number: 0.20  |  State: 0

How would it be possible to generate a random number for cell?

Edit: After using the suggestion by @drescherjm I am faced with the issue of the first value not being random but instead being incremented very slowly by one, see below for two outputs after the suggestion.

[0][0] Generated Number: 0.25  |  State: 0
[0][1] Generated Number: 0.79  |  State: 0
[1][0] Generated Number: 0.37  |  State: 0
[1][1] Generated Number: 0.97  |  State: 0

[0][0] Generated Number: 0.25  |  State: 0
[0][1] Generated Number: 0.38  |  State: 0
[1][0] Generated Number: 0.00  |  State: 0
[1][1] Generated Number: 0.25  |  State: 0

EDIT: This is my attempt for the minimal reproducible example. Below is the code I made to reproduce this:

Main.c

    #include "header.h"

int main() {
    srand((unsigned int) time(NULL));
    test();
    return 0;
}

Test.c

#include "header.h"

void test() {
    for (int i = 0; i < grid_w; ++i) {
        for (int j = 0; j < grid_h; ++j) {
            grid[i][j] = randomNumTest(i, j);
        }
    }
}

randomNumTest.c

#include "header.h"
    
    int randomNumTest(int x, int y) {
        float randNumber = (float) rand() / (float) (RAND_MAX) * (float) 1;
    
        printf("[%i][%i] Generated Number: %.2f\n", x, y, randNumber);
    
    }

Header.h

#include "stdio.h"
#include "stdlib.h"
#include "time.h"

#define grid_h 2
#define grid_w 2

void test();

int randomNumTest(int x, int y);

int grid[grid_h][grid_w];



What range of values does python's random seed take?

Python's int type allows for very large values, but surely if I pass, for instance, 10**100000 into random.seed, it won't actually store that - does it just use a 32-bit integer internally?




How to generate random convex polygon?

How can I generate a random convex polygon in x86 assembly?

I'm working on a project where I would like to generate random polygons. Does anyone have a clue?




lundi 6 décembre 2021

Type random letter in VBS?

I'm making script with VBS that should do something like this:
Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.SendKeys "something"But it should type random letters. Is there way to do so, or would it be possible to make it run random script in folder and each one types letter?




Generating random sequences that are harder to crack

I am building a simple mobile game where players play rock paper scissors agains a computer. I am using Unity, and am looking to use the Random.Range function to determine which hand the computer plays against the player.

I see in Unity's documentation that they use an Xorshift 128 algorithm for the Random.Range function, which, according to this blog post and several other sources, can be easily cracked.

I'm wondering if there are ways to make it more "random" - I understand that true randomness cannot be achieved, but am wanting to learn ways to make harder to crack the pattern.

Any ideas will be appreciated! Thanks.




Javascript method to generate

Let's say there are 100 people, and $120, is what kind of formula, could divide it into random amounts to where each person gets something?

In this scenario, one person could get an arbitrary amount like $0.25, someone can get $10, someone can get $1, but everyone gets something. Any tips?

So in javascript, an array of 100 could be generated, and these random numbers would be in them, but they would add up to 100




Why I am getting values that are outside of my rand function parameters c++

I am trying to output 25 random values between 3 and 7 using a function. Every time I run my program I receive two values that are within those parameters but the rest are out of the range.

#include <iostream>
#include <iomanip>
using namespace std;


void showArray(int a[], int size);


void showArray(int a[], const int size)
{ 
    
   int i;
    
    for (i = 0; i < size; i++)
    {
        cout << a[i] << ", ";
    }
}
 

int main()
{
    //int iseed = time(NULL);
    //srand(iseed);

    srand(time(NULL));
    int randomNumb = rand() % 3 + 4;
    int array[]  = {randomNumb};

   
  
    
    
    showArray(array, 25);

this is my Output : 4, 4, -300313232, 32766, 540229437, 32767, 0, 0, 1, 0, -300312808, 32766, 0, 0, -300312761, 32766, -300312743, 32766, -300312701, 32766, -300312679, 32766, -300312658, 32766, -300312287,




Replacing elements in a list randomly in Python

I have a list of words

words=['hello', 'test', 'whatever' , 'hello' , 'apple' , 'test','hello',......]

and I want to randomly replace half (can be rounded down/up by one) of the instances of some elements in the list (that are stored in another list) like 'test' and 'hello' with the the words reversed i.e I'd want my new list to look something like:

['olleh', 'test', 'whatever' , 'hello' , 'apple' , 'tset','olleh',......] (here I am working with the words test and hello)

How would I do this?

I know to reverse the words I can simply do reversed_words = [i[::-1] for i in words] but I'm more unsure about the randomly selecting half the occurances part.




How to count repeating functions in a for loop, Discord.py

I am trying to create a Discord slot bot where if 2 of the emojis match the bot rewards the user a prize and if all 3 then multiply the prize by 3x. However in order to do this I need to check and see if my function is repeating any values, ive looked online for an answer and the closed thing I found to what I think I needed was .count if description_text.count(i): and then if two or more matched payout x2 etc. but since my function is a int and not a string it does not work. I also tried counting the list but at last that only returned false since the list is unique.

I was wondering if you anyone had any insight on how I might be able to see if the emojis are repeating and then if they are payout the prizes accordingly. Thanks!

final = [
    "||:watermelon:||", #0
    "||:lemon:||", #1
    "||:tangerine:||", #2
    "||:apple:||", #3
    "||:pineapple:||", #4
]

description_text = ""

for i in range(3):
    description_text = f"{description_text} {random.choices(final, cum_weights=(0.4, 0.4, 0.2, 0.2, 0.2), k=1)[0]}"
    
embed = discord.Embed(title="Slot Machine", description= description_text, color=0x00d9ff)
embed.set_footer(text="Use !lottery to see how Prizes work!")
await ctx.send(embed=embed)

if description_text.count(i):
    await update_bank(ctx.author,2*amount)
    await ctx.send(f'You won :slight_smile: {ctx.author.mention}')
else:
    await update_bank(ctx.author,-1*amount)
    await ctx.send(f'You lose :slight_frown: {ctx.author.mention}')

Error Message: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: must be str, not int




Please help me with my random error when generating cards for my deck in javascript

My goal is to make a simple card game. I have this bug where sometimes it doesnt push one of the objects into the array. First I thought that the picked number wouldn't fit between the if statements to declare the values of the objects. I have tried to redefining the pickedNumber manually right after it got the random value. Then it worked. The numbers that I have problems with are: 36, 38, 24, 25, 37 when it was random, but when i defined the var pickedNumber manually it worked as it should. Any hints on how to fix this? Thanks a lot in advance.

picture of when the code fails

picture of when it works

function log(txt) {
  console.log(txt);
}
let cards = [];
let hand = [];

// fill card deck
for (let i = 1; i < 53; i++) {
  cards.push(i);
}

// index for to make the random math not to choose a number over the highest index of cards[]

// loop for picking some random card with a value
for (let i = 0; i < 3; i++) {
  // random index to choose
  let randomNumber = Math.floor(Math.random() * cards.length);
  log(randomNumber);
  // random number
  let pickedNumber = cards[randomNumber];
  log(pickedNumber);
  // remove the picked card
  const index = cards.indexOf(pickedNumber);
  if (index > -1) {
    cards.splice(index, 1);
  }
  let finalValue;
  let card = {
    value: finalValue,
    suit: "",
  };

  // these if statements are for deviding the cards from 52 to 4x13
  if (pickedNumber < 14) {
    card.value = pickedNumber;
    card.suit = "♥";
    hand.push(card);
  } else if (pickedNumber > 13 && pickedNumber < 26) {
    card.value = pickedNumber -= 13;
    card.suit = "♣";
    hand.push(card);
  } else if (pickedNumber > 26 && pickedNumber < 39) {
    card.value = pickedNumber -= 26;
    card.suit = "♦";
    hand.push(card);
  } else if (pickedNumber > 39 && pickedNumber < 53) {
    card.value = pickedNumber -= 39;
    card.suit = "♠";
    hand.push(card);
  }

  // reduce maxIndex to dont overpick index
}
log(hand);




How can I generate a random number sequence of a specific length? c#

I am trying to implement the Digit Span task, where the participant has to reproduce sequences of numbers. It starts with three numbers and if the participant is answering correctly one number is added. If the participant is wrong he will hear another sequence with the same length again and if he is then again wrong the sequence is reduced by one number.

So far I am solving this with Lists (threeDigits, FourDigits, FiveDigits,..) that are filled at the beginning with some Audio Files of that certain length. But this is quite complicated because I need to add so many Audio Files.

Instead of filling the lists with specific Audio Files I want to solve this now by randomly generating a sequence depending on the List that was chosen. So for example if the List "four Digits" was chosen a random sequence of four numbers should be generated. I have recorded audio files for each number (1-9) and for the four Digits List randomly four of them should be played.

I am really new to Unity so I don't really know how to do this. If you could help me or have any advice I would be very thankful.




How to get a random element from an array of objects using probabilities in vuejs

I try to call multiple times a method that draw an element from an array using probabilities.

My first method (first_function) is a promise that when resolved return this array :

[
          [
            {
              cardName: 'Energy Fire', cardRatio: 50
            },
            {
              cardName: 'Energy Water', cardRatio: 50
            }
          ],
          [
            {
              cardName: 'Charizard', cardRatio: 10
            },
            {
              cardName: 'Pikachu', cardRatio: 30
            },
            {
              cardName: 'Rayquaza', cardRatio: 60
            },
          ]
 ]

When the promise is resolved, i call another method (second_function) :

      my_promise.then(result => {
        for (const position in result ) {
          this.second_function(result[position])
        }    
      })

There is my second method (second_function) :

    second_function(pull) {
          var winner = Math.random() * 100;
          var threshold = 0;
          for (let i = 0; i < pull.length; i++) {
              threshold += pull[i].cardRatio;
              if (threshold > winner) {
                return console.log('winner',pull[i])
              }
          }
    }

I want to draw a random card from each array (this is why i call multiple times second_function in the first_function) but the problem is just one draw is resolved (i see just one console.log). However, second_function is called multiple times like expected but it looks like the for loop in the second_function is called one time only.




Fastest way to randomly sample N elements from a Python list with exclusions

Say I have a list of 20 unique numbers and I want to randomly sample N = 3 numbers from the list. For each number, there is the limitation that it cannot be in the final sample with some other numbers, given in a dictionary exclusions.

lst = list(range(20))
N = 3
exclusions = {0: [5], 1: [3, 13], 2: [10], 3: [1, 4, 18],
              4: [3, 15, 17, 19], 5: [0], 6: [12], 7: [13, 15],
              8: [10], 9: [16], 10: [2, 8, 12], 11: [15],
              12: [6, 10], 13: [1, 7], 14: [], 15: [4, 7, 11],
              16: [9], 17: [4], 18: [3], 19: [4]}

Right now I am using trial-and-error:

import random
sample = {random.choice(lst)}
n_sample = 1
while n_sample < N:
    s = random.choice([x for x in lst if x not in sample])
    if not set(exclusions[s]).isdisjoint(sample):
        sample.add(s)
        n_sample += 1

print(sample)
# {10, 2, 12}

However, this is super inefficient and cannot catch the case when there is no solution at all, especially when N is large. Can anyone suggest an efficient way to do this in Python?




dimanche 5 décembre 2021

the answer only keeps saying the first one

Every time I put in a number, it only prints the first input everytime instead of it being random. This is the code I used:

import random 
import sys 

answer = True 
while answer:
  question = input("Roll the di to get your fortune: ")

  answers = random.randint(1,6) 

  if question == "":
    sys.exit()

  elif answer == 1: 
    print("You will get a new friend. ")

  elif answer == 2:
    print("You will go to disneyland. ")

  elif answer == 3: 
    print("You will receive kindess.. ")

  elif answer == 4:
    print("Your will get a dog. ")

  elif answer == 5:
    print("You will suffer. ")

  elif answer == 6:
    print("You will have bad luck. ")






roll()

I really need help, I cant seem to figure out what I am doing wrong.




How to copy a file and rename it with a random number with js

I have a many files and I need to rename them with shuffle numbers.

Here is an example with 50 files (1 to 50) I found this code and I'am able to get the files renamed and put in a new folders ...

BUT some are not copied since their is some numbers that are generated twice. And if I run the script again and again, I get all my new 50 files but there is some that are duplicated.

const fs = require('fs');

for (let i = 1; i <= 50; i++) {

  function getRandomNumber(min, max) {
    
    let totalEle = max - min + 1;
    let result = Math.floor(Math.random() * totalEle) + min;
    return result;
  }
  function createArrayOfNumber(start, end) {
    let myArray = [];
    for (let i = start; i <= end; i++) {
      myArray.push(i);
    }
    return myArray;
  }
  let numbersArray = createArrayOfNumber(1, 50);

    let randomIndex = getRandomNumber(0, numbersArray.length - 1);
    let randomNumber = numbersArray[randomIndex];
    numbersArray.splice(randomIndex, 1);

    fs.copyFile(`old/${i}.json`, `new/${randomNumber}.json`, (err) => {});
}

It's my first steps in js, I try to figure it out and I'm not... What can I do ?




Add Two Numbers With Neural Network and Educating it

I am trying to create neural network that returns 1 when the sum of two numbers is positive and -1 when negative.

Datas And Targets

I writed the x1's and x2's into a 2D array and I tried to create random weights in a NeuralNetwork class. But I have no idea about generating random double weights between [-1,1] and educate the neuron. I coded a lil bit but I do not now how to execute the remaning part. I have been researching this for 5 days but I only learned sth about sigmoid functions. Here is my starting point.

import numpy as np from numpy import exp, array, random, dot, tanh

# Class to create a neural
# network
class NeuralNetwork():

        weights = [random.random(), random.random(),]
                     # weights generated in a list
        inputs = [[6, 5], [2, 4], [-3, -5], [-1, -1], [1, 1], [-2, 7], [-4, -2], [-6, 3]]

I am pretty new on ANN. Thanks a lot for the help.




Generate random doubles between 0 and 1000 in Java

I am working on an assignment for my Java class and I am having trouble generating a random dollar amount. I need the value to be a double between 0 and 1000 (for example, 561.64 or 968.42). nextDouble() only produces values between 0.0 and 1.0. I'm not having any luck searching here or on Google. Can anybody point me in the right direction? I am trying to use the SecureRandom class because that what we've used in other exercises, but I could probably use a different method if there's a good reason.




How to generate 2D array for random numbers?

I am a beginner here and want to generate a random number of float type in the range 0 to 1 with 3*4 size.

Later I want also to slice the first row and last column of the array.

I tried this one but it's not good way.

 import random
a=random.sample(range(0, 1))

Best




random.choice() not selecting all possibilities [closed]

random.choice() in Python does not work correctly.

I have the following function, but the following happens when called:

def Randomswitch():
    thechosenone = random.choice(range(0, 2))
    if (thechosenone == 0):
        return "WIN"
    if (thechosenone == 1):
        return "LOSE"

Randomswitch()

When Randomswitch is called it only returns WIN every time it's called.

I am breaking my head trying to figure this out.

Can anyone help me please?




samedi 4 décembre 2021

Random Number Guesser not running as intended

Code

Whenever I guessed the right number, It says that I lost. This is a simple project I made as a beginner so please explain in the simplest way possible




Creating a simple one-dimensional Sobol sequence generator

A Sobol sequence, a series of low-discrepancy quasi-random numbers in range [0,1], can be generated by first initializing a vector of direction numbers:

Dim V(31) As ULong
For i = 1 To 31
  V(i-1) = 2 ^ (32 - i)
Next

and then by fetching each number by continually looping through the enumeration below:

For Each lnumber As ULong In Sobol(V)
   MessageBox.Show(lnumber / 2 ^ 32)
Next

The above loop can be used to generate up to 2^32 values, which is the typical period of a linear congruential generator.

The question is, how can individual Sobol numbers be pulled from Sobol() without using a loop, and instead obtaining one number at a time from a single call-out to the function? The idea would be to instantiate a public class, anywhere in my code, like

Dim ran As New SobolNumber()

and then calling for the next number using for example:

Dim x as Double
x = ran.NextSobolNumber

The Sobol() function and required Ruler() function are listed below:

Public Iterator Function Sobol(ByVal v() As ULong) As IEnumerable(Of ULong)
    Dim s As ULong = 0
    For Each r In Ruler()
        Yield s = s Xor v(r)
    Next r
End Function

Public Iterator Function Ruler() As IEnumerable(Of Integer)
    Yield 0
    For Each r In Ruler()
        Yield r + 1
        Yield 0
    Next r
End Function



K-means on Python

I have code of k-means algorithm, but i don't know how to make my claster centers move. I have task, in which i need to randomly generate the numbers and the centers. In the cycle begin to move the centers (recalculate their coordinates) and they will simultaneously shift a small distance relative to their previous ones positions. This is the condition for stopping the cycle. MY CODE:

import numpy as np
import matplotlib.pyplot as plt

DIM = 2    # размерность массива точек
N = 2000    # количество точек
num_cluster = 2    # количество кластеров
iterations = 100    # итерации

x = np.random.randn(N, DIM)     # заполняем массив точками
y = np.zeros(N)     # обнуляем точки по y

for t in range(iterations):
    if t == 0:  # цикл центров
        index = np.random.choice(range(N), num_cluster, replace=False)  # выбираем центры кластеров
        mean = x[index]
    else:
        for k in range(num_cluster):
            mean[k] = np.mean(x[y == k], axis=0)  # подходят ли точки к кластеру
    for i in range(N):  # цикл приближения точек к цетру
        dist = np.sum((mean - x[i])**2, axis=1)     # расстояние от точек к центру
        pred = np.argmin(dist)      # выбираем найменшую дистанцию
        y[i] = pred     # выбираем точку с найменшей дистанцией

for k in range(num_cluster):    # цикл вывода кластера
    fig = plt.scatter(x[y == k, 0], x[y == k, 1])
    plt.scatter(x[index][0], x[index][1], c='r', marker="^")    # помечаем центры кластеров
plt.show()



how do I generate random numbers then add to a set in Java?

I want to make an empty set, then add N- many random numbers between 1 and 100 to a set. I used count to be up to 10 but I'm not sure if that is correct. I also am not sure how to add the generated numbers to the HashSet.

    //generates random birthdays
    Random coins = new Random();
    int number;

    for (int count = 1; count <= 10; count++){
        number = 1+coins.nextInt(100);
    }
      HashSet<Integer> hash = new HashSet<Integer>();
      hash.add(number);



I've declared variable "x" but i did not call it, is it ok to not call variables that have values assigned?

import random


def add_sums(Num):
    total = 0
    all_num = []
    for x in range(1, Num+1):
        gen = random.randint(1, 30)
        all_num.append(gen)
    
    print("List:", all_num)
    for y in all_num:
        total += y
    print("List total:", total)


user_max = int(input("Max numbers in list: "))
add_sums(user_max)

In this program, the user will enter the total amount of numbers in a list. the random module will generate random numbers between 1 to 30. Then all the numbers from the list will be added together.

I've tried to use the variable x but it doesn't give the results I want, does anyone know a better/simpler way of creating this program. Also, is it bad practice to create a variable and not call it?




How to generate randome Integers in react js without repeating [duplicate]

When the user press the button next function NextQuestion will be called this function should be able to loop randomly through data (array of objects with two properties name and description) without repeating the same elements each time the user press the button next and then after it finishes showing all elements it should call another function to alert me (for future developing)

import React, {useContext} from 'react';
import CheckAnswer from './CheckAnswer';
import { RandomIntContext } from '../Contexts/RandIntContext';
import { ExamStateContext } from '../Contexts/ExamStateContext';
import { DataContext } from '../Contexts/DataContext';

import { ButtonGroup, ToggleButton, Button } from 'react-bootstrap';

const NextQuestion = () => {

    const {randInt, setRandInt} = useContext(RandomIntContext);
    const {examState, setExamState} = useContext(ExamStateContext);
    const {data} = useContext(DataContext);

    const nextQuestion = () => {
        setRandInt(Math.floor(Math.random() * data.length));
    }

    return (
        <div className="next_cont">
            <div>
                <ButtonGroup>
                    <ToggleButton type="radio" variant="outline-dark" value="word" size="md" checked= {examState === "word"} onClick={(e) => setExamState("word")}> Word</ToggleButton>
                    <ToggleButton type="radio" variant="outline-dark" value="description" size="md" checked= {examState === "description"} onClick={(e) => setExamState("description")}> Description</ToggleButton>
                </ButtonGroup>
            </div>

            <h3>{examState === "word" ? "What is the description of the word" : "What is the word that describes"} {data[randInt][examState]}</h3>

            <CheckAnswer/>

            <div>
                <Button variant="outline-dark" onClick={nextQuestion}>Next</Button>
            </div>
        </div>
    )
}

export default NextQuestion



Unknown Amount of Random Objects with a value 0 - 1 - get one of them respecting their 0 - 1 value like a rarity [JAVA]

I'm currently writing a project where I need to get a random object respecting a rarity saved in each object with a method like this:

public Item getRandomItem() {
return ?
}

The 0-1 Value is stored in every Item (Items are in a Set<>):

Item#getRarity()

So how can I get a random Item respecting the "rarity" in the "Item" so that for example if there is only one Item in the Set<Item> with the rarity "0.4" it would be given to 100% and if there are two entries with the same rarity there would have a change 50% each and if there would be another two entries with rarities "0.1" and "0.9" there would have 10 and 90% chance. My problem is that all the rarities together are not 1 (100%) so it is possible that all the rarities together are higher or lower than the Number "1".

I hope you understand my problem and you have an idea how to solve it.

Thanks




vendredi 3 décembre 2021

How do I use the MOD or % operator to get [equal number of items] for each [slot] in an Array size of 12?

Abstract:

Homework I'm giving myself.

How do I fill an array evenly with Cryptorandom, Random, or /dev/random data?

Where does the engineering fail when this is used in an Application and where can I find its signal in SysOps and Security?




matlab random number generation in parfor loop

I want to generate same normal random numbers for loop and parfor loop. Following MATLAB documentation I tried three different method:

Method 1: Using rng(seed, 'twister')

N = 1;

for ind = 1:10
    rng(ind, 'twister')
    samps(ind) = normrnd(0,1,N,1);
end

plot(samps); hold on

parfor ind = 1:10
    rng(ind, 'twister')
    samps(ind) = normrnd(0,1,N,1);
end

scatter(1:length(samps), samps)
legend({'using for loop', 'using parfor loop'})

By using rng twister method

Method 2: Using RandStream Method

N = 1;
 
sc = parallel.pool.Constant(RandStream('Threefry'));
for ind = 1:10
    stream = sc.Value;
    stream.Substream = ind;
    samps(ind) = normrnd(0,1,N,1);
end

plot(samps); hold on

sc = parallel.pool.Constant(RandStream('Threefry'));
parfor ind = 1:10
       stream = sc.Value;
       stream.Substream = ind;
       samps(ind) = normrnd(0,1,N,1);
end

scatter(1:length(samps), samps)
legend({'using for loop', 'using parfor loop'})

Using Threefry stream-substream method

Method 3: Using another RandStream method

N = 1;
 
stream = RandStream('mrg32k3a');
for ind = 1:10
    stream.Substream = ind;
    samps(ind) = normrnd(0,1,N,1);
end

plot(samps); hold on

stream = RandStream('mrg32k3a');
parfor ind = 1:10
       set(stream,'Substream',ind);
       samps(ind) = normrnd(0,1,N,1);
end

scatter(1:length(samps), samps)
legend({'using for loop', 'using parfor loop'})

Another randStream method

My question is why the last two methods are not working. If I understood MATLAB documentation correctly, they should have worked. Also, is there anything wrong with using rng(seed, 'twister') method with different seeds to produce statistically independent samples?




ValueError: Sample larger than population or is negative but list contains more elements than sample size in list retrieved from url

python 3: I am trying to code a bingo game which asks the user for 1-3 players, assigns each player a name, and then creates their Bingo card by choosing 25 elements from the list listOfStrings. the list contains 53 elements which are all strings. I am getting the error "ValueError: Sample larger than population or is negative" but 25<53 ? is the size of my list incorrect or do I have to assign each element a number? not sure why this is happening. im new to programming so probably a simple mistake or miscomprehension. thanks in advance

import urllib.request
import random
listOfStrings = []

def createList():
    try:
       with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f:
           d = f.read().decode('utf-8')
           split= d.split("\n")
           listOfStrings = split
    except urllib.error.URLError as e:
        print(e.reason)


def players(listOfStrings):
    noPlayers = input("How many players would like to play Bingo? Choose 1-3: ")
    if noPlayers == "1":
        name = input("What is the name of player 1? ")
        player1card = random.sample(list(listOfStrings), 25) 


createList()
players(listOfStrings)
print(player1card)



(PHP) having issues making a foreach loop that rolls a dice for 6 characters using rand() and compares their old stat with the new one from dice [closed]

I have been stuck on this PHP exercise for almost a week, the multiple values in the array are confusing me.

exercise: Here is the code representing a group of four characters in an associative array whose key is the name of the character.

$characters = [
  "Ganolon" => ["Strength" => 1, "Dexterity" => 2,
  "Intelligence" => 6, "Wisdom" => 6, "Charisma" => 5],
  "Cony" => ["Strength" => 5, "Dexterity" => 4,
  "Intelligence" => 3, "Wisdom" => 3, "Charisma" => 6],
  "Aegon" => ["Strength" => 6, "Dexterity" => 5,
  "Intelligence" => 5, "Wisdom" => 1, "Charisma" => 5],
  "Mountain" => ["Strength" => 1, "Dexterity" => 3,
  "Intelligence" => 4, "Wisdom" => 5, "Charisma" => 3]
];

From this array, write the code to do the following operations: a) Have all the characters take a Charisma test, by rolling a 6-sided dice for each character (use rand ()!)and compare the result with the character's initial Charisma attribute. If his attribute is greater than or equal to the result obtained on the dice, the character has passed the test. Generate a UL list showing each of the test results, including a message saying if the character has passed the test.

Heres what I have so far:

foreach ($characters as $x => $value) {
  $diceThrow = rand(1,6)

  if($diceThrow <= ) {}
}



Random numbers in a matrix which are divisible by 5 in R?

How can I write random numbers in a matrix which are divisible by 5 in R? For instance, 20 20 85 45 55 5 15 20 90 10




How to hide Value in array for Battleship game?

I'm on my way to create an Battleship game however i'm not sure on how to change the 1 in the first players grid to a 0, so that the player can not see where the ship is.

import random

# formatt to access certain grid point print (grid_1[1][2])

grid_1 = [[0, 0, 0, 0],
          [0, 0, 0, 0],
          [0, 0, 0, 0],
          [0, 0, 0, 0]]

row_random = random.randint(0,3)
column_random = random.randint(0,3)
ship_1 = grid_1[row_random][column_random] = 1 
# creates a random spot in the grid where the ship will be 







def Player_1():
 
  for i in grid_1:
    print (i)
    #loops through grid so the output is in row and column form 
  x = int(input("Enter row:"))
  y = int(input("Enter column:"))
  co_ordinates_1 = (grid_1[x][y])
  # user guses where the ship will be
  if co_ordinates_1 == 1:
    print("BATTLESHIP HIT")
  elif co_ordinates_1 != 1:
    print("You missed!")
  # shows the user if they hit the target or not
Player_1()



why do I get error listOfStrings not defined when it's defined and taken as a parameter?

for python 3: I am trying to code a bingo game where each player has a card of 25 strings (in a 5x5 pattern) which are chosen randomly from a list. the list has 53 different items to choose from. im working on adding the players, and when each player is added I want to create their card. when I try player1card = random.sample(list(listOfStrings), 25) it just says that my list isn't defined even though I thought it was. can someone explain to me why? thank you in advance

import urllib.request
import random


def createList():
    listOfStrings = []
    try:
       with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f:
           d = f.read().decode('utf-8')
           split= d.split("\n")
           listOfStrings = split
    except urllib.error.URLError as e:
        print(e.reason)


def players(listOfStrings):
    noPlayers = input("How many players would like to play Bingo? Choose 1-3: ")
    if noPlayers == "1":
        name = input("What is the name of player 1? ")
        player1card = random.sample(list(listOfStrings), 25) 


createList()
players(listOfStrings)
print(player1card)

returns NameError: name 'listOfStrings' is not defined




Parallel sampling and groupby in pandas

I have a large df (>=100k rows and 40 columns) that I am looking repeatedly sample and groupby. The code below works, but I was wondering if there is a way to speed up the process by parallelising any part of the process. The df can live in shared memory, and nothing gets changed in the df, just need to return 1 or more aggregates for each column.

import pandas as pd
import numpy as np
from tqdm import tqdm

data = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

data['variant'] = np.repeat(['A', 'B'],50)

samples_list = []
for i in tqdm(range(0,1000)):
    df = data.sample(
            frac=1, # take the same number of samples as there are rows
            replace=True, # allow the same row to be drawn multiple times
            random_state=i # set state to be i for reproduceability
            ).groupby(['variant']).agg(
                {
                    'A': 'count',
                    'B': [np.nanmean, np.sum, np.median, 'count'],
                    'C': [np.nanmean, np.sum],
                    'D': [np.sum]
                }
                )
    df['experiment'] = i
    samples_list.append( df )

# Convert to a df
samples = pd.concat(samples_list)

samples.head()