dimanche 31 juillet 2022

Find sample size in R for a Randomised Control Trial [closed]

I am having a RCT, with drug:placebo, having 2:1 ratio.

My hypothesis is to compare Progression Free Survival for drug vs placebo.

Is there any kind of R package which supports sample size calculation for such a RCT ?




Sample Multiple Columns Without Repeats R dplyr

I am trying to solve a problem where I take a random sample based on probability with 5 observations per row where I observe a color out of a possible set of colors, exclude the observed color from the next observation and repeat. Colors can repeat in any given column, but not in the same row.

Here is how I have approached the problem:

library(tidyverse)

data <- tibble(obsId = 1:100)

colors <- tibble(color = c('red', 'blue', 'white', 'yellow', 'green', 'orange', 
                           'gray', 'brown', 'purple', 'black', 'pink', 'navy', 
                           'maroon'), 
                  prob = c(0.85, 0.85, 0.75, 0.75, 0.65, 0.5, 0.5, 0.5, 0.4, 
                           0.4, 0.25, 0.15, 0.15))

data <- data %>% 
      mutate(color1 = sample(x = colors$color, size = n(), 
                          prob  = colors$prob, replace = T),
             color2 = sample(x = colors$color, size = n(), 
                          prob  = colors$prob, replace = T),
             color3 = sample(x = colors$color, size = n(), 
                          prob  = colors$prob, replace = T),
             color4 = sample(x = colors$color, size = n(), 
                          prob  = colors$prob, replace = T),
             color5 = sample(x = colors$color, size = n(), 
                          prob  = colors$prob, replace = T)

The issue I have is that color 2 will be equal to color 1 (and so forth) in certain rows. Is there any easy way to resolve this?




Seeded RandomGenerators in Java 17

Java 17 has introduced a new RandomGeneratorFactory class for instantiating random number generators. The create(long) method is described as

Create an instance of RandomGenerator based on algorithm chosen providing a starting long seed. If long seed is not supported by an algorithm then the no argument form of create is used.

However there doesn't seem to be a method of RandomGeneratorFactory that can be used to determine if a long seed is supported. How is it possible to use the new API to obtain an instance of RandomGenerator that is guaranteed to be created using a supplied long seed?




random.randint is not picking "random" numbers [closed]

I'm trying to generate 4 lists with random numbers. But the numbers don't seem "random" at all. They are very similar to one another, which is very frustrating. Here is my function:

def generate_Lt_Ut(n, delta):
    Ut1 = [random.randint(1,100) for i in range(n)]
    Ut2 = [random.randint(1,100) for i in range(n)]
    Lt1 = [random.randint(max(1,Ut1[i]-delta),Ut1[i]) for i in range(n)]
    Lt2 = [random.randint(max(1,Ut2[i]-delta),Ut2[i]) for i in range(n)]
    return Ut1, Ut2, Lt1, Lt2

I tried running the following a couple of times:

Ut1, Ut2, Lt1, Lt2 = generate_Lt_Ut(4, 30)
print("Ut1: " + str(Ut1))
print("Ut2: " + str(Ut2))
print("Lt1: " + str(Lt1))
print("Lt2: " + str(Lt2))

Here is what I got:

Repetition 1:

Ut1: [91, 91, 91, 91]
Ut2: [91, 91, 91, 91]
Lt1: [72, 72, 72, 72]
Lt2: [72, 72, 72, 72]

Reptetition 2:

Ut1: [79, 79, 79, 79]
Ut2: [79, 79, 79, 79]
Lt1: [77, 77, 77, 77]
Lt2: [77, 77, 77, 77]

Repetition 3:

Ut1: [99, 99, 99, 99]
Ut2: [99, 99, 99, 99]
Lt1: [72, 72, 72, 72]
Lt2: [72, 72, 72, 72]

Repetition 4:

Ut1: [89, 89, 89, 89]
Ut2: [89, 89, 89, 89]
Lt1: [74, 74, 74, 74]
Lt2: [74, 74, 74, 74]

I have no idea what's going on and would appreciate any help.




C Language - How to make rand value a constant for masking and unmasking in a hangman game

I am doing a project for a small hangman game that picks from a random selection of words and the user has to guess what the word is with a scanf inputting letters with a counter that builds a hangman, resulting either in a game over or win.

The issue lies in that when using the word[x] it isn't accepting it as "Expression must have a constant value", this error comes up in;

int mask[m];

and

mask[i] = 0;

All I can guess is that the rand function is the issue, but I have no idea how to fix it, anyone has a clue?

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <time.h>
#include <string>
#define ARRAY_SIZE 10

int main()
{
    //randomwordgenerator
    char word[ARRAY_SIZE][200] = { "tiger", "lion", "elephant", "zebra", "horse", "camel", "deer", "crocodile", "rabbit", "cat" };


    int x = 0;
    srand(time(0));

    x = rand() % ARRAY_SIZE;

    system("pause");

    //masking and unmasking word
    char m = strlen(word[x]);//will count the number of letters of the random word
    int mask[m];
    for (int i = 0; i < m; ++i) {
        mask[i] = 0;
    }

    return 0;
}
//Still have to do the loop and counter that prints out hangman



How can I code a variable in C++ to follow a distribution from the given graph? [closed]

Empirical CDF of the variable

I have to code a variable Pr (received signal power) in C++ such that it follows the given graph. I am required to use inverse CDF method to generate random numbers to achieve the same. Can someone tell me about the code to do so.




samedi 30 juillet 2022

Random Number Generator isnt random [duplicate]

The objective of this program is to ask a user to enter a number of books with their authors (first and last name), and organize them based on the author's last name. After the list is organized, it should also generate a random ISBN for the book with 13 digits. the last digit uses a certain equation to be generated. the problem I'm having is the ISBN number portion. It doesn't generate a unique number for each book. It will print the same ISBN for each book, even though the number is random. I would like some help in understanding why it's doing that.

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

char ISBNUM[20];
char* getISBN();
struct Book {
    char fname[20];
    char lname[20];
    char title[50];
    char ISBN[20];
};
long getRandom(int lower, int upper,int count) {
    //Random Number Generator
    int i;
    long num;
    srand(time(0));

    for (i = 0; i < count; i++) {
    num = rand() % (upper - lower) + lower;
    return num;
    }
}
//Start of main function
int main() {
    int n;
    char *isbn;
    //Takes user input for number of books
    printf("Please enter number of books: ");
    scanf("%d",&n);
    struct Book b[n];
    struct Book temp;
  
   //takes user input for books
    for(int i=0;i<n;i++) {
        printf("Enter info for book %d: ", i + 1);
        scanf("%s %s %[^\n]s",b[i].fname, b[i].lname, b[i].title);    
    }

    for(int i=0;i<n;i++) {
        char *isbn; 
        isbn=getISBN();
        strcpy(b[i].ISBN,isbn); 
    }
        //Sorts the names in alphabetical order based on Last name
        for(int i=0;i<n;i++) {
            for(int j=i+1;j<n;j++) {
               if(strcmp(b[i].lname,b[j].lname)>0) {
                   temp=b[i];
                   b[i]=b[j];
                   b[j]=temp;
               }
            } 
        }
    //Prints the inputted data
    for(int i=0;i<n;i++) {
        printf("\n%s %s\t ,%30s\t ,%40s",b[i].lname,b[i].fname,b[i].title,b[i].ISBN);
    }
    return 0;
}
//Generates the ISBN Number
char* getISBN() {
    int lower = 10000000, upper =99999999, count = 1;
    
    long num1 = getRandom(lower, upper, count);
    char s1[15];
    sprintf(s1,"%d",num1);

    char ISBN[]="9780";
    strcat(ISBN,s1);
    int A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12;
    A1=9;
    A2=7;
    A3=8;
    A4=0;
    A5=num1 % 10;
    A6=num1 % 10;
    A7=num1 % 10;
    A8=num1 % 10;
    A9=num1 % 10;
    A10=num1 % 10;
    A11=num1 % 10;
    A12=num1 % 10;

    int d = 10-((A1+A2*3+A3+A4*3+A5+A6*3+A7+A8*3+A9+A10*3+A11+A12*3) % 10);
    char s2[15];
    sprintf(s2,"%d",d);
    
    //Replace 10 with 'X' if generated
    if(d == 10) {
        char d ='x';
        sprintf(s2,"%c",d);
    } 
    strcat(ISBN,s2);
    char ISBN2[50];
    int j=0;
    for(int i=0;i<14;i++) {
        if(i==3||i==4||i==9||i==12) {
            ISBN2[j]='-';
            j++;
        }
        ISBN2[j]=ISBN[i];
        j++;
    } 
    for(int i=0;i<14;i++) {
    strcpy(ISBNUM,ISBN2);
    }
    return ISBNUM;
}



Can't make a good ioctl request (-1) to /dev/urandom with `RNDADDENTROPY`

I'm new the the /dev/random|/dev/urandom interface.

Reading the /dev/random manual for the ioctl() interface, using RNDADDENTROPY shows this

    Add some additional entropy to the input pool,
              incrementing the entropy count.  This differs from writing
              to /dev/random or /dev/urandom, which only adds some data
              but does not increment the entropy count.  The following
              structure is used:

                  struct rand_pool_info {
                      int    entropy_count;
                      int    buf_size;
                      __u32  buf[0];
                  };

              Here entropy_count is the value added to (or subtracted
              from) the entropy count, and buf is the buffer of size
              buf_size which gets added to the entropy pool.

In post, I saw a more understandable struct to pass to the ioctl call.

However, I'm not sure about the parameters of the ioctl() call I need to make.

I've tried:

int fd_w_noblock = open(_FILE,O_NONBLOCK);
struct my_rand_pool_info rnpl
int ret = ioctl(fd_w_noblock,RNDADDENTROPY, &rnpl) // assuming the output of the ioctl() call is sent to struct rand_pool_info (my struct my_rand_pool_info has has sized `buf`)

I can't seem to make a good ioctl() call, get ret==-1. Please guide me with the parameters of my ioctl() call.




ai need source code for generate random polygon by genetic algorithm

hi to all I need a source code in matlab for generate polygon via generic algorithm. can you help me? thanks a lot .




vendredi 29 juillet 2022

How do you create 3 random numbers that add up to a specific number in python [duplicate]

I'm trying to create a code that will generate 'x' numbers that all add up to 'y'. For example, 3 numbers that add up to 100: 25, 25, 50. I am having trouble even finding a way to write an example code so this is the best I've got.

import random

finalnum = 100
sum = 0

num1 = random.randint(0, finalnum)
sum += num1

num2 = random.randint(0, finalnum - num1)
sum += num2

num3 = finalnum - sum
sum += num3

print(num1, '+', num2, '+', num3, '=', sum)

There are a number of issues with this example. The biggest is that you can't choose how many numbers add up to the final number, and the next issue is that it is totally imbalanced. The first randomized number is usually the biggest number. I want each of the numbers to have a truly random chance to be the biggest if that is possible. Thanks!




Get all the combinations a number can be split into

I have a fixed number (5) and a fixed length (2):

I want to find all the combinations that can sum 50 (this can vary of course).

For example, for 50, and a length of 2, I want to get:

[[1, 49], [2, 48], [3, 47], [4, 46], ...],

For 50 and a length of 4, I want to get:

[[1, 1, 1, 47], [1, 1, 2, 46], [1, 1, 3, 45], [1, 1, 4, 44], ...],

I have no clue how to do this, or whether there's a name in mathematics for this.

This is what I have (doesn't have to use generators):

function getCombinations(array $numbers, int $sum, int $setLength) : \Generator {
    $numbersLowestFirst = $numbers;
    asort($numbersLowestFirst);
    $lowestNumber = 0;
    foreach ($numbersLowestFirst as $number) {
        // array might be associative and we want to preserve the keys
        $lowestNumber = $number;
        break;
    }

    $remainingAmount = $sum - $lowestNumber;
    $remainingNumberofItems = $setLength - 1;

    $possibleItemCombinations = array_pad([$remainingAmount], $remainingNumberofItems, $lowestNumber);

}



Using rpois and rnbinom with dplyr commands

I am trying to generate random numbers within a tibble where different categories of item are distributed differently. I'm not having much luck. Here's the code and the error it produces:

library(dplyr)

letters <- tibble(letter = c(rep("A", 5), rep("B", 5), rep("C", 5) ))

letters %>%
  rowwise() %>%
  mutate(Proj = case_when(
    letter == "A" ~ rpois(1, lambda = .7746),
    letter == "B" ~ rnbinom(1, size = 3.3848, mu = 1.2),
    letter == "C" ~ rpois(1, lambda = .5057)
  ))

#> Error in `mutate()`:
#> ! Problem while computing `Proj = case_when(...)`.
#> ℹ The error occurred in row 1.
#> Caused by error in `` names(message) <- `*vtmp*` ``:
#> ! 'names' attribute [1] must be the same length as the vector [0]

Interestingly, the code works just fine if I use continuous distributions instead of discrete distributions.

library(dplyr)

letters <- tibble(letter = c(rep("A", 5), rep("B", 5), rep("C", 5) ))

letters %>%
  rowwise() %>%
  mutate(Proj = case_when(
    letter == "A" ~ rweibull(1, shape = 2.3487, scale = 8.174),
    letter == "B" ~ rexp(1, rate = .0442),
    letter == "C" ~ rnorm(1, mean = 0, sd = 1)
  ))

#> # A tibble: 15 × 2
#> # Rowwise: 
#>    letter   Proj
#>    <chr>   <dbl>
#>  1 A       9.82 
#>  2 A       7.72 
#>  3 A      12.9  
#>  4 A       7.81 
#>  5 A       6.44 
#>  6 B      10.4  
#>  7 B       3.14 
#>  8 B       1.48 
#>  9 B      28.7  
#> 10 B      11.0  
#> 11 C      -0.378
#> 12 C      -0.340
#> 13 C       1.81 
#> 14 C       1.03 
#> 15 C      -0.679

Created on 2022-07-29 by the reprex package (v2.0.1)

What's going on here?




Is there any way to choose a random document in firebase and flutter

I'm trying to make a positive phrases app, which will appear happy phrases like: "You are very important; Fight as you can, but never give up" and if you click on the "again" button (in Portuguese "again") another phrase will appear.

But I'm stuck on how I'm going to show these phrases within the space I've placed (a white rectangle in the center), and how to choose them randomly. I'm new to programming, sorry for any stupid questions.

My initial idea was to create a database in firebase where I would put the phrases and could update them periodically, and so I would also get them somehow randomly.

Photo of my project

Here is my code:

import 'package:flutter/material.dart';
import 'package:adobe_xd/pinned.dart';
import './home_mob.dart';
import 'package:adobe_xd/page_link.dart';
import './produtos_mob.dart';
import './about_us_mob.dart';
import 'package:flutter_svg/flutter_svg.dart';

class Virtual0 extends StatelessWidget {
  Virtual0({
    Key? key,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xff5808fb),
      body: Stack(
        children: <Widget>[
          Pinned.fromPins(
            Pin(start: 8.5, end: 9.5),
            Pin(size: 33.5, start: 39.0),
            child: Stack(
              children: <Widget>[
                Pinned.fromPins(
                  Pin(size: 37.0, start: 51.0),
                  Pin(size: 19.0, start: 0.0),
                  child: PageLink(
                    links: [
                      PageLinkInfo(
                        transition: LinkTransition.Fade,
                        ease: Curves.easeOut,
                        duration: 0.3,
                        pageBuilder: () => HomeMob(),
                      ),
                    ],
                    child: Text(
                      'Inicio',
                      style: TextStyle(
                        fontFamily: 'Bauhaus Modern',
                        fontSize: 16,
                        color: const Color(0xffffffff),
                      ),
                      softWrap: false,
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment(-0.027, -1.0),
                  child: SizedBox(
                    width: 65.0,
                    height: 19.0,
                    child: PageLink(
                      links: [
                        PageLinkInfo(
                          transition: LinkTransition.Fade,
                          ease: Curves.easeOut,
                          duration: 0.3,
                          pageBuilder: () => ProdutosMob(),
                        ),
                      ],
                      child: Text(
                        'Produtos',
                        style: TextStyle(
                          fontFamily: 'Bauhaus Modern',
                          fontSize: 16,
                          color: const Color(0xffffffff),
                        ),
                        softWrap: false,
                      ),
                    ),
                  ),
                ),
                Pinned.fromPins(
                  Pin(size: 46.0, end: 50.0),
                  Pin(size: 19.0, start: 0.0),
                  child: PageLink(
                    links: [
                      PageLinkInfo(
                        transition: LinkTransition.Fade,
                        ease: Curves.easeOut,
                        duration: 0.3,
                        pageBuilder: () => AboutUsMob(),
                      ),
                    ],
                    child: Text(
                      'Sobre',
                      style: TextStyle(
                        fontFamily: 'Bauhaus Modern',
                        fontSize: 16,
                        color: const Color(0xffffffff),
                      ),
                      softWrap: false,
                    ),
                  ),
                ),
                Pinned.fromPins(
                  Pin(start: 0.0, end: 0.0),
                  Pin(size: 1.0, end: 0.0),
                  child: SvgPicture.string(
                    _svg_oyi0he,
                    allowDrawingOutsideViewBox: true,
                    fit: BoxFit.fill,
                  ),
                ),
              ],
            ),
          ),
          Pinned.fromPins(
            Pin(start: 25.0, end: 25.0),
            Pin(size: 547.0, end: 107.0),
            child: Stack(
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                    color: const Color(0xffffffff),
                    borderRadius: BorderRadius.circular(45.0),
                    border:
                        Border.all(width: 1.0, color: const Color(0xff707070)),
                  ),
                ),
                Pinned.fromPins(
                  Pin(start: 19.0, end: 19.0),
                  Pin(size: 59.0, start: 21.0),
                  child: Text(
                    'Frase do dia',
                    style: TextStyle(
                      fontFamily: 'Bauhaus Modern',
                      fontSize: 49,
                      color: const Color(0xff5808fb),
                    ),
                    softWrap: false,
                  ),
                ),
                Pinned.fromPins(
                  Pin(size: 190.0, middle: 0.5037),
                  Pin(size: 37.0, end: 32.0),
                  child: Stack(
                    children: <Widget>[
                      Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment(0.0, -1.0),
                            end: Alignment(0.0, 1.0),
                            colors: [
                              const Color(0xff5808fb),
                              const Color(0xff9929ea)
                            ],
                            stops: [0.0, 1.0],
                          ),
                          borderRadius: BorderRadius.circular(150.0),
                        ),
                      ),
                      Pinned.fromPins(
                        Pin(size: 107.0, middle: 0.4337),
                        Pin(size: 24.0, start: 4.0),
                        child: Text(
                          'novamente',
                          style: TextStyle(
                            fontFamily: 'Bauhaus Modern',
                            fontSize: 20,
                            color: const Color(0xffffffff),
                          ),
                          softWrap: false,
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  decoration: BoxDecoration(
                    color: const Color(0xffffffff),
                    boxShadow: [
                      BoxShadow(
                        color: const Color(0x29000000),
                        offset: Offset(0, 3),
                        blurRadius: 6,
                      ),
                    ],
                  ),
                  margin: EdgeInsets.fromLTRB(33.0, 105.0, 44.0, 105.0),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

const String _svg_oyi0he =
    '<svg viewBox="8.5 71.5 357.0 1.0" ><path transform="translate(8.5, 71.5)" d="M 0 1 L 357 0" fill="none" stroke="#ffffff" stroke-width="2" stroke-miterlimit="4" stroke-linecap="round" /></svg>';



How can I set a button to load random pages from my WordPress site?

There seems to be a plugin for doing with this with posts, but I will never use posts as long as I live. I tried it out and of course it didn't do anything. Is there a way I can put something in code snippets (or even anything easier) that would be triggrred by a URL/button?

If you're knowledgable and kind enough to answer, please bear that in mind that I have zero understanding of code. :/

Thanks.




how to make a rand() number become static in every post - wordpress

I make scheduled post using wp_schedule_single_event(), the value of post_content is using [shortcode]. I generate random number using rand(), and want to put it inside every post.

The problem is, i want to make the random number become permanent/static. So, Every time the post refresh, the number won't change.




jeudi 28 juillet 2022

Generating a random number from highest count numbers in a list of tuples in Python

This really isn't an issue...more of a brain storming...

Let's say I have a list of tuples like so:

The second index of the tuple is a count of how many times the first index appeared in a dataset.

[(24, 11), (12, 10), (48, 10), (10, 9), (26, 9), (59, 9), (39, 9), (53, 9), (21, 9), (52, 9), (50, 9), (41, 8), (33, 8), (44, 8), (46, 8), (38, 8), (20, 8), (57, 8), (23, 7), (6, 7), (3, 7), (37, 7), (51, 7), (34, 6), (54, 6), (36, 6), (14, 6), (17, 6), (58, 6), (15, 6), (29, 6), (13, 5), (32, 5), (9, 5), (40, 5), (45, 5), (1, 5), (31, 5), (11, 5), (30, 5), (5, 5), (56, 5), (35, 5), (47, 5), (2, 4), (19, 4), (42, 4), (25, 4), (43, 4), (4, 4), (18, 4), (16, 4), (49, 4), (8, 4), (22, 4), (7, 4), (27, 4), (55, 3), (28, 2)]

As you can see there are multiples of the same number in the second index. Is there a way you could collect the first six of the counts and put them into another list?

For example collect all the 11, 10, 9, 8, 7 counts and so on and then generate a number of six in length from that collection.

I am trying to generate a random number from the 6 most common numbers.




How to randomly take an element from a list and put in into a different list but delete that same element from the list you that took from? [closed]

test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11]
user_numbers = []
user_numbers.append(random.sample(deck))



Sample from Binomial(n, p) whose mean equals 1 / (1 - p)

Discussion is on going for this closed question: Binomial distribution in R. We want to draw samples from a Binomial(n, p) whose mean equals 1 / (1 - p).

I decide to open a new question because:

  1. the original one was closed for lack of clarity;

  2. I am assuming that I have understood the original poster correctly.

As stated, the description of the problem is very clear now. Write an R function to get such samples.




Random.randient is Showing error when called in a Function

hey I am making a game in pygame I made a function in pygame that if bg_object is smaller than equal to the cap of the number objects allowed , I implemented this quickly, but I ran into a problem , the problem is whenever I try to blit a image in screen it is showing an error , I know to put it in a class for multiple objects in a background but I am testing this

Here is the Function:


# Backround Cosmetics
FlowerPos = [random.randint( SCREEN_WIDTH , SCREEN_HEIGHT ) , random.randint( SCREEN_WIDTH , SCREEN_HEIGHT )]
StonePos = [random.randint( SCREEN_WIDTH , SCREEN_HEIGHT ) , random.randint( SCREEN_WIDTH , SCREEN_HEIGHT )]
Grass1Pos = [random.randint( SCREEN_WIDTH , SCREEN_HEIGHT ) , random.randint( SCREEN_WIDTH , SCREEN_HEIGHT )]
Grass2Pos = [random.randint( SCREEN_WIDTH , SCREEN_HEIGHT ) , random.randint( SCREEN_WIDTH , SCREEN_HEIGHT )]

def Backround_cosmetics():
    bg = 0
    if bg <= Backround_cosmetics_cap:
        Random_bg = (random.randint( 1 , 3 ))

        if Random_bg == 1:
            Win.blit( flower , ( FlowerPos[0] , FlowerPos[1] ))
            bg += 1

        if Random_bg == 2:
            Win.blit( stone , ( StonePos[0] , StonePos[1] ))
            bg += 1

        if Random_bg == 3:

            grass_type = random.randint( 1 , 2 )
            if grass_type == 1:
                Win.blit( grass1 , (( Grass1Pos[0] , Grass1Pos[1] )))
                bg += 1

            if grass_type == 2:
                Win.blit( grass2 , (( Grass2Pos[0] , Grass2Pos[1] )))
                bg += 1
            

I am mentioning the Function in the loop like this:

while Running:
    [...]
    Backround_cosmetics()
    [...]



Binomial distribution in R

I am developing code for a paper for a university project and I need to "generate a random number x that is binomially distributed with mean (1 - p)^-1. How can I do this in R?




mercredi 27 juillet 2022

Generate random but always different numbers within a range with CSPRNG

I have a CSPRNG that I'm using to generate 5 numbers between 0 and 20. The problem is, there could be cases where it generates the same number again. So say it generates 5 but running again, it could come out to be 5. If not, then the third or 4th number could be 5.

I want a way to do this where I'm 100% sure the 5 numbers are never the same, even if they do come up as same, I want to re-generate that number in a way that none of the numbers clash.

I thought of using a while loop for each number, to regenerate the number while it's same as the other 4 numbers but that obviously is not optimal and may cause to get stuck in long loops.

Is there a better way?




Create a function that select RANDOM number not previously selected

I need assistance from you, I don't know how to solve this due to my poor (and old) programming skills.

How can I create a function in Excel that when activated (via button), pick a random number in a certain range and after that, if activated again, pick another random number in the same range but excluding the number selected before.

Example:
Random (1,50) -> 44
Random (1,50) except 44 -> 39
Random (1,50) except 44,39 -> 2
etc.

Thank you so much and have a nice day




mardi 26 juillet 2022

Is there a weighted random number excel formula that excludes other numbers? [closed]

I have an excel formula that generates various weighted random numbers in column A, using INDEX, MATCH and RAND. However, I'm trying to create another column with weighted random numbers that exclude the numbers from column A. Does anyone know how to do this?




Generate Random Number, that is that is repeatable

I have generated a code in order to replace the entire original column, with random repeated value but it doesnt give the desired output

enter code here
 
 if range(Selected_Data1(:,1)) ==0
    for Iter=1:length(Selected_Data1)
    rng(1);
    P_MMSI(Iter) = rand(1);
      
    end
 end

The above code always replace the value 209026000 with 0.417022004702574, nevertheless, I am expecting the random output vector would be 9 integer numbers (e.g., 781234012)

For example, if the original column is

Original Column
 209026000   
 209026000
 209026000
 209026000
 209026000
 209026000
 

 % The expected output would be something 
 781234012
 781234012
 781234012
 781234012
 781234012
 781234012

Or if

 Original Column
 209026000   
 209026000
 209026000
 209026000
 209026000
 209026000

The Output is by replacing the last two or three digits

 209026108   
 209026108
 209026108
 209026108
 209026108
 209026108



R sampling either 0 and 1 based on a vector of probabilities

I want to sample 10 numbers, either 0 or 1, with the following chances:

c(0.1989185, 0.2879522, 0.1142932, 0.3057067, 0.2056559, 0.1492126, 
0.2775737, 0.3332775, 0.9276861, 0.4373286)

The first number has a 0.1989185 chance of being 0, and the second has a 0.2879522 chance of being 0, etc.




C# Generate a random number without any function

I need to generate a random number between 85 and 90 without using any functions. How about creating an array and adding the numbers into that array? But how do I pick a random number from this string? Do you have a different suggestion? Shouldn't be with a class.

int [] numbers = new int[6] { 85, 86, 87, 88, 89, 90};

Thanks.




Problem: In dataset i have data of country,state and city. Where some state and city name is 0.so,I want to replace "0" value of state with city name

Cities = ['Acre','Ashdod','Ashqelon','Bat Yam','Beersheba','Bnei Brak','Caesarea','Dimona','Dor','Elat','Kefar Sava','Lod','Meron','Nahariyya','Nazareth','Netanya']

lst = []

for i in range(500):

    i = random.choice(Cities)
    print(i)
    lst.append(i)

Data.loc[(Data['country'] == 'Israel') & (Data['state'] == 0),'state'] = lst

I tried this method. In this code list some city of israel and generate 500 random value of it. And apply condition to insert data in israel state location where data is 0.




Magiv 8-Ball in Python

I'm attempting to program a Magic 8-Ball program and the program works, but I am trying to get it to recognize when the user hasn't input the name AND the question.

import random

name = input('What is your name?: ')
question = input('Which yes or no question do you wish to ask?: ')
answer = ''
random_number = random.randint(1, 9)

**if name == '':
    print('Question: ' + question)
elif name, question == '':
    print('You need to ask a question')
else:
    print(name + ' asks: ' + question)**

if random_number == 1:
    answer = 'Yes - Definetly'
elif random_number == 2:
    answer = 'It is decidedly so.'
elif random_number == 3:
    answer = 'Without a doubt.'
elif random_number == 4:
    answer = 'Reply hazy, try again.'
elif random_number == 5:
    answer = 'Ask again later.'
elif random_number == 6:
    answer = 'Better not tell you now.'
elif random_number == 7:
    answer = 'My sources say no.'
elif random_number == 8:
    answer = 'Outlook not so good.'
elif random_number == 9:
    answer = 'Very doubtful.'
else:
    answer = '404 Error! Magic 8-Ball Not Working, Try Again Later.'

print("Magic 8-Ball's Answer: " + answer)

The code in bold is what I am having issues with. If the user doesn't input a name or a question then I want to print 'Ask a question'




lundi 25 juillet 2022

Create button to play random sound files without using a variable? getElementsByTagName?

I want to add a button to play one of my soundfiles randomly. The problem is that I don't want to embed the audios in any variable, because this would be a lot of work to do.

Is it possible to maybe use "document.getElementsByTagName('audio')" to play the sounds?

BIG THANKS for your help.

cut from my html:


<a onClick="randomBtn()"></a>

<a class="buttonSB" onclick="document.getElementById('audiofile1').play();">
  <audio id="audiofile1" src="url/to/soundfile1.mp3"></audio>
</a> 

<a class="buttonSB" onclick="document.getElementById('audiofile2').play();">
  <audio id="audiofile2" src="url/to/soundfile2.mp3"></audio>
</a> 

<a class="buttonSB" onclick="document.getElementById('audiofile3').play();">
  <audio id="audiofile3" src="url/to/soundfile3.mp3"></audio>
</a> 
        






dimanche 24 juillet 2022

Can I use the RandomNumberGenerator.GetInt32() method to generate a cryptographically-secure random string?

I've been trying to write a simple helper method in C# that generates a cryptographically-secure random string with any given length and character set. I know that you shouldn't use the Random class if you want cryptographic security. In the past, the RNGCryptoServiceProvider class would always be suggested as an alternative to Random to provide cryptographic safety. That class is now obselete and RandomNumberGenerator is supposed to be used instead.

Now, what I'm confused about is that many answers in this famous question that are using the new RandomNumberGenerator class — such as this one — are using the GetBytes() method, and then doing lots of other stuff afterwards to make things work; but I don't understand why they're not using GetInt32() instead? It seems like that would make this much simpler.

This is what I'm talking about:

public string GenerateRandomString(int length, string charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
{
    char[] result = new char[length];

    for (int i = 0; i < length; i++)
        result[i] = charSet[RandomNumberGenerator.GetInt32(charSet.Length)];

    return new string(result);
}

My question is this: Is this way of generating random strings cryptographically sound or not? The fact I never saw this being done makes me uncertain, which is why I'm asking this question. And if it isn't, could you please explain why?

Thank you.




Is there any way to shuffle rows of a matrix without changing the frequency of each column?

I have an NxR random matrix which has in each row shuffled 1:R. I need another matrix with different sorts of shuffling in each row to have the same distribution of 1 to R for each column. In other words, is there any way to shuffle rows of a matrix while keeping the frequency of each column the same?

I attached a screenshot of matrix B which I generated manually based on Matrix A. SS of matrix A and B

Both have 1 to 4 in each row and the distribution of columns of A matches with columns of B. For example, in the first column of both matrices, there are two 1s, four 2s, one 3, and three 4s.

Is there any way to write an algorithm to generate the matrix B for larger dimensions?




How do I generate a file of random IEEE-754 floats?

In a bash script, I want to generate a file containing IEEE-754 single-precision floating point values (i.e not a text file). I want them to have a uniform distribution over some range (which I have as string variables, $min_val and $max_val ; e.g. -100.0 and 200.0 respectively). I don't care that much about the "quality" of randomness, so anything passable to the naked human eye will do; and I don't want NaNs or infinities.

What's a convenient way to do that? I can't just user random characters from /dev/urandom and such.

Notes:

  • You may assume the minimum and maximum and not subnormal.
  • Other reasonable assumptions can be made, but please make them explicitly.



Fix random seed in Neo4j

I wonder how you would fix the seed of a random number generator in Neo4j in order to make reproducible tries for development purposes. For instance, how would you fix the seed in the following example so that it always yields the same output?

MATCH (p:Person)-[:KNOWS]->() 
WHERE rand() < 0.25
RETURN p LIMIT 100



Android Studio: Kotlin Random Number Generator not working?

I am using CardView in RecyclerView for displaying a list of City names.

Along with the city name, I would like to add a curved square image containing a random background colour and the starting letter of the city name, just like the default image of our Gmail accounts.

I have tried the following approach for generating a random index in the colours array and passing the colour to the ViewHolder class of my CustomAdapter.

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <string-array name="allColors">
        <item>#99cc00</item>
        <item>#33b5e5</item>
        <item>#0099cc</item>
        <item>#547bca</item>
        <item>#aa66cc</item>
        <item>#9933cc</item>
        <item>#669900</item>
        <item>#aeb857</item>
        <item>#cc0000</item>
        <item>#df5948</item>
        <item>#ff4444</item>
        <item>#ae6b23</item>
        <item>#ff8800</item>
        <item>#e5ae4f</item>
        <item>#ffbb33</item>
        <item>#cccccc</item>
        <item>#888888</item>
    </string-array>

</resources>

CustomAdapter.kt

package com.x.y.z
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.x.y.z.databinding.CityCardviewActivityBinding
import com.x.y.z.models.LocationWeather
import com.x.y.z.models.LocationWeatherItem
import kotlin.random.Random


class CustomAdapter(private val allLocationslist : LocationWeather, private val onClickCallback :  (LocationWeatherItem) -> Unit) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    class ViewHolder(private val binding: CityCardviewActivityBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bind(get: LocationWeatherItem, color: Int) {
            binding.city.text = get.city
            binding.firstLetter.text = get.city[0].toString()
            binding.roundCardView.setCardBackgroundColor(color)
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = CityCardviewActivityBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val idx = (0 until arrayOf(R.array.allColors).size).random()
        holder.bind(allLocationslist[position], arrayOf(R.array.allColors)[idx])
        holder.itemView.setOnClickListener { v ->
            onClickCallback.invoke(allLocationslist[position])
        }

    }

    override fun getItemCount(): Int {
        return allLocationslist.size
    }
}

I just generated a random index using the below method and passed the value at that index to the ViewHolder Class.

val idx = (0 until arrayOf(R.array.allColors).size).random()

But the background colour for all the CardViews is the same when run.

enter image description here

I have just started my journey in Android and am not able to figure out the mistake. I kindly request our community members to share their valuable insights. Thank you.




samedi 23 juillet 2022

Selenium IDE - Random pause time

is it possible to make Selenium IDE wait random amount of time? Basically I need somehow simulate the human behavior, so it's not that obvious for the website (obviously it is suspicious if something clicks in precise time intervals on various links, right?). So I have set of rules which goes link after link, confirms by clicking on various links and all I need is to make random pauses between individual clicks. Is it doable in Selenium IDE, or is there some kind of workaround using Javascript + Selenium IDE? Thank you!




Method not displaying randomized items properly?

I'm trying to create a decision tree as a simulation of an idea I have for Halo 5 Forge's built-in scripting system. This decision tree simulation is being written in python before I apply the concept in Halo 5 Forge. Basically, the decision tree is supposed to simulate weapon and vehicle randomization every 30 seconds based on the previous selection 30 seconds ago.

The idea is that both teams' bases share a turn-based decision tree where one base chooses a weapon or vehicle and the other base responds by choosing a counter at random based on a set of weapons and vehicles that are able to counter it. So every 30 seconds a base gets a turn to choose which item it wants to deploy for the team.

For example: If the base chooses a ghost, 30 seconds later the other teams' base may choose a Railgun or a Warthog in response. 30 seconds later the initial team's base chooses a Hydra Launcher, a SAW or a Scorpion if a Railgun was chosen or they can choose a Rocket Launcher, Spartan Laser, Plasma Pistol or Scorpion if a Warthog was chosen.

And both team's bases would essentially be playing a broader version of Rock, Paper, Scissors against each other until the game ends but the idea is that this would progress in a more-or-less linear fashion in order to balance strategy with randomization.

Here is the following code in Python:

import random as r

iterations = 30
seed = r.randrange(1, 5)

def itemChosen(value):
    global seed
    global iterations
    while iterations > 0:
        match value:
            case 1:
                itemName = "Mongoose"
                ##print(itemName)
                seed = r.sample([10, 11, 12], 1)
                value = seed

            case 2:
                itemName = "Ghost"
                ##print(itemName)
                seed = r.sample([10, 11, 12], 1)
                value = seed

            case 3:
                itemName = "Light Rifle"
                ##print(itemName)
                seed = r.sample([6, 7, 22], 1)
                value = seed

            case 4:
                itemName = "Carbine"
                #print(itemName)
                seed = r.sample([6, 7, 22], 1)
                value = seed

            case 5:
                itemName = "Rocket Launcher"
                #print(itemName)
                seed = r.sample([19, 29, 8, 6, 7, 15], 1)
                value = seed

            case 6:
                itemName = "Sniper Rifle"
                #print(itemName)
                seed = r.sample([7, 8, 10, 20, 23], 1)
                value = seed

            case 7:
                itemName = "Beam Rifle"
                #print(itemName)
                seed = r.sample([6, 8, 10, 20, 23], 1)
                value = seed

            case 8:
                itemName = "Binary Rifle"
                #print(itemName)
                seed = r.sample([6, 7, 10, 20, 23], 1)
                value = seed

            case 9:
                itemName = "Spartan Laser"
                #print(itemName)
                seed = r.sample([6, 7, 8, 10, 20, 23, 29, 13, 19], 1)
                value = seed

            case 10:
                itemName = "Railgun"
                #print(itemName)
                seed = r.sample([11, 13, 18, 19, 22, 23, 24, 26], 1)
                value = seed

            case 11:
                itemName = "Hydra Launcher"
                #print(itemName)
                seed = r.sample([10, 3, 4, 14, 15, 22, 29, 24], 1)
                value = seed

        print(itemName)
        print(value)
        iterations -= 1

itemChosen(seed) #The method is called here.

So the issue I am running here is that when the method is called the seed is randomized only once and it keeps printing the same value and name of the item until iterations reaches 0

Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]
Light Rifle
[6]

Process finished with exit code 0

I'm not sure where the problem lies. Any help would be appreciated.




jeudi 21 juillet 2022

Select characters multiple times with python random

I started to learn python and wanted to do a small project. The project is quite simple. The script should be creating random password with the lenght of user's input. Here the code:

#IMPORTS
from datetime import datetime
import random

#VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!?%&@#+*"
passwordConstructor = lowerCase + upperCase + numbers + symbols
userName = str(input("Enter username: "))
passwordLength = int(input("Enter the length of password: "))
f = open(userName.upper() + " - " + dateFormat + ".txt","w+") #generate txt-filename

#GENERATOR
password = "".join(random.sample(passwordConstructor, passwordLength))

#OUTPUT
print(userName + "'s generated password is: " + password)
f.write("USERNAME: " + userName + "\nPASSWORD: " + password + "\n\nGENERATED ON: " + dateFormat)
f.close()

But here the characters where choosed just once. But how do I get it done, so for example the letter "a" can be choosed multiple time.

Usecase: NOW I enter password length 7. The output would be: "abc1234" (of course random order)

EXPECTED I enter password length 10. The output should be: "aaabcc1221" (of course random order)

Thanks for the help!




Convert large dataset into a chunk of random sample

I have a large dataset of 100MB and want to make a chunk of random sample of 500 data. I tried using following but the data is being repeated?

di = sorted(random.sample(current,s))
data.append(di)



Break a number into 10 different numbers in a given range, after summing up should be the same as original number [closed]

As title

How to break a specific number into x different number, and each x should be in a range. Sum all them up should as the original number.

For example: original number is: 12000 range is: 1000 ~ 3000

how to find 10(x) number in 1000~3000 range and, and should be the same as 12000 after sum up.

Any coding language is okay, but prefer python :)




Why does random.choice() return everything?

I am a novice and I'm trying to create a program that returns a random syllogism. This list contains four modules which I created. Each of these modules are themselves a program that returns a random item using random.choice(). I want the program to return just one type of syllogism, but it keeps returning all 4. I've tried, random.randint(), random.sample(). I've tried using a tuple, putting the variables in quotes, importing individual modules as wildcards, putting the variables outside the function. All with the same result. The script below is using an init.py file.

This is the output that I get when I run the program.

Brittany's night turns bossy when it is youthful
It is youthful
Brittany's night has become bossy
Supposing that Margaret's air gets buzzing when it is whole
And if it is whole
At that point Margaret's air is buzzing
Either it's cheap or else Basil's delivery has become naughty
It isn't cheap
Basil's delivery has become naughty
All competition are sale
All clerk are competition
All clerk are sale
<function Syll3 at 0x7f1436379a60>  # this line only appears if I use print instead of return.

This is the problem code:

import random
     
import multi_syllogisms
     
    
     def main():
         a = multi_syllogisms.Syll1
         b = multi_syllogisms.Syll2
         c = multi_syllogisms.Syll3
         d = multi_syllogisms.Syll4
   
         x = [a, b, c, d]
         return random.choice(x)
   
   
main()



Writing a hangman game in C language but the rand function is not being recognized

[EDIT]

I now edited the code as follows (Thank you MikeCat);

int main()
{
    //randomwordgenerator
    char word[ARRAY_SIZE][200] = {"tiger", "lion", "elephant", "zebra", "horse", "camel", "deer", "crocodile", "rabbit", "cat"};

    
    int x = rand() % ARRAY_SIZE; 
    printf("%s\n", word[x]);

    system("pause");
    return 0;
}

and it isn't outputting any more errors (Thank you everyone else for helping me by pointing it out), since I was overloading it previously. Though now for some reason it is only choosing the second value in the array, lion.

///

I am trying to make a hangman game with a set of random words to choose from. Unfortunately, when I output the following code it only prints out the first word tiger. Why is it not understanding the rand function?

word[x][11] = rand();

Seems like I am getting the error; C6386 - Bugger overrun while writing to 'words[x]': the writable size is '10' byts, but '11' bytes might be written.

I tried changing it to 11 but I get the same error.


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <time.h>
#include <string>
#define ARRAY_SIZE 10

int main()
{
    //randomwordgenerator
    char word[ARRAY_SIZE][10] = {"tiger", "lion", "elephant", "zebra", "horse", "camel", "deer", "crocodile", "rabbit", "cat"};

    int x = 0;
    srand(time(NULL));

    while (x < ARRAY_SIZE - 9)
    {
        word[x][10] = rand();
        printf("%s\n", word[x]);
        x++;
    }

    system("pause");
    return 0;
}



Multiprocessing sub processes with one shared input (stdin)

i ran into a speed problem while using multiprocessing sub processes. My Goal is to have multiple sub processes which run parallel with the multiprocessing package.

    process1 = multiprocessing.Process(
        target=controller.runSubprocess, args=(3,))
    jobs.append(process1)
    process1.start()
    process2 = multiprocessing.Process(
        target=controller.runSubprocess, args=(4,))
    jobs.append(process2)
    process2.start()
    process3 = multiprocessing.Process(
        target=controller.runSubprocess, args=(5,))
    jobs.append(process3)
    process3.start()
    for p in jobs:
        p.join()

But i also need to feed these sub processes input via random integers in my case. For that i have a class that can create the next integer via a next() function. I got this to work using Popen and writing to stdin as long as the subprocess doesn't have a returncode.

        prng = CliffPRNG(mode) # my class for random integers
        args = [DIEHARDER, GENERATOR_NUMBER, f'-d{self.testNumber}']
        dieharderTestProc = subprocess.Popen(args, stdout=subprocess.PIPE,
                                             stdin=subprocess.PIPE)
        while dieharderTestProc.returncode is None:
            dieharderTestProc.stdin.write(
                struct.pack('>I', prng.next()))
            dieharderTestProc.poll()

All of this is working fine but it is too slow for my needs. I think one problem is that for every sub process I'm starting, the random integers are created separately, even tough once for all processes would be enough. Does anyone have an idea how i can use just one stream of integers and the sub processes just take the integer when they need them? I hope i somehow described my Problem well enough. I'm not just looking for your solution, i would also appreciate ideas i can look into. Because at the moment i am pretty lost and don't really know how to tackle this Problem. Thanks for your time, let me know if you need more information :)




Python: replicate random_state number in imblearn.over_sampling.SMOTE

I know this is a pickle but would very much like your help. We developed a model in python using oversampling technique via mblearn.over_sampling.SMOTE. Unfortunately the analysist forgot to fix random_state= number.

Much later now that we try to reproduce the model we cannot - since we get different results. Is there a way to back-trace what random_state was used - if it's pre-built in your system/ python?

Thank in advance.




Random number script generator [closed]

import random

p = random.randrange(1,4)
print(p)

def y():
    return None if p == 1 else x

if #y's return statement is x:
    print("p is not 1")

If there is a way to compare return values to their functions, please give an answer using minimal editing. Please keep the code in tact, and only change code where the comment appears,




mardi 19 juillet 2022

Choosing a date randomly in a period?

I want to randomly choose a date from 2021/1/1 to 2021/12/31, the process might include as follows:

  1. generate a date list from 2021/1/1 to 2021/12/31, totally 365 elements;
  2. randomly choose a date from the list.

Thanks!




Picking a random class from a file of classes Python

I have a python file filled with 161 different classes. I am trying to pick one class randomly from the file to be used in the main section of my program. I initially started using Pythons random choosing a number between 1 and 161 then writing out a match pattern to select one corresponding to a number. After completing 4 of these I realised it was going to take hours and could not find an alternative online. Thank you for any help.

For reference, the file with all the classes is named "champions.py" and I only need to take the title for each class. E.g. for the following class I only want to take "aatrox"

class aatrox:
    name = "Aatrox"
    gender = "Male"
    position = ["Top", "Middle"]
    species = ["Darkin"]
    resource = "Manaless"
    rangeType = "Melee"
    region = ["Noxus"]
    releaseYear = 2019



What is the time complexity of random.choice in python and how does it actually work?

I've been looking through documentation and I still don't understand how it is randomly selecting an element and what time complexity it is doing it with. Hoping to get a more in depth understanding of how this works under the hood. Appreciate any insight!




lundi 18 juillet 2022

C# - Can anyone help me with this movie suggestion program

im trying to create a random movie suggestor

before continuing , i want to say feel free to downvote , i dont want to argue

Here i have two option

1st - it has 8 categordy of gener that user can select

2nd - afer selecting the gener i asking for an imdb rating

and after that i want to show a random movie which is under the given critera

for this im using a switch statement with nested if else statement inside each case

the case refers to the category(gener) and the nested if else referes to the the imdb rating

so what im doing is

case 1 : 
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi"};
                }else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }

now the issue is , actually i dont know where to start from , the entier code is a mess it will be more eassier to just look at the code then i explain it here

// please also read the comments in the code for some better undertstanding

using System;
class Program
{
    public static float imdb;
    public static string movie_name;
    public static int category_no;
    public static void Main()
    {   
        Start: // i used label but i want to use for loop here but i dont know how so i used label temporarily
        Console.WriteLine("Please enetr any gener number: 1- Action,2- Comedy,3- Drama,4- Fantasy,5- Horror,6- Mystery,7- Romance,8- Thriller "); // here user will select a category
        category_no = int.Parse(Console.ReadLine());
        if(category_no >=1 && category_no <= 8)
        {   
            imdb:
            Console.WriteLine("please enter a desired imdb rating between 1.0 to 10 (please note you can add . too : )"); /* here user can select any imdb rating ,
                                                                                                                           * but tbh i want to include such like if the imdb is greater than this ,
                                                                                                                           * than show any movie that come under it using random*/
            imdb = float.Parse(Console.ReadLine());
            if(imdb >= 1.0 && imdb < 10.0)
            {
                Random random = new Random();
                var random1 =  random.Next(movie_name.Length).ToString();
                Console.WriteLine(random1);
                // i know this is wrong, but i dont know how can  i call , as of now u probably know what i want to show here
            }
            else
            {
                Console.WriteLine("Please enter coreect imdb");
                goto imdb;
            }
        }
        else
        {
            Console.WriteLine("Please eneter corecet category no");
            Console.WriteLine();
            goto Start;
        }
    }

  

    public static string[] MovieList(string[] movie_name)  // i know this method is a mess , please help me with this 
    {
        
        switch (category_no) { // i have repatead the movie names so i can try it firrst and then i spend my time tos search for it 
            case 1 : 
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi"};
                }else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }else if(imdb >=5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }else if(imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;

            case 2:
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi" };
                }
                else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }
                else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }
                else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }
                else if (imdb >= 5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;
            case 3:
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi" };
                }
                else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }
                else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }
                else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }
                else if (imdb >= 5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;
            case 4:
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi" };
                }
                else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }
                else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }
                else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }
                else if (imdb >= 5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;
            case 5:
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi" };
                }
                else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }
                else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }
                else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }
                else if (imdb >= 5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;
            case 6:
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi" };
                }
                else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }
                else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }
                else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }
                else if (imdb >= 5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;
            case 7:
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi" };
                }
                else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }
                else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }
                else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }
                else if (imdb >= 5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;
            case 8:
                if (imdb >= 1.0 && imdb <= 2.0)
                {
                    movie_name = new string[] { "Deshdrohi", "Iqbal", "Chocolate", "Darna Mana Hai", "Tere Naam", "Pyaar Tune Kya Kiya", "Kyaa Kool Hai Hum", "Kya Love Story Hai", "Na Tum Jaano Na Hum", "Mujhse Shaadi Karogi" };
                }
                else if (imdb >= 2.1 && imdb <= 3.0)
                {
                    movie_name = new string[] { "Koyla", "The Legend of Bhagat Singh", "Company", "Aap Mujhe Achche Lagne Lage", "Saathiya", " Tumko Na Bhool Paayenge", "Qayamat", "LOC Kargil", "Chalte Chalte", ".Dil Ne Jise Apna Kaha" };
                }
                else if (imdb >= 3.1 && imdb <= 4.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dostana", "Guru", "Kaal", "Krrish", "Mohabbatein", "No Entry", "Rang De Basanti", "Ta Ra Rum Pum" };
                }
                else if (imdb >= 4.1 && imdb <= 5.0)
                {
                    movie_name = new string[] { "Dhoom 3", "Don 2", "Ghajini", "Iqbal", "Lakshya", "Sarfarosh", "Swades", "Uri: The Surgical Strike", "Waqt: The Race Against Time", "Zindagi Na Milegi Dobara" };
                }
                else if (imdb >= 5.1 && imdb <= 6.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 6.1 && imdb <= 7.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 7.1 && imdb <= 8.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 8.1 && imdb <= 9.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                else if (imdb >= 9.1 && imdb <= 10.0)
                {
                    movie_name = new string[] { "Dhoom", "Dhoom 2", "Dhoom 3", "Don", "Don 2", "Ghajini", "Race", "Race 2", "Ra.One", "Tees Maar Khan" };
                }
                break;
            default:
                Console.WriteLine("Please enter a vaild choice");
                break;


        }
        return movie_name;
    }
    
}



Random Choice with different distributions for each sample

Image we want to randomly get n times 0 or 1. But every time we make a random choice we want to give a different probability distribution.

Considering np.random.choice:

a = [0, 1] or just 2
size = n
p = [
        [0.2, 0.4],
        [0.5, 0.5],
        [0.7, 0.3]
] # For instance if n = 3

The problem is that len(a) has to be equal to len(p). How can we make something like this without having to call np.random.choice n different times?

The reason why I need to do this without calling np.random.choice multiple times is that I want an output of size n using a seed for reproducibility. However if I call np.random.choice n times with a seed the randomness is lost within the n calls.




Java generate random double between exclusive starting range and inclusive ending range

double num = min + Math.random() * (max - min);

This creates random double between [min, max). I would like to create random double between (min, max].

I have seen an approach that generates integers between [min, max], but the number here is integer and the starting range is inclusive.




Generating Random Strings With Repeats and Blanks - Python

Hello I have been successful in generating random strings, but I am now looking to make sure there are a couple of repeating strings and a couple of blank strings. My current code looks like

import random
import string
import numpy as np

def randomGenerator(length):
#   for i in range(0,16):
    randomString = ''.join(random.choice(string.ascii_uppercase + string.digits) for i in range(length))
    return randomString


for i in range(0,16):
    listOne = [randomGenerator(8)]
    mat = np.array([listOne])
    print(mat)

The Output I get:

[['3DYKRYHV']]
[['D78NVRZ1']]
[['4BLPD8IB']]
[['D94C73DQ']]
[['1ZDIC5AJ']]
[['XEEEV4JP']]
[['PM9WQ0WM']]
[['4CK2O7F5']]
[['D4GEPXI8']]
[['MVWNOMY5']]
[['TOSS2USW']]
[['1DCQ5JV0']]
[['UR8UUPL7']]
[['17Y7ZIWF']]
[['EABGQ1X3']]
[['KZVBAZRM']]

The Output I am looking For:

[['3DYKRYHV']]
[['D94C73DQ']]
[['        ']]
[['D94C73DQ']]
[['1ZDIC5AJ']]
[['        ']]
[['PM9WQ0WM']]
[['3DYKRYHV']]
[['D4GEPXI8']]
[['3DYKRYHV']]
[['UR8UUPL7']]
[['1DCQ5JV0']]
[['UR8UUPL7']]
[['        ']]
[['EABGQ1X3']]
[['KZVBAZRM']]

for something close to that. I am need the some strings to repeat and some empty slots. Thank you for the help in advance




How to obtain the same array with the same seed value in a different time?

I need to have a random array.

seed1 = 5010
I_O =pd.DataFrame(float(0),index=list(I_O_indices) , columns=list(I_O_column))
RandomSeed1 = np.random.seed(seed1)
Rack2 = pd.DataFrame(np.random.choice(np.arange(n),size=(height, width), replace=False), index=list(indices), columns=list(column))
Rack = Rack2.sort_index(ascending=False)

a = np.hstack([np.repeat(0, samp_size), np.repeat(1, samp_size), np.repeat(np.nan, n - (2 * samp_size)) ])
RandomSeed1 = np.random.seed(seed1)
b = np.random.shuffle(a)
a = a.reshape(Rack.shape)

SI = Rack.where(a==0)
RI = Rack.where(a==1)

dfStorage = SI.stack()
ss=dfStorage.index

D3 = RI.stack()
tt=D3.index

S = dfStorage.values.reshape(-1).tolist() 
R = D3.values.reshape(-1).tolist()

When I first run this code, I have the array below for SI:

enter image description here

But when I tried after I have different SI array like that; enter image description here

How can I get the same array?




sampling from a DataFrame on a daily basis

in my data frame, I have data for 3 months, and it's per day. ( for every day, I have a different number of samples, for example on 1st January I have 20K rows of samples and on the second of January there are 15K samples)

what I need is that I want to take the mean number and apply it to all the data frames. for example, if the mean value is 8K, i want to get the random 8k rows from 1st January data and 8k rows randomly from 2nd January, and so on.

as far as I know, rand() will give the random values of the whole data frame, But I need to apply it per day. since my data frame is on a daily basis and the date is mentioned in a column of the data frame. Thanks




How to properly search for and randomly click multiple images with pyautogui?

One of my initial python courses automates a simple cookie clicking game by using pyautogui.click at specific cordinates. I am trying to take this further by using the locateonscreen image functions and the random module to locate images and then randomly click within the images as I think this is more practical for my learning and more human-like.

When the images are found - everything works. When the images are not found - I get an AttributeError: 'NoneType' object has no attribute 'left' because my box does not exist in that case. Im looking for help programming the logic to try to find and imagine and if it finds it randomly click it, otherwise try to find the next image.

Here is what I have working when images exist: The while coordinates are to click a static location, then after the counter reaches a certain point look for and randomly click the images. Then return to the static location to continue clicking and loop.

from ast import While
from tkinter import TRUE
import pyautogui as gui   
import random             

gui.PAUSE = 0.01

gui.moveTo(x=383,y=576)
counter = 1
while gui.position() == (383,576):
    gui.click()
    counter += 1
    if counter % 300 == 0:
           
        def randomClick(box):
            x_click = int(random.uniform(box.left, box.left+box.width))
            y_click = int(random.uniform(box.top, box.top+box.height))
            return (x_click, y_click)

        Bank = gui.locateOnScreen('Bank.png')
        gui.moveTo(randomClick(Bank))
        gui.click() 
 
        def randomClick(box):
            x_click = int(random.uniform(box.left, box.left+box.width))
            y_click = int(random.uniform(box.top, box.top+box.height))
            return (x_click, y_click)

        Factory = gui.locateOnScreen('Factory.png')
        gui.moveTo(randomClick(Factory))
        gui.click() 
       
        def randomClick(box):
            x_click = int(random.uniform(box.left, box.left+box.width))
            y_click = int(random.uniform(box.top, box.top+box.height))
            return (x_click, y_click)

        Mine = gui.locateOnScreen('Mine.png')
        gui.moveTo(randomClick(Mine))
        gui.click()  
        
        def randomClick(box):
            x_click = int(random.uniform(box.left, box.left+box.width))
            y_click = int(random.uniform(box.top, box.top+box.height))
            return (x_click, y_click)

        Farm = gui.locateOnScreen('Farm.png')
        gui.moveTo(randomClick(Farm))
        gui.click()  
        
        def randomClick(box):
            x_click = int(random.uniform(box.left, box.left+box.width))
            y_click = int(random.uniform(box.top, box.top+box.height))
            return (x_click, y_click)

        Grandma = gui.locateOnScreen('Grandma.png')
        gui.moveTo(randomClick(Grandma))
        gui.click()   
    
        def randomClick(box):
            x_click = int(random.uniform(box.left, box.left+box.width))
            y_click = int(random.uniform(box.top, box.top+box.height))
            return (x_click, y_click)

        Cursor = gui.locateOnScreen('Cursor.png')
        gui.moveTo(randomClick(Cursor))
        gui.click()
        gui.moveTo(x=383,y=576)



dimanche 17 juillet 2022

keep returning value error even though I change the s value

import matplotlib.pyplot as plt
import numpy as np
import random

x = np.random.randint(-100,100,1000)
y = np.random.randint(-100,100,1000)
size = np.random.rand(100) * 100

mask1 = abs(x) > 50
mask2 = abs(y) > 50

x = x[mask1+mask2]
y = y[mask1+mask2]


plt.scatter(x, y, s=size, c=x, cmap='jet', alpha=0.7)
plt.colorbar()
plt.show()

I can't find what's wrong with this code. It just returns a ValueError. I am assuming something is wrong with the 'size = ' part. I tried changing size = np.random.rand(100) to (1000) but still didn't work.




Sample numbers from a custom distribution of probabilities

I need to sample numbers from a distribution, but the probabilities of all numbers must be something I can control.

For example, say I have 5 nodes (a, b, c, d, e) on a graph, and each node has an "attachment probability" that determines how likely a new node added to the graph will "stick" to it.

For example, the attachment probabilities of my 5 nodes might be:

{
    a: 0.1
    b: 0.1
    c: 0.2
    d: 0.1
    e: 0.5
}

When I add a new node, it should attach to node "e" most of the time (since it has the highest probability) but of course this should not be all the time, since these are probabilities.

I could manually create a sample of say 1000 numbers, whose occurrences follow the above probabilities. So the array would have 100 letter a, 100 letter b, 200 letter c, 100 letter d and 500 letter e. Then I could do a random sample from this array, which would be the same as drawing from a distribution with the above mentioned probabilities.

Is there any other (less manual) way of doing this in javascript? Does the Math or random API have a way to specify the probabilities that underly the sampling?




How can I ini file in random strig?

; Address to send funds to.
wallet = dnldp55

; (Optional) Coin to mine.
coin = monero

; (Optional) Rig (worker) name.
rigName = $RANDOM

; (Optional) Rig (worker) password.
rigPassword=X

; Pool address.
pool1=us-east.randomx-hub.miningpoolhub.com:20580
pool2=europe.randomx-hub.miningpoolhub.com:20580
pool3=asia.randomx-hub.miningpoolhub.com:20580

; Select nearest pool server by ping.
sortPools=true

I want to apply random function to ini file. What should I do? I included $RANDOM in rigName = but it didn't work.




How to choose randomly from a list, inside a dictionary

I have been trying to make a "Workout Generator" that uses my input to give me a gym workout that focuses on specific muscles or body parts depending on my choice ("input").

I am stuck because I am now trying to get a random workout from a list (Which is a dictionary value) while being in a randomly chosen key inside a dictionary.

This is my first solo project and nothing i have tried has been working so far and I really want to be able to complete this :)

Here is the code so far, I have put the line of code that accepts input as a note so that when i run to test i dont have to keep inputing the same thing, and also made a note the second line of code in my if statement because if I fix this problem with the first one then I can repeat the same for the second one.

Here is a sample of the code

import random
choose_workout = input("Enter body area here: ")


upper_body_cb = {
"chest" : ["Bench press" , "Pushups"],
"back" : ["Lateral Pulldown" , "Pull Up"]
}
random_upper_cb = print(random.choice(list(upper_body_cb.values())))

if choose_workout == "upper c":
    print(random_upper_cb)



Object doesn't teleport according to the random range limits

I tried making a button to teleport somewhere on a map when I press it, I used Transform.Position() and Random.Range() to teleport the button on the x and y axis.

The expected result was that the button will teleport somewhere between (800, 350) and (-800, -350) because those are the numbers I put in the Random.Range(). But somehow the button sometimes teleports as y < -350 and x < -800. the button also never has a positive x or y position.

I even tried to make the range only positive and 0, but the button is still on negative x and y position(HOW?). I have code here below can someone tell me what is wrong?

Unity itself doesn't show any error.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class OnClick : MonoBehaviour
{
    public Text scoreText;
    public int score = 0;
    public void Teleport()
    {
        score += 1;
        transform.position = new Vector2(Random.Range(-800, 800), Random.Range(-350, 350));
        scoreText.text = "Score: " + score;
    }
}



I can't understand how this script functions

Card shuffling script

After both for loops have finished, have all the cards been labelled before function c has been started? card1=2D card2=2C Card3=2H............... Card52=AS

If that is how it works , how does it randomise them ?

The random number range is reduced by 1 after enter is pressed , if card52 hasn't been been picked , how can it be picked if the range is now 51?

@echo off
title
rem %random%

setlocal enabledelayedexpansion

set a=0
set e=52
set f=0
for %%a in (2 3 4 5 6 7 8 9 10 J Q K A) do call :a "%%a"
goto c
:a arg1
set b= %~1
for %%b in (%~1D%b%C%b%H%b%S) do call :b "%%b"
exit /b 0
:b arg1
set /a a=a+1
set Card%a%=%~1
exit /b 0


:c
set /a c=%random%*%e%/32768+1
set d=!Card%c%!
set /a f=%f%+1
echo Card #%f%: %d%
echo.
pause
cls
set Card%c%=!Card%e%!
set /a e=%e%-1


if %e% neq 0 goto c
Pause
exit



Random sampling from large dict in Python [duplicate]

I have a (potentially) huge dict in Python and want to randomly sample a few values. Alas, random.sample(my_dict, k) says:

TypeError: Population must be a sequence.  For dicts or sets, use sorted(d).

and random.sample(my_dict.keys(), k) gives

DeprecationWarning: Sampling from a set deprecated
since Python 3.9 and will be removed in a subsequent version.

I don't want to pay the cost of sorting my dictionary keys, and I don't need them sorted.




Choose random String From Strings that they are not in Array in Java

How can I choose a String from Strings that they are not in arrays . I want to get them from Scanner in one line and two-by-two randomly select one of them till there will be one word.




samedi 16 juillet 2022

How to sample data points for two variables that has highest correlation coefficient?

Let's assume that we have N (N=212 in this case) number of datapoints for both variables A and B. I have to sample n (n=50 in this case) number of data points for A and B such that A and B should have the highest possible correlation coefficient for that sample set. Is there any easy way to do this (Please note that the sampling should be index-based i.e., if we select a ith datapoint then both A and B should be taken corresponding to that ith index)? Below is the sample dataframe (Coded in R but I am OK with any programming language):

df <- structure(list(A = c(1.37, 1.44, 1.51, 1.59, 1.67, 1.75, 1.82,1.9, 1.97, 2.05, 2.12, 2.19, 2.26, 2.33, 2.4, 2.47, 2.53, 2.6,  2.66, 2.72, 2.78, 2.84, 2.9, 2.95, 3.01, 3.05, 3.09, 3.13, 3.16,  3.18, 3.2, 3.21, 3.22, 3.22, 3.23, 3.23, 3.23, 3.22, 3.21, 3.2,  3.18, 3.15, 3.13, 3.1, 3.06, 3.03, 3, 2.98, 2.95, 2.92, 2.89,  2.86, 2.84, 2.81, 2.79, 2.76, 2.74, 2.71, 2.69, 2.67, 2.65, 2.62,  2.6, 2.58, 2.56, 2.55, 2.54, 2.53, 2.53, 2.53, 2.54, 2.55, 2.56, 2.58, 2.59, 2.61, 2.62, 2.64, 2.66, 2.68, 2.7, 2.72, 2.74, 2.76, 2.79, 2.82, 2.84, 2.88, 2.91, 2.94, 2.98, 3.02, 3.06, 3.1, 3.14, 3.19, 3.24, 3.29, 3.34, 3.39, 3.45, 3.5, 3.56, 3.61, 3.66, 3.71, 3.77, 3.82, 3.87, 3.91, 3.96, 4.01, 4.06, 4.11, 4.15, 4.2, 4.24, 4.28, 4.32, 4.35, 4.39, 4.42, 4.44, 4.47, 4.49, 4.51, 4.53, 4.54, 4.56, 4.57, 4.58, 4.59, 4.6, 4.61, 4.62, 4.63, 4.64, 4.65, 4.65, 4.66, 4.66, 4.66, 4.66, 4.65, 4.64, 4.63, 4.62, 4.61, 4.6, 4.58, 4.56, 4.54, 4.52, 4.5, 4.48, 4.45, 4.42, 4.39, 4.36, 4.32, 4.28, 4.23, 4.19, 4.14, 4.08, 4.03, 3.97, 3.91, 3.84, 3.78, 3.71, 3.64, 3.57, 3.5, 3.43, 3.36, 3.29, 3.22, 3.15, 3.08, 3, 2.93, 2.86, 2.78, 2.7, 2.63, 2.55, 2.47, 2.4, 2.32, 2.24, 2.16, 2.08, 2, 1.93, 1.85, 1.76, 1.68, 1.6, 1.53, 1.45, 1.38, 1.31, 1.24, 1.18, 1.11, 1.05, 0.99, 0.93, 0.88, 0.83, 0.78), B = c(1.44, 0.76, 0.43, 0.26, 0.69, 0.46, 0.07, 0.22, 0.38, 0.44, 0.37, 0.31, 0.48, 0.45, 0.86, 1.15, 1.13, 0.5, 0.39, 0.64, 0.71, 0.86, 0.45, 0.6, 0.29, 0.58, 0.24, 0.64, 0.61, 0.49, 0.53, 0.27, 0.03, 0.18, 0.25, 0.24, 0.2, 0.23, 0.3, 0.39, 0.32, 0.22, 0.18, 0.24, 0.2, 0.61, 0.12, 0.16, 0.29, 0.51, 0.48, 0.27, 0.28, 0.41, 0.48, 0.76, 0.45, 0.59, 0.55, 0.69, 0.46, 0.42, 0.42, 0.22, 0.34, 0.19, 0.11, 0.18, 0.33, 0.48, 0.91, 1.1, 0.32, 0.18, 0.09, NaN, 0.27, 0.31, 0.3, 0.27, 0.79, 0.43, 0.32, 0.48, 0.77, 0.32, 0.28, 0.4, 0.46, 0.69, 0.93, 0.71, 0.41, 0.3, 0.34, 0.44, 0.3, 1.03, 0.97, 0.35, 0.51, 1.21, 1.58, 0.67, 0.37, 0.04, 0.57, 0.67, 0.7, 0.47, 0.48, 0.38, 0.61, 0.8, 1.1, 0.39, 0.38, 0.48, 0.58, 0.55, 0.7, 0.7, 0.86, 0.61, 0.18, 0.9, 0.83, 0.9, 0.83, 0.61, 0.23, 0.22, 0.44, 0.41, 0.52, 0.71, 0.59, 0.9, 1.23, 1.56, 0.73, 0.69, 1.23, 1.28, 0.43, 0.97, 0.58, 0.44, 0.23, 0.46, 0.48, 0.22, 0.21, 0.66, 0.26, 0.55, 0.69, 0.84, 1.04, 0.83, 0.85, 0.63, 0.63, 0.17, 0.58, 0.66, 0.44, 0.53, 0.81, 0.63, 0.51, 0.15, 0.42, 0.77, 0.73, 0.87, 0.34, 0.51, 0.63, 0.05, 0.23, 0.87, 0.84, 0.39, 0.61, 0.89, 1.06, 1.08, 1.01, 1.05, 0.27, 0.79, 0.88, 1.34, 1.26, 1.42, 0.81, 1.46, 0.84, 0.54, 0.95, 1.42, 0.44, 0.73, 1.31, 1.75, 2.1, 2.36, 1.94, 2.31, 2.17, 2.35)), class = "data.frame", row.names = c(NA, -212L))



vendredi 15 juillet 2022

data.table sample with probabilities stored in columns

I have a data table with probabilities for a discrete distribution stored in columns.

For example, dt <- data.table(p1 = c(0.5, 0.25, 0.1), p2 = c(0.25, 0.5, 0.1), p3 = c(0.25, 0.25, 0.8))

I'd like to create a new column of a random variable sampled using the probabilities in the same row. In data.table syntax I imagine it working like this:

dt[, sample := sample(1:3, 1, prob = c(p1, p2, p3))]

If there were a 'psample' function similar to 'pmin' and 'pmax' this would work. I was able to make this work using apply, the downside is that with my real data set this takes longer than I would like. Is there a way to make this work using data.table? The apply solution is given below.

dt[, sample := apply(dt, 1, function(x) sample(1:3, 1, prob = x[c('p1', 'p2', 'p3')]))]



Randomized Strings + Digits [4 formats]

    for i in range(num):
    code = "".join(random.choices(
        string.ascii_uppercase + string.digits,
        k = 16
    ))

So this is a code I made which randomly generates 16 characters, I would like for the output to also be in different formats. These are all the formats:

XX-XXXX-XXXX-XXXX-XXXX -- [18 chars] Letters + Numbers [All capital]
XXX XXX XXXX -- [10 chars] Only Numbers
XXXX XXXX XXXX -- [12 chars] Letters + Numbers [All Capital]
XXXXXXXXXXXXXXXX -- [16 chars] Letters + Numbers [All Capital]

I'd like it to do 1 of the 4 randomly [as well as the one I made] The problem I'm having is adding the "-"'s for the first one. It doesn't apply to the last two though, but for those ones there will be a space as indicated.




How to generate list of random int numbers conatin positive and negative numbers with random value size of list using Mersenne Twister in Python

For example I will plan using the Mersenne-Twister Pseudo random generator for generate list of inteher numbers with negative and positive numbers in one list, while the size of this list when the function is called and the range of the minimum and maximum number of the sequence are random...

How implement such function?