jeudi 31 mars 2022

Python program to get the count of happening Largest straight

Seems like my future depends on answering this question I'm completely new to Numpy can someone give me code for this question

You are rolling 5 dice at a time. When the dice come out as 1-2-3-4-5 or 2-3-4-5-6, then it is called a largest straight. Write a python program to get the count of happening largest straight when we simulates rolling five dice 10000 times.




mercredi 30 mars 2022

how can I get a random generation of yes and no?

how can I get a random generation of yes and no? and result store in dataframe column.

I want to the random generation of yes and no and store value in the column but still not successful... here is my code, it's working well but does not store the same result in the column.

import string
import random
l1 = ["yes", "no"]
for x in range(8):
    rand = random.randint(0, 1)
    print(l1[rand])



Random function not compatible with matplotlib?

import random
import matplotlib.pyplot as plt
a = 5
b = 10
c = 20
x = (print(random.randrange(a, b)))
y = (print(random.randrange(b, c)))
projectname = input('What is your project name?: ')
indep = input('What is your independent variable?: ')
dep = input('What is your dependent variable?: ')
plt.plot(x, y)
plt.xlabel(indep)
plt.ylabel(dep)
plt.title(projectname)
plt.show()

Here is the error code: "ValueError: x, y, and format string must not be None"

New to coding




I'm trying to build a dice program using C++ it isn't displaying my return [closed]

The code is printing the greeting and all the messages except the number. I need to see what is being generated by my random number generator.

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

void greeting(int pnum){
       if(pnum == 1) {
           std::cout << "Please press \"ENTER\" to roll the die"; 
       }
       else {
            std::cout << "Please press \"ENTER\" to roll the die AGAIN"; 
       }
        std::cin.ignore();
}

int dieroll(void){
    int ran;
    srand(time(NULL));
    ran = rand()%6+1;
    std::cout << "You have rolled :" << std::endl;
    return ran;
}

int main(void){
    int counter, firstdie, ran;
    char firststart;

    do {
        greeting(1);
        firstdie = dieroll();
    }
 
    while (ran > 0);
    {
        return ran;
    }
    
    std::cin.ignore();
    return 0;
}

I'm a beginner so i'm unsure where to start trouble shooting. I'm looking into making local variables.




How to get a random background from a list

I created this code 3 different ways.

Are any of these the preferred ways in how the code should be written?

Are any of these good?

Maybe one of these could be modified or adjusted.

I was told different things on how the code should be made.

How it works is, after a page is loaded, only 1 background is selected from a group of backgrounds.

Clicking Run Code snippet produces a new background image.

Code 1 https://jsfiddle.net/0hcgkurm/

(function randomBackground() {

  const linearGradients = [
    "linear-gradient(to right, #c6ffdd, #fbd786, #f7797d)",
    "linear-gradient(to right, #6a3093, #a044ff)",
    "linear-gradient(to right, #a8ff78, #78ffd6)",
    "linear-gradient(to right, #6d6027, #d3cbb8)",
    "linear-gradient(to right, #4da0b0, #d39d38)",
    "linear-gradient(to right, #74ebd5, #acb6e5)",
    "linear-gradient(to right, #12c2e9, #c471ed, #f64f59)",
    "linear-gradient(to right, #4b79a1, #283e51)",
    "linear-gradient(to right, #0099f7, #f11712)"
  ];

  const randomColor =
    linearGradients[Math.floor(Math.random() * linearGradients.length)];
  document.querySelector("body").style.setProperty("--bg-color", randomColor);
}());
:root {
  --bg-color: linear-gradient();
}

body {
  background: var(--bg-color, white);
  background-repeat: no-repeat;
  min-height: 100vh;
  overflow: hidden;
}

Code 2 https://jsfiddle.net/f7qopgwL/

(function randomBackground() {
  const varNames = [
    "color-a",
    "color-b",
    "color-c"
  ];

  const random = Math.floor(Math.random() * varNames.length);
  document.body.style.backgroundImage = 'var(--' + varNames[random] + ')';
}());
:root {
  --color-a: linear-gradient(120deg, #155799, #159957);
  --color-b: linear-gradient(0deg, #522db8 0%, #1c7ce0 100%);
  --color-c: linear-gradient(45deg, #102eff, #d2379b);
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  background-repeat: no-repeat;
}

Code 3 https://jsfiddle.net/r9bygt3d/

(function randomBackground() {
  const classNames = [
    "bg1",
    "bg2",
    "bg3",
    "bg4",
    "bg5",
    "bg6",
    "bg7",
    "bg8",
    "bg9",
    "bg10"
  ];

  const random = Math.floor(Math.random() * classNames.length);
  document.querySelector("body").classList.add(classNames[random]);
}());
.bg1 {
  --color: linear-gradient(76.9deg, #e8bbf2, #8787fd 51.66%, #84caff 109.18%);
}

.bg2 {
  --color: linear-gradient(45deg, #102eff, #d2379b);
}

.bg3 {
  --color: radial-gradient(60% 60% at 50% 50%, rgb(40, 0, 115), rgb(0, 0, 0));
}

.bg4 {
  --color: radial-gradient(rgba(80, 0, 0, 0.1) 0%, rgba(80, 0, 0, 0.2) 30%, rgba(21, 11, 1, 0.9) 100%), linear-gradient(to right, #02111d, #037bb5, #02111d);
}

.bg5 {
  --color: radial-gradient(rgba(80, 0, 0, 0.1) 0%, rgba(80, 0, 0, 0.2) 30%, rgba(21, 11, 1, 0.9) 100%), linear-gradient(to right, #02111d, #037bb5, #02111d);

}

.bg6 {
  --color: radial-gradient(circle at 5% 13%, #0b7bd2, #3d41b4 40%, #591fa4 101%);
}

.bg7 {
  --color: linear-gradient(95deg, #67115e, #2d0546 31%, #160322);
}

.bg8 {
  --color: linear-gradient(darkviolet, navy);
}

.bg9 {
  --color: linear-gradient(120deg, rgba(255, 125, 255, 0.7), rgba(125, 85, 255, 0.7) 70%);
}

.bg10 {
  --color: linear-gradient(90deg, #10069F, #9932CC);
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  background-image: var(--color);
  background-repeat: no-repeat;
}



C: Shuffle String elements in 2d array

I am trying to shuffle the string elements in a 2d array, and I'm quite confused whether I should just shuffle the columns or all of them. Here's what I've done so far.

int main(int argc, char const *argv[]){

  char words[4][20] = {"abc", "dec", "dsz", "dfas"};
  for (int i=0;i<4;i++){
    srand(time(NULL));
    int r = rand() % 4;
    int temp = i;
    strcpy(words[i], words[r]);
    strcpy(words[r],words[temp]);
  }
  for(int j=0;j<4;j++){
    printf("Elements: %s\n",words[j]);
  };
  return 0;
}

However, this gives me a Trace/BPT trap: 5 error. Any helps would be appreciated.




Probability Random Number Generator in c# [closed]

So im trying to do a luck game and i try to find something like Crash game that generate a random number with a probability like this can up to x100 but most of the time it's ~x1 - x2 and more rarely x3 - x8.

I dev in c#.




mardi 29 mars 2022

Computing a random subset in Python - what's wrong in my code?

This code is to return a subset with size k from the set size n (EPI 5.15). That is, take n > 0, k <= n, and from n we (hypothetically) form a set {0, 1, 2, ..., n-1} from which we pick k elements to form a subset. There are nCk possibilities of picking a subset and we want it to be uniformly picked and we also want the permutation in that subset is also random. There are three versions of codes -- from official solution, my tweak, and my own solution. The latter two are WRONG but I don't know why. I will explain the gist of the algorithm right below the three codes.

Official Solution

def random_subset(n: int, k: int) -> List[int]:
    H = {}
    for i in range(k):
        r = random.randrange(i, n)
        rmap = H.get(r, r)
        imap = H.get(i, i)
        H[r] = imap
        H[i] = rmap
    return [H[i] for i in range(k)]

Change to the official solution (WRONG)

def random_subset(n: int, k: int) -> List[int]:
    H = {}
    for i in range(k):
        r = random.randrange(i, n)
        H[r] = H.get(i, i)
        H[i] = H.get(r, r)
    return [H[i] for i in range(k)]

My solution (DEAD WRONG)

def random_subset(n: int, k: int) -> List[int]:
    H = {}
    for i in range(k):
        r = random.randrange(i, n)
        if r in H:
            H[i] = H[r], i
        else:
            H[i] = r, i
    return [H[i] for i in range(k)]

Underlying Logic

We pick an element from the part of array A, <0, 1, 2, ..., n-1>, without duplicate. At first, pick r from array A and swap it with A[0]; then pick another r and swap it with A[1] ... until we have filled A[k-1], in total we have k elements, like the following code:

'''
A = <0, 1, 2, ..., n-1>
i    0  1  2       n-1
'''

def random_sampling(k, A):
    for i in range(k):
        r = random.randrange(i, len(A))
        A[i], A[r] = A[r], A[i]

A = [i for i in range(n)]
k = some_constant
random_sampling(k, A)
answer = A[:k]

To reduce space complexity from O(n) to O(k) by mimicking an array <0, 1, 2, ..., n-1>, we changed the right above code into an official solution that uses a hash table from which we select an element to be included in a subset. The problem arises in the way I use hash table differently from original answer but I don't know why.




How can I access the internal variable of a method in Java junit?

I have a function in which a random number is generated as shown below

public void method(){
     int number = random();
     // continue
}

My question is how can I access this variable without mocking random method?

I need this variable for my test scenarios.




lundi 28 mars 2022

is there a way to upper case a char from a vector in c++?

I'm trying to write a code that generates a password from a string, if user wants a 8 character pass the code takes a string with 5 letters and adds randomly 3 more chars at the end and changes randomly to upper case a letter. For example:

Input: pedro

Output: pEdRo/*+ (Symbols should be generated randomly)

But I'm getting: EEpEdro-$!

Why I'm getting EE at the beginning of the vector? I have tried to use .erase but did not work, also I always got the same chars at the end (-$!) instead of random chars. Hope you can help me :)

#include <vector>
#include <string>
#include <numeric>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main(int argc, char const *argv[])
{
    vector<char> mixed;
    int passlen;
    string input;
    string output;
    const char *specials[10] = {"/", "*", "-", "+", "%", "$", "!", "¿", "[", "}"};

    cout << "Ingrese longitud de caracteres" << endl;
    cin >> passlen;

    if (passlen == 8)
    {
        cout << "Ingrese cadena de 5 caracteres" << endl;
        cin >> input;
    }
    else
    {
        cout << "Ingrese cadena de 8 caracteres" << endl;
        cin >> input;
    }

    for (int i = 0; i <= input.length(); i++)
    {
        char toPush = input[i];
        mixed.push_back(toPush);
    }
    for (int j = 0; j <= 2; j++)
    {
        char x = *specials[(rand() % 10) - 1];
        mixed.push_back(x);
    }

    for (int k = 0; k <= 2; k++)
    {
        int element = rand() % (mixed.size() - 3);
        mixed[element] = putchar(toupper(mixed[element]));
        // mixed.erase(mixed.begin());
    }
    output = accumulate(begin(mixed), end(mixed), output);

    cout << output << endl;

    return 0;
}



Why is this code of snake, water and gun not working?

I got an exercise while learning python from this tutorial and I got an exercise of Snake, Water and Gun and did solve it but the program just takes an input and then stops. This is the code I am using:

import random
print("Welcome to Snake, Water or Gun!")

opts = ["Snake", "Water", "Gun"]
u_ch = input("Enter Snake, Water or Gun:")
c_ch = random.choice(opts)
chances = 10
ties = 0
u_score = 0
c_score = 0
while chances < 10:
    if u_ch == "Snake" and c_ch == "Snake":
        chances -= 1
        ties += 1
        print("It is a tie.")
        print(f"{chances} chances left.")

    elif u_ch == "Snake" and c_ch == "Water":
        chances -= 1
        u_score += 1
        print("Computer wins 1 point.")
        print(f"{chances} chances left.")

    elif u_ch == 'Snake'and c_ch == "Gun":
        chances -= 1
        u_score += 1
        print("You win 1 point.")
        print(f"{chances} chances left.")

    if u_ch == "Water" and c_ch == "Snake":
        chances -= 1
        c_score += 1
        print("Computer wins 1 point.")
        print(f"{chances} chances left.")

    elif c_ch == "Water":
            chances -= 1
            ties += 1
            print("It is a tie.")
            print(f"{chances} chances left.")

    if c_ch == "Gun":
            chances -= 1
            u_score += 1
            print("Player wins 1 point.")
            print(f"{chances} chances left.")

    if u_ch == "Gun":
        if c_ch == "Snake":
            chances -= 1
            u_score += 1
            print("Player wins 1 point.")
            print(f"{chances} chances left.")

        elif c_ch == "Water":
            chances -= 1
            c_score += 1
            print("Computer wins 1 point.")
            print(f"{chances} chances left.")

        elif c_ch == "Gun":
            chances -= 1
            ties += 1
            print("It is a tie.")
            print(f"{chances} chances left.")

if c_score > u_score:
    print(f"You lose!\nComputer score:{c_score}\nYour score:{u_score}\nTies:{ties}")
if u_score > c_score:
    print(f"You win!\nComputer score:{c_score}\nYour score:{u_score}\nTies:{ties}")
if c_score == u_score:
    print(f"Tie!\nComputer score:{c_score}\nYour score:{u_score}\nTies:{ties}")

I am not able to understand the problem at all.

I wanted the computer to play a full game and I used the random module also but it stops after taking an input only. This is the code:

import random
print("Welcome to Snake, Water or Gun!")

opts = ["Snake", "Water", "Gun"]
u_ch = input("Enter Snake, Water or Gun:")
c_ch = random.choice(opts)
chances = 10
ties = 0
u_score = 0
c_score = 0
while chances < 10:
    if u_ch == "Snake" and c_ch == "Snake":
        chances -= 1
        ties += 1
        print("It is a tie.")
        print(f"{chances} chances left.")

    elif u_ch == "Snake" and c_ch == "Water":
        chances -= 1
        u_score += 1
        print("Computer wins 1 point.")
        print(f"{chances} chances left.")

    elif u_ch == 'Snake'and c_ch == "Gun":
        chances -= 1
        u_score += 1
        print("You win 1 point.")
        print(f"{chances} chances left.")

    if u_ch == "Water" and c_ch == "Snake":
        chances -= 1
        c_score += 1
        print("Computer wins 1 point.")
        print(f"{chances} chances left.")

    elif c_ch == "Water":
            chances -= 1
            ties += 1
            print("It is a tie.")
            print(f"{chances} chances left.")

    if c_ch == "Gun":
            chances -= 1
            u_score += 1
            print("Player wins 1 point.")
            print(f"{chances} chances left.")

    if u_ch == "Gun":
        if c_ch == "Snake":
            chances -= 1
            u_score += 1
            print("Player wins 1 point.")
            print(f"{chances} chances left.")

        elif c_ch == "Water":
            chances -= 1
            c_score += 1
            print("Computer wins 1 point.")
            print(f"{chances} chances left.")

        elif c_ch == "Gun":
            chances -= 1
            ties += 1
            print("It is a tie.")
            print(f"{chances} chances left.")

if c_score > u_score:
    print(f"You lose!\nComputer score:{c_score}\nYour score:{u_score}\nTies:{ties}")
if u_score > c_score:
    print(f"You win!\nComputer score:{c_score}\nYour score:{u_score}\nTies:{ties}")
if c_score == u_score:
    print(f"Tie!\nComputer score:{c_score}\nYour score:{u_score}\nTies:{ties}")



I'm having an issue resetting a randomized phone number in Javascript without resetting the whole browser

//So I am brand spanking new to javascript (like, I've been dropped into the deep end for this for my intro to engineering class with only my wits and the p5.js references), so forgive me if this question is obvious to you, because it's stumping my teammate and I.//

I am making a game where you are given a randomized phone number and you have to use some numbered buttons to type in the random number to win. We have managed to get that part to work, after a bit of head scratching, but I can't seem to figure out how to get the number to reset after someone wins the game. What we're working on right now is making the win state nicer than just a bit of text saying "you win" or "you lose" with nothing else to follow. Our plan is to have a screen pop up that gives you the option to play again or go to the home screen to choose another game to play. Since I'm the one who figured out how to get the phone number to randomize, I need to figure out how to get it to reset. If you guys could help, I'd very much appreciate it.

this is what I have for my generator so far:

let number1, number2, number3, number4, number5, number6, number7, number8, number9, number0, randNum;

function getRandomInt() {
  return Math.floor(Math.random() * 10);
}

number0 = getRandomInt();
number1 = getRandomInt();
number2 = getRandomInt();
number3 = getRandomInt();
number4 = getRandomInt();
number5 = getRandomInt();
number6 = getRandomInt();
number7 = getRandomInt();
number8 = getRandomInt();
number9 = getRandomInt();
randNum = '(' + number0 + number1 + number2 + ') ' + number3 + number4 + number5 + '-' + number6 + number7 + number8 + number9;

When I had the variables to create a random number in a function, they would be randomizing constantly, and when I took them out, they were set, but now that they're outside of a function, I don't know how to get them to reset.




using a single set of random number generators in a loop

Given the code below, is it possible to modify it so that there's a single set of M "random" numbers for x and y that will "restart" at the beginning of the set for every iteration of i?

What I know I can do is pre-generate an array for x and y of length M but I cannot use arrays because of limited memory. I was thinking of using random numbers with seeds somehow but havent been able to figure it out.

Thank You!

double x = 0;
double y = 0;
double a = 0;
double f = 100e6;
double t = 0;
double fsamp = 2e9;

double sampleNormal()
{
   double u = ((double) rand() / (RAND_MAX)) * 2 - 1;
   double v = ((double) rand() / (RAND_MAX)) * 2 - 1;
   double r = u * u + v * v;
   if (r == 0 || r > 1) return sampleNormal();
   double c = sqrt(-2 * log(r) / r);
   return u * c;
}

for(int i = 0; i < N; i++)
{
    for(int j = 0; j < M; j++)
    {
        x = sampleNormal();
        y = sampleNormal();
        t = j/fsamp;

        a = x*cos(2*pi*f*t)+y*sin(2*pi*f*t);
    }
}



How can I join multiple strings in not a specified order in Python? [duplicate]

I want to join strings but randomly. If I do this:

a = 'this'
b = 'is'
c = 'a'
d = 'string'
e =  ''

f = e.join(a + b + c + d)


output : 'this is a string'

This is excatly what I don't want.

I want to get string in random order. Like this:

'string this a is'



random sampling of many groups within dataframe IF group size is greater than a value

I'm a newbie. Consider the following. For any LOC_ID that has more than 3 unique SUB_IDs, I take a random sample of 3 unique SUB_IDs to piece together a new dataframe with concatenate:

dataframe_in

df_concat = pd.DataFrame(columns=['LOC_ID', 'SUB_ID'])

for loc in test_df['LOC_ID'].unique():
    sub_ids = test_df[test_df['LOC_ID'] == loc]['SUB_ID'].unique()
    if len(sub_ids) > 3:
        np.random.seed(622)
        sub_ids_max = np.random.choice(sub_ids, size=3, replace=False)
        df_sample = test_df[test_df['SUB_ID'].isin(sub_ids_max)]
    else:
        df_sample = test_df[test_df['SUB_ID'].isin(sub_ids)]
    df_concat = pd.concat([df_concat, df_sample], ignore_index=True)

dataframe_out

The following is the real case where I also have a year component with 6 years. Each LOC_ID within locids_sub has more than 10 unique SUB_IDs in at least one year. Per LOC_ID, per year, I need to ensure that there are no more than 10 unique SUB_ID's:

max_subid = 10
years = df_bb['Year'].unique()

count_df = df_bb.groupby(['LOC_ID', 'Year']).nunique().reset_index()
locids_sub = count_df[count_df['SUB_ID'] > max_subid]['LOC_ID'].unique()

# Subset df_bb by locids_sub
df_bb_sub = df_bb[df_bb['LOC_ID'].isin(locids_sub)][['Year', 'LOC_ID', 'SUB_ID']]

df_concat = pd.DataFrame(columns=df_bb.columns)  # Initializing df

for year in years:
    for loc in locids_sub:
        sub_ids = df_bb_sub[(df_bb_sub['Year'] == year) & (df_bb_sub['LOC_ID'] == loc)]['SUB_ID'].unique()
        if len(sub_ids) > max_subid:
            np.random.seed(year+int(loc[-2:]))
            sub_ids_max = np.random.choice(sub_ids, size=max_subid, replace=False)
            df_sample = df_bb[df_bb['SUB_ID'].isin(sub_ids_max)]
        else:
            df_sample = df_bb[df_bb['SUB_ID'].isin(sub_ids)]
        df_concat = pd.concat([df_concat, df_sample], ignore_index=True)

With 6 years, 1460 LOC_IDs in locids_sub, and 1828201 rows in df_bb, this takes 30 minutes to run.
Please let me know how to make this more efficient.




Generate unique 16 digit alphanumeric based on input number in python

How would I generate unique 16 digit alphanumeric based on input number in python. Result should be the same if we run the function multiple times. for example if the input is 100 and the program returns 12345678abcdefgh and next time if the user provides same input it should return the same result 12345678abcdefgh.




I want to generate a random variable follows Weibull Distribution [closed]

I want to generate a random variable that follows Weibull Distribution. I have the mean and coefficient of variation (COV). I want to know how to generate it using either python or Matlab. Since the scale and shape are not given.




Change random value in 2D array as efficiently as possible in JavaScript

var cells = [
    [1, 2, 3, 5],
    [1, 1, 2, 3],
    [1, 1, 1, 2],
    [0, 1, 0, 1]
]

The challange is to pick one equally random 0 from cells and change it randomly to a 1 or 2.

The chance of it changing to a 1 should be 90%. The chance of a 2 10%.

cells will always be a 4x4 array.

I am wondering if there are some faster solutions (even if it is uglier) that I cannot find. Anything slighly faster is welcome as an answer!

Your solution should rather not use external libraries.




dimanche 27 mars 2022

Im trying to create a Random name generator but i get error CS1525 from Instantiating a Random? [closed]

static void Main(string[] args)
{
    var guyfirstNames = new string[]
    {
           "Noah", "Parker", "Tyler", "Isaac", "Emilo", "Hugo", "Victor", "Ruben", "Aidan",
           "Ben", "Bob", "Logan", "Antonio", "Ryder", "Anthony", "Ivan", "Calvin", "Liam", "Lucas", "Braxon",
           "Elijah", "Oliver", "William", "James", "Alan", "Brian", "Bryan", "Conner", "Carter", "Cory",
           "Damian", "Damien", "Derek", "Devin", "Donovan", "Dominik", "Drake", "Dustin", "Eric", "Erick",
           "Erik", "Gary", "Gavin", "Jared", "Jason", "Jeff", "Jeffrey", "Jeremy", "Justin", "Keith", "Kevin",
           "Kyle", "Mark", "Riley", "Matthew", "Robin", "Scott", "Arthur", "Alfred", "Carl", "Curtis", "Cyrus", "Felix",
           "Frank", "Grant", "Larry", "Leroy"
    };
    Random rBoyFirstName = new Random();
    Console.WriteLine("Congratulations you were born a One in 4 trillion chance");
}

link to code https://app.codingrooms.com/w/gLIHaTVvEkwn

As in the question name I'm trying to get a random name generator but it doesn't work because i get error CS1525 on (27,8) i tried changing The Random but it doesn't work i also tried changing the name of the Random but it doesn't work i tried indenting it differently also doesn't work please help me

Note:I am not all that good at coding so some of the things i say might not make sense like changing the Random i'm not sure if that is how you say it but i don't know any other way so sorry if it's confusing.




How do include the upper limit of `rand` in Clojure?

In Clojure's rand function, the lower limit 0 is included, but the upper limit is not. How to define a rand function equivalent which includes the upper limit?




samedi 26 mars 2022

Random effect meta regression in the package 'meta'

I want to do a random-effect multivariate meta regression model using the package 'meta' in r. However, when I used 'metareg' function, the output I got is the mixed effect models. How can I get the estimates from the random-effect model? I am very new to the meta analysis. Please help me.




How to distinguish between different Gaussian random number generators

For example I have 2 different Gaussian random number generators. The first mathematical expectation is 50 and the variance is 5. The second mathematical expectation is 60 and the variance is 5. (Actually I don't know their mathematical expectation and variance) They generate random signals at the same time. Maybe the first one produces "46 48 50 49 55 56 53 52". The second produces "60 56 59 62 66 54 59 57". I can only detect jumbled numbers right now, like "46 60", "48 56", "50 59", "49 62", "55 66", "56 54", "53 59", "52 57".

I know this problem can be easily solved by increasing the number of samples. But what I am facing now is to determine the mathematical expectation of these two different random number generators in as few samples as possible. Is there any algorithm to solve this problem, please.




how do i randomly select an element in an array?

So I've been trying to do this for an embarrassingly long time now. First of all here is my (very bad) code:

char firstInfection() {            
     char cities[] = {"aa", "bb", "cc", "dd", "ee", "ff"};            
     srand(time(NULL));            
     int randnum = rand() % 5;            
     char firstCity = cities[randnum];            
     return firstCity; 
}

I didn't include the preprocessor stuff but I'm also using string, math and time (obviously stdio and stdlib too)

Line 2 errors out here, saying: error: too many initializers for ‘char []’ I'm not really sure what's going on here.

I'm having trouble understanding some of the things I need to do. I was told on tutorialspoint that I have to initialize random with line 3: srand(time(NULL)) I'm not sure why lol.

I tried shortening the names of the elements in cities[]

I'm not really sure what else to do try. I'm guessing that the whole thing is completely wrong but I really don't know.




How to get a random item list in Firestore with Flutter and show it in a GridView

how can i get random item something mix everytime user open the app. right now i having a gridview that show item but not randomly. i just get all of the data in firestore and show it into gridview with unlimited length of item that look like this

 @override
  Widget build(BuildContext context) {
    final productProvider = Provider.of<ProductProvider>(context);
    List<Product> productsList = productProvider.products();
    return Column(
      children: [
        Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Suggestion Products',
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
                  ),
                  TextButton(
                      onPressed: () {
                        Navigator.of(context).pushNamed(
                          FeedsScreen.routeName,
                          arguments: 'popular',
                        );
                      },
                      child: const Text('view all')),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10.0),
              child: SizedBox(
                width: double.infinity,
                child: Column(
                  children: [
                    GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: productsList.length,
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              childAspectRatio: 2 / 3,
                              mainAxisSpacing: 1,
                              crossAxisSpacing: 15),
                      itemBuilder: (ctx, i) {
                        return ChangeNotifierProvider.value(
                          value: productsList[i],
                          child: const MainProduct(),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

and how can i achieve an suggestion product base on what user history search. kinda look like some o ecommerce app do. when i search for a computer in the app. in the suggestion will suggest me some related product. thanks




How Can I reset the Text value to an empty string after I've randomly generated a password with javascript

var generateBtn = document.querySelector("#generate");

// put our characters into seperate arrays
const uppercaseLetters = ['A', 'B', 'C', 'D', "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", 'Z']

const lowercaseLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

const numeric = ["0", "1", "3", "4", "5", "6", "7", "8", "9"]

const specialCharacters = ["+", "-", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^",
  "~", "*", "?", ":",
]

//create an empty password array and empty generatedPassword string
let passwordArry = [];

let generatedPassword = '';

//create variables for included types


//write a function to generate the password
function writePassword() {

  //prompt to the user how many characters they want
  let passwordLength = window.prompt(`How many characters? enter between 8 & 128`);

  //if user doesnt enter a password or the input is nan
  while (!passwordLength || isNaN(passwordLength)) {
    window.alert(`this field cannot be empty & has to be an integer`);
    passwordLength = window.prompt(`How many characters? enter between 8 & 128`);
  }

  //if password length is les than 8 or more than 128, reprompt
  if (passwordLength < 8 || passwordLength > 128) {
    window.alert(`Password must be between 8 & 128 characters`);
    passwordLength = window.prompt(`How many characters? enter between 8 & 128`);
  }

  let includeUppercase;
  let includeLowercase;
  let includeNumeric;
  let includeSpecialCharacter

  //alert the user to input on every prompt

  while (!includeNumeric && !includeSpecialCharacter && !includeLowercase && !includeUppercase) {
    alert("check all")
    includeNumeric = prompt("Should include numeric character, enter yes or no").toLowerCase()
    includeSpecialCharacter = prompt("Should include special character,enter yes or no").toLowerCase()
    includeLowercase = prompt("Should include lowercase character,enter yes or no").toLowerCase()
    includeUppercase = prompt("Should include uppercase character,enter yes or no").toLowerCase()
  }

  //if user selects to include any of these characters by entering yes then we will put those characters into an array, if the users enter anything else then the program will do nothing and go to the next prompt

  if (includeNumeric === "yes") {
    passwordArry = passwordArry.concat(numeric)

  }
  if (includeLowercase === "yes") {
    passwordArry = passwordArry.concat(lowercaseLetters)

  }
  if (includeUppercase === "yes") {
    passwordArry = passwordArry.concat(uppercaseLetters)

  }
  if (includeSpecialCharacter === "yes") {
    passwordArry = passwordArry.concat(specialCharacters)

  }

  // now that we have added the types to the password array, we now loop through the array to grab random characters
  // generates a random password from the entered password length
  for (let i = 0; i < passwordLength; i++) {
    //create a variable to hold the random number , we multiply the random number by the length of the whole password array
    const randomLength = Math.floor(Math.random() * passwordArry.length)
    //the random length is a number and we use that number for the index of the password array
    generatedPassword = generatedPassword + passwordArry[randomLength];

    let passwordText = document.querySelector("#password");

    passwordText.value = generatedPassword;

  }


}

generateBtn.addEventListener('click', writePassword);
<div class="wrapper">
  <header>
    <h1>Password Generator</h1>
  </header>
  <div class="card">
    <div class="card-header">
      <h2>Generate a Password</h2>
    </div>
    <div class="card-body">
      <textarea readonly id="password" placeholder="Your Secure Password" aria-label="Generated Password"></textarea>
    </div>
    <div class="dojo">

    </div>
    <div class="card-footer">
      <button id="generate" class="btn">Generate Password</button>
    </div>
  </div>
</div>

I tried to set passwordText.value to and empty string at he beginning of the write password function but that would not work because passwordText.value is not defined until the end of the function. I also tried to create a function called PlayAgain to run the writePassword function again if the user chooses to and set the text value to an empty string but that didnt work either




vendredi 25 mars 2022

What is the characteristics of a Random machine learning model? and how to generate random model output [closed]

A few characteristics of a Random model I know are :

  • AUC score <=0.5
  • Precision recall curve is an horizontal line
  • It treats both events (binary classification) as 50-50%

How can I generate random model output for a balanced classification problem? I have tried dummy classifier from sklearn and also random number generation but none fulfill the above characteristics




Flutter how to get random item list in firestore and show them in listview

how can i get random item something mix everytime user open the app. right now i having a listview that show item but not randomly. i just get all of the data in firestore and show it into listview with unlimited length of item that look like this

 @override
  Widget build(BuildContext context) {
    final productProvider = Provider.of<ProductProvider>(context);
    List<Product> productsList = productProvider.products();
    return Column(
      children: [
        Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Suggestion Products',
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
                  ),
                  TextButton(
                      onPressed: () {
                        Navigator.of(context).pushNamed(
                          FeedsScreen.routeName,
                          arguments: 'popular',
                        );
                      },
                      child: const Text('view all')),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10.0),
              child: SizedBox(
                width: double.infinity,
                child: Column(
                  children: [
                    GridView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: productsList.length,
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              childAspectRatio: 2 / 3,
                              mainAxisSpacing: 1,
                              crossAxisSpacing: 15),
                      itemBuilder: (ctx, i) {
                        return ChangeNotifierProvider.value(
                          value: productsList[i],
                          child: const MainProduct(),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

and how can i achieve an suggestion product base on what user history search. kinda look like some o ecommerce app do. when i search for a computer in the app. in the suggestion will suggest me some related product. thanks




Take 2 random dates from list of dates based on days range condition

I would like to randomly choose 2 dates from the list of dates based on condition that if date range between 2 randomly choosen dates from the list is lower than 100 days we want to take them if not we look for other 2 random dates from the list.

Code below will not work but this is more or less what I would like to achieve:

dates = [date(2020, 1, 25), date(2020, 2, 23), date(2020, 3, 27)]

def get_2_random_dates_with_with_days_range_100():
   choosen_dates = random.choice([a, b for a, b in dates if a.days - b.days <= 100])

Also code above shows more or less what I've tried which is to use list comprehension with the condition but it would require me to unpack 2 values from the list

Thanks




jeudi 24 mars 2022

I get different accuracy each time i run my mlpclassifier

I'm using MLP classifier to classify my text data with 4 emotions

['calm', 'happy', 'fearful', 'disgust']. I checked everything I know random state , test split, gridsearchcv. The algorithm works fine and the accuracy is the problem, even though i am using the same dataset each time i run , the change in accuracy is very huge. The following is the code, Can some one tell me where i went wrong...

 def extract_feature(file_name, mfcc, chroma, mel):
    with soundfile.SoundFile(file_name) as sound_file:
        X = sound_file.read(dtype="float32")
        sample_rate = sound_file.samplerate
        if chroma:
            stft = np.abs(librosa.stft(X))
        result = np.array([])
        if mfcc:
            mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)
            result = np.hstack((result, mfccs))
        if chroma:
            chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T, axis=0)
            result = np.hstack((result, chroma))
        if mel:
            mel = np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T, axis=0)
            result = np.hstack((result, mel))
    return result

# Define the motions dictionary
emotions = {
    '01': 'neutral',
    '02': 'calm',
    '03': 'happy',
    '04': 'sad',
    '05': 'angry',
    '06': 'fearful',
    '07': 'disgust',
    '08': 'surprised'
}

# Emotions we want to observe
observed_emotions = ['calm', 'happy', 'fearful', 'disgust']


# Load the data and extract features for each sound file
def load_data():
    x, y = [], []
    for folder in glob.glob('dataset/Actor_*'):
        # print(folder)
        for file in glob.glob(folder + '/*.wav'):
            file_name = os.path.basename(file)
            emotion = emotions[file_name.split('-')[2]]
            if emotion not in observed_emotions:
                continue
            feature = extract_feature(file, mfcc=True, chroma=True, mel=True)
            x.append(feature)
            y.append(emotion)
    return train_test_split(np.array(x), y, test_size=0.25)


x_train, x_test, y_train, y_test = load_data()
# Shape of train and test set and Number of features extracted
print((x_train.shape[0], x_test.shape[0]))
print('Features extracted: {x_train.shape[1]}')

'''model = MLPClassifier(alpha=0.001, batch_size=256, epsilon=1e-08, hidden_layer_sizes=(18,), activation='logistic',
                      learning_rate='adaptive',
                      max_iter=500, solver='adam')'''
model = MLPClassifier(alpha=0.0001, batch_size=25, epsilon=1e-3, hidden_layer_sizes=(100,), activation='logistic',
                      learning_rate='constant',
                      max_iter=500, solver='adam', early_stopping=True)
model.fit(x_train, y_train)
# Predict for the test set
y_pred = model.predict(x_test)
# Calculate Accuracy

# clf = GridSearchCV(MLPClassifier(), param_grid, scoring='accuracy')
# clf.fit(x_train, y_train)

# y1_pred = clf.predict(x_test)

accuracy = accuracy_score(y_test, y_pred, normalize=True)

The accuracy keeps changing between 30-74.some times even below 30% gives this warning..

C:\Users\Gowtham nag\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\neural_network_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (500) reached and the optimization hasn't converged yet.

warnings.warn(




mercredi 23 mars 2022

How could I save the output of the console to a text file? [duplicate]

The title doesn't serve this question justice but I don't know how else to phrase it. (I already know that the contents of the console can be saved with a right-click, this is something different.) I'm using this for a different purpose, but let's simplify it so it's easier to understand. let's say that I have this code:

function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}
const numberRandom = getRandomInt(999);
console.log(numberRandom);

This basically generates a 'random' number with a max of 999, let's say I want to run this code 100 times and have the output be saved to a text file, like this: "12, 135, 765, 457, 876" etc. Would there be a quick and clean method to do that? If not, what is the next best solution?




How to randomly select an index in an array in Python without using any libraries

I need to generate a random index in an array without using any library such as random. For example I have an array of size=30, I need to generate an index that is within index 0-29 randomly. Perform this using hard code only and without any library.




How can i randomly insert values in an array in c#

I wanted to know how i could insert values randomly in an array. I have 4 values to randomly put in a 4x4 array




:))))) random ID

Python is an object-oriented programming. yappers




Creating random number using Exponential distribution in a specified range?

I need to create random numbers in a user specified range. I understood how to create random numbers and refering to Generating random numbers of exponential distribution that question. However, I need my random numbers to be in a range. I wrote a piece of code, althogh it works in theory, because it calculates very little numbers it approaches 0 and give wrong numbers. My code is

        double u;
        double p1 =  -1.0 *  lambda * minvalue;
        double p2 =  -1.0 *  lambda * maxvalue;
        double a_min =  1 - exp(p1);
        double a_max =  1 - exp(p2);
        u = (rand() / (RAND_MAX + 1.0));
        double diff = a_min - a_max;
        u = u * (a_min - a_max);
        u = u + a_max;
        double p3 = 1.0- u;
        int x = (int)(-log(p3) / lambda);
        return x;

lambda, minvalue and maxvalue are all integers. How can I deal with this issue ot is there any alternative solutions?

My code deals with very little numbers and so it is rounded to 0 then the result is calculated wrongly .




Generate random User ID with a function ; including quantity_digits and quantity_list being provided as arguments

Please note I am only allowed to use Math and Random class

so for this, I was considering using "for loop" for the number of of digits restriction from quantity_digit and use ''.join() function to add things up. The list might be like this ["333322","999883"].

I was wondering how do I for each iteration, randomly pick an element and within that element, pick random number from it. Can this be done? Please help

so this is I want to do

  1. define the function 2)for loop for addition of the characters from the string
  2. choose random string from the list each iteration
  3. and (each iteration) in that list I want to select several characters from that specific String
  4. use join() function to add things up



How to understand "a given random-number generator always produces the same sequence of numbers" in C++ primer 5th?

Title "Engines Generate a Sequence of Numbers" in section 17.4.1 has following Warring.

A given random-number generator always produces the same sequence of numbers. A function with a local random-number generator should make that generator (both the engine and distribution objects) static. Otherwise, the function will generate the identical sequence on each call.

"A given random-number generator always produces the same sequence of numbers." What kind of given generator does it refer to?

If I give a random number engine and a random number distribution, they form a given random number generator.

  1. Will it always produce a fixed sequence of values given a seed?
  2. Won't it change because of different compilers or system environments?

So I compiled and ran the following code on different compilers.

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

minstd_rand0 dre1(13232);
minstd_rand0 dre2(13232);

int main()
{
    uniform_int_distribution<unsigned> h1(0,10);
    uniform_int_distribution<unsigned> h2(0,10);
    unsigned t=100;
    while(t--){
        cout << "dre1:" << h1(dre1) << endl;
        cout << "dre2:" << h2(dre2) << endl;
    }

}

For it's easy to watch, I won't release all the results.

//in gcc and clang:
dre1:1 
dre2:1 
dre1:5 
dre2:5 
dre1:1 
dre2:1 
dre1:9 
dre2:9 
dre1:6 
dre2:6
//in msvc
dre1:0
dre2:0
dre1:0
dre2:0
dre1:3
dre2:3
dre1:2
dre2:2
dre1:0
dre2:0

Why did this happen?




How do I add criteria to obtain two equivalent samples from my data?

I have a dataset of about 6000 words. I'd like to pull two samples of 25 words each, however the average WordLength for both samples must be the same, and all words across both samples must be different.

This is what my data looks like:

Word      Type                 CEFR    WordLength
a         indefinite article   a1      1
abandon   verb                 b2      7
ability   noun                 b2      7
able      adjective            a1      4

This is just one of the criteria I need the samples to match on; if this is straightforward to you, please consider taking a look at my other question which adds a more complicated level: Scraping Oxford5000 words and obtaining two equivalent word lists




Discord.py - random post from subreddit using asyncpraw

I need to display a 1 random submission from the most 100 hot reddit submissions after entering the command. This is my code without randomness, it's just send me 100 posts:

@bot.command()
async def picture(ctx, name):
    picture_submission = await reddit.subreddit("Genshin_Impact")
    post_to_pick = random.randint(1, 100)
    async for submission in picture_submission.search(f"{name}", params={'include_over_18': 'on'}, limit=100):
        url = submission.url
        title = submission.title
        embed = discord.Embed(title=f'__{title}__', colour=discord.Colour.light_gray(),
                              timestamp=ctx.message.created_at, url=url)
        embed.set_image(url=url)

        await ctx.send(embed=embed)

I've tried random.choice(), but it didn't worked:

    async for submission in picture_submission.search(f"{name}", params={'include_over_18': 'on'}, limit=100):
        random.choice(submission)
    url = submission.url
    title = submission.title
    embed = discord.Embed(title=f'__{title}__', colour=discord.Colour.light_gray(),
                              timestamp=ctx.message.created_at, url=url)
    embed.set_image(url=url)
    await ctx.send(embed=embed)

Error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Submission' has no len()

Before I moved from PRAW to AsyncPRAW I've used this and it worked fine:

@bot.command()
async def picture(ctx, name):
    picture_submission = reddit.subreddit("Genshin_Impact").search(f"{name}", sort="hot", params={'include_over_18': 'on'})
    post_to_pick = random.randint(1, 100)
    for i in range(0, post_to_pick):
        submission = next(x for x in picture_submission if not x.stickied)
    url = submission.url
    title = submission.title
    embed = discord.Embed(title=f'__{title}__', colour=discord.Colour.light_gray(), timestamp=ctx.message.created_at, url=url)
    embed.set_image(url=url)

    await ctx.send(embed=embed)



mardi 22 mars 2022

Would there be a way to generate a random string of “n” letters from the main method?

I am trying to have the string be randomly generated and used in a for loop.
When I try, I can’t seem to get it to even generate be a string with “n” letters.

I tried to add together multiple chars to create a string, but, from the for loop, all of the chars are the same. (I tried using chars because I will be doing a project with them and I need experience.) I have resorted to using strings and I need help finding out how to do the random generation.




Why can't I print a random number from 1 to a variable?

I was making a python program where you type in an input, and it finds a random number from 1 to that input. It won't work for me for whatever reason.

I tried using something like this

import random
a = input('pick a number: ')
print(random.randint(1, a))
input("Press enter to exit")

but it won't work for me, because as soon as it starts to print it, cmd prompt just closes. does anyone know how to fix this?




How can I send a random message everyday from an array at a specific hour on discord.js?

I'm trying to make a bot that will send a random message from an array using cron.

Here is my code:

const cron = require('cron');

module.exports = {
    name: 'pesanrandom',
    description: "random message every day",
    execute(message, args, cmd, client, Discord){
      let scheduledMessage = new cron.CronJob('00 54 16 * * *', () => {
        //
        var listPesan = [
          'Met siang guys, dah pada mam siang blum?',
          'Siapa yang tadi pagi mimpiin cowo atau cewe kpopnya',
          'Siang-siang enaknya...',
          'Dor kaget ga',
          'Laper dah',
        ];

        var pesanRandom = listPesan[Math.floor(Math.random() * listPesan.length)];

        const pesanEmbed = new Discord.MessageEmbed()
              .setColor('#50C878')
              .setTitle('vermillion#3039')
              .setDescription(pesanRandom)
              .setFooter('© Vermillion')

        client.channels.cache.get('927589065925214239').send(pesanEmbed);
        //
      });

      scheduledMessage.start()
    }
}

I already try the code and it works but it can only randomize the message one time. How to make it randomize the message everytime the message is sent?




Random position on X Axies

I'm trying to randomize position my div on the x axies. As default my div value is 5em (console.log(balloon.offsetWidth) => 80 in px)

get random number between 2 numbers:

function getRandomNumber(min:number, max:number){
    return Math.floor(Math.random() * (max - min) + min);
}

setting random position among the body width - the width of the div to prevent overflow

function setBalloonRandomXAxies(balloon:HTMLDivElement){
    balloon.style.left = `${getRandomNumber(0, (body.offsetWidth - balloon.offsetWidth))}px`
}

I'm still getting results bigger than: (body width - balloon width).

this works but, not dynamic maybe my div will change sizes sometimes

balloon.style.left = `${getRandomNumber(0, (body.offsetWidth - 80))}px`

Any helpers out there ?




How to display random custom html widget within a widget area?

I've registered a new widget area in functions.php using

        'name' => __( 'Grand angle sous les articles', 'twentyten' ),
        'id' => 'grand-angle',
        'description' => __( 'Grand angle en bas des articles', 'twentyten' ),
        'before_widget' => '<div id="grand-angle">',
        'after_widget' => '</div>',
        'before_title' => '',
        'after_title' => '',
    ) );

I'm calling this new widget area in a php template like this :

<?php if ( is_active_sidebar( 'grand-angle' ) ) : dynamic_sidebar( 'grand-angle' ); endif; ?>

Inside this new widget area I'm now adding several custom html widgets and I would like to display them randomly. These custom html widgets contain ads (mostly images) and I need to set up a rotation. Any idea how to do that? Thank you very much for your help.




Why do i get a type error when using Python random number generator and trying to do <= [closed]

This is my code

from random import seed
from random import random

seed(9382)
i=random
if i>=8:
    print(random())
else:
   print("€###€&€#€€€€§§&%€bel=ö")`

I don’t understand why it doesn’t work

I tried using random but I always get

TypeError:
"\>=" not supported between instances
of 'builtin_function_or \_method' and
int



lundi 21 mars 2022

Is there a better way of referring to the index of a digit within an integer? [duplicate]

Python newbie The purpose of the code is to add together the two digits within a random two-digit number (e.g. 11 = 1+1 = 2)

import random

def add_double_digits():
    num = random.randrange(10, 99)
    snum = str(num)

    print(num)
    print(int(snum[0]) + int(snum[1]))

add_double_digits()

I've had to create a variable called "snum" (string number) which converts the number into a string and then back again so that I can get the index of the individual digits. I hope I'm using the correct terminology. Is there a more efficient way of doing this/ am I lacking some fundamental knowledge here or is this the way it should be done? Thanks.




randomly coloring an nXn matrix

I have an nXn matrix (or an image) and I want to randomly break it into different continuous regions where each region has its unique color. The following specs for each region:

  1. The union of regions must give the whole matrix.
  2. Each region has its unique color. Colors cannot be repeated.
  3. The maximum number of elements within each region is M and the minimum is Z.
  4. Each region must be continuous. That is a color should be only seen in a continuous region. Having two disjoint regions with the same color is prohibited.
  5. Preferably, each region boundary is smooth. That is there is no narrow areas and then expansion such as Maryland state map but more like Wyoming, Oregon, and Washington.

My initial thought is to start with point (0,0) and then randomly generate xandy such as np.random.randint(Z,M). Then, draw a line between the randomly generated x and y. However, the problem with this approach that it needs to keep track of all pixels/elements or some of them will end up not assigned to any region, which is time consuming. Anyone has a better idea?




Random Sample in R: Limiting Number of Repetitionsout of a 2 digit vector

I have the following vector in R: c(0,1).

I am wishing to randomly sample from this vector 10 elements at a time, but such that no more than 2 elements repeat.

The code I have tried is sample(c(0,1),10,replace=T)

But I would like to get

sample(c(0,1),10,replace=T) = (0,1,1,0,1,1,0,0,1,0)

sample(z,4,replace=T) = (0,1,0,1,0,0,1,0,1,0)

but not

sample(z,4,replace=T) = (1,0,0,0,1,1,0,0,0)

And so on.

How could I accomplish this?




I am making a memory game. How do I randomize the images in my gridview?

I am trying to randomize the images shown in my 4x4 grid for a memory card game. But I do not know how. Could someone help me.

I am very lost, the game itself works but does not randomise the images like i want it to. I have tried various methods but my knowledge of java is not deep enough. This is for a small project and we have yet to be taught randomising and

My game activity

public class Game extends AppCompatActivity { 
//Variables 
ImageView curView = null; 
private int countPair = 0; 
//Score 
private TextView scoreLabel; 
private int score = 0; 
//Tries 
private int tries = 0; 
private TextView tryLabel; 
//Attempts 
private int attempt = 10; 
private TextView attemptlabel; 
//FinalScore 
private TextView finalscore;

//The cards images initialised
final int[] drawable = new int[] {
        R.drawable.one,
        R.drawable.two,
        R.drawable.three,
        R.drawable.four,
        R.drawable.five,
        R.drawable.six,
        R.drawable.seven,
        R.drawable.eight,
        R.drawable.nine,
        R.drawable.ten,
        R.drawable.eleven,
        R.drawable.jack,
        R.drawable.king,
        R.drawable.trump};
//Position of the cards / variables
int[] pos = {0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7};
int currentPos = -1;


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

    //Hides action bar
    getSupportActionBar().hide();


    //Changes score text
    scoreLabel = (TextView) findViewById(R.id.scoreText);
    scoreLabel.setText("Score : 0");

    //Changes try text
    tryLabel = (TextView) findViewById(R.id.tries);
    tryLabel.setText("Tries : 0");

    //Changes attempt text
    attemptlabel = (TextView) findViewById(R.id.attemptext);
    attemptlabel.setText("Attempts left : 10");

    //Change text for final score
    finalscore = (TextView) findViewById(R.id.textView15);

    //Initialises as a MediaPlayer
    final MediaPlayer yay = MediaPlayer.create(this, R.raw.yay);
    final MediaPlayer fail= MediaPlayer.create(this, R.raw.fail);
    final MediaPlayer music = MediaPlayer.create(this, R.raw.battle);

    //Button OnClick to enable and loop music
    final Button button1 = (Button)findViewById(R.id.song);
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            music.setLooping(true);
            music.start();
        }
    });
    //Button OnClick to pause music
    final Button button2 = (Button)findViewById(R.id.stop);
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            music.pause();
        }
    });






    //Initiates GridView alongside the ImageAdapter I created
    GridView gridView = (GridView) findViewById(R.id.gridView);
    //Collections.shuffle(list);
    ImageAdapter imageAdapter = new ImageAdapter(this);
    gridView.setAdapter(imageAdapter);





    
    //What happens when you click the card
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        //This section of code enables the position of the code
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            if (currentPos < 0)
            {
                currentPos = position;
                curView = (ImageView)view;
                ((ImageView)view).setImageResource(drawable[pos[position]]);
                //Whenever an attempt is made give 1 point for tries and remove from attempts left
                tries +=1;
                attempt -=1;


            }

            else
            {
                //If the card is pressed and it is wrong, then say to the user it is incorrect
                if (currentPos == position)
                {
                    ((ImageView)view).setImageResource(R.drawable.back);
                }
                else if (pos[currentPos]!=pos[position])
                {
                    curView.setImageResource(R.drawable.back);
                    Toast.makeText(getApplicationContext(),"No match, try again!", Toast.LENGTH_SHORT).show();
                    //When correct plays the wav fail file below
                    fail.start();
                }
                else
                //If the card is pressed and it is right, then say to the user it is correct
                {
                    ((ImageView)view).setImageResource(drawable[pos[position]]);
                    countPair++;
                    //Add 1 points everytime the user is correct
                    score +=1;
                    //When correct plays the wav yay file below
                    yay.start();


                    Toast.makeText(getApplicationContext(),"That was correct!",Toast.LENGTH_SHORT).show();


                    //When all the cards are correct
                    if(countPair==0)
                    {
                        Toast.makeText(getApplicationContext(),"You win!",Toast.LENGTH_SHORT).show();
                    }
                }
                //Current position is back

                currentPos = -1;
                //Change text to x + score/tries/attempt
                scoreLabel.setText("Score : " + score);
                tryLabel.setText("Tries : " + tries);
                attemptlabel.setText("Attempts left : " + attempt);

                //If attempts reach 0 then a toast message shows your final score
                if(attempt==0)
                {
                    Toast.makeText(getApplicationContext(),"Game Over!, your final score was : "+ score,Toast.LENGTH_SHORT).show();
                    //Disables the ability to continue playing until reset
                    gridView.setOnItemClickListener(null);
                    //Changes Match them all to You lose after 0 attempts left
                    finalscore.setText("YOU LOST!");

                }
                //Allows the button to be pressed
                final Button button = (Button)findViewById(R.id.finish);
                button.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        //Makes a toast message saying games over, alongside how many attempts were successful
                        Toast.makeText(getApplicationContext(),"Game Ended! Successful attempts = "+ score,Toast.LENGTH_SHORT).show();
                        //Makes a toast message showing how many tried were attempted
                        Toast.makeText(getApplicationContext(),"Tries Attempted = "+ tries,Toast.LENGTH_SHORT).show();
                        //Disables onClick on the gridView to stop the game
                        gridView.setOnItemClickListener(null);
                        //Changes the title to Game Ended
                        finalscore.setText("Game Ended");
                        //Accuracy of attempts (How many were correct in a percentage))
                        float endScore = tries / score;
                        float magical = endScore*100;
                        Toast.makeText(getApplicationContext(),"Total accuracy= "+ magical,Toast.LENGTH_SHORT).show();


                    }
                });

            }
        }
    });


}

}

Then my base adapter

public class ImageAdapter extends BaseAdapter

{ private Context context;
public ImageAdapter(Context context)
{
    this.context = context;
}

@Override
public int getCount() {
    return 16;
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null)  //If it is not recycled, initialise some attributes
    {
        //The parameters of the card block.
        imageView = new ImageView(this.context);
        imageView.setLayoutParams(new GridView.LayoutParams(350,350));
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setPadding(8,8,8,8);

    }
    //Changes the block to "back" which is the cards behind.

    else imageView = (ImageView) convertView;


        imageView.setImageResource(R.drawable.back);


    //If the card is correct then show the image.
    return imageView;


}



Quantifying Randomness, quantifying of how random a newly discovered infinite series is and be able to get a more complete list on quantifying random?

A very interesting topic, "quantification of randomness" in mathematics it is sometimes reffered to as "complex theory" (although it is more about pseudorandom than randomness) that is based on saying that a complicated series is more random and then there are tests for randomness in Statistics and perhaps the most intriguing test related to information theory -"entropy"(as also being of relevence to and result of second law of thermodynamics), while there are also random numbers generators (pseudorandom numbers generators) and true random numbers generators using quantum computing.

So, what I've been trying to, is making a complete list of all available algorithms or books or even random number generators that will allow me to tell me how much random a series is, allowing me to "quantify randomness".

There are 125 unique infinite series which are pseudorandom that I have discovered and generated based on a rule, now how do I test for randomness and quantify it? If the series is random or there is probably a pattern, or something that will allow me to predict the next number in the series given I don't know what the next number is.

Now, do anyone know of any github links based on any of the above? ^ (like anything related to quantifying randomness in general that you think will be helpful). A book/books on quantifying randomness will be very very helpful too. Actually anything at all...

(Also, Any coding language will do if it is able to make use of any existing algorithms for computing randomness, I have used Python for generating 125 unique infinite series which are pseudorandom-like, so is there a way already available to check how much random these series are (programmatically) or what do you suggest I should do...)

I didn't try much as of yet but what I'm planning to is first being able to plot the data (infinite sequences) get images (descriptive statistics to the rescue) to tell me if the data is first looking like random noise, although it is kind of already as from the way I computed it but essentially being able to convert one kind of data to another and see if it is behaving like noise or not.

Then there are measures such as based on compression's (something like Kolmogorov complexity) and the ways algorithms might have been used to determine how much random pi could be? I'm looking into Entropy as well, books, reading stuff and also exploring cryptographic ways but all of these are research work, am yet to arrive at developing proper and more complete ways of also being able to implement all of it programmatically and I need as many ways of being able to do it as possible.




dimanche 20 mars 2022

Degrees of Freedom in SAS Proc MIXED

Below is a SAS proc Mixed code generated by JMP. Both JMP and SAS give me a confidence interval for the variance components (in the table "covariance parameter estimates"). I would like the degrees of freedom in the output, or at least a formula to calculate them. Can anyone tell me where that would be?

DATA Untitled; INPUT  x y Batch &$; Lines;
0  107.2109269  4  
3  106.3777088  4  
6  103.8625117  4  
9  103.7524023  4  
12  101.6895595  4  
18  104.4145268  4  
24  100.6606813  4  
0  107.6603635  5  
3  105.9161433  5  
6  106.0260339  5  
9  104.660272  5  
12  102.5820776  5  
18  103.7961511  5  
24  101.2887124  5  
0  109.2066284  6  
3  106.9341754  6  
6  106.6141445  6  
9  106.8234541  6  
12  104.7778902  6  
18  106.0184734  6  
24  102.9822743  6  
;
RUN;

PROC MIXED ASYCOV NOBOUND  DATA=Untitled ALPHA=0.05;
CLASS Batch;
MODEL  y =  x/ SOLUTION DDFM=KENWARDROGER;
RANDOM Batch / SOLUTION ;
RUN;



Sort dataframe by variable instead of column value

I have a dataframe that I am currently sorting by row id 8, however I want to adjust this so it sort it by a variable that contains a random number. See code below

    cosine_similarity_matrix_df.sort_values(by=['8'], ascending=False).head(11)

I want to make it so that instead of sorting the dataframe by row id 8, it sorts depending upon the random number stored in the variable called "id". I have tried to alter the code to put the variable id instead of ['8'] but this doesnt seem to work. Is there any way i can do this




Generate totals of multinomial distribution directly

Let's assume we want to generate n samples from a multinomial distribution from given probabilities p. This works well with sample or rmultinorm. The totals can then be counted with table. Now I wonder if there is a direct way (or another distribution) available to get the result of table directly without generating complete sample vectors.

Here an example:

set.seed(123)
n <- 10000              # sample size
p <- c(0.1, 0.2, 0.7)   # probabilities, sum up to 1.0

## 1) approach with sample
x <- sample(1:3, size = n, prob = p, replace = TRUE)
table(x)
# x
# 1    2    3 
# 945 2007 7048 

## 2) approach with rmultinorm
x <- rmultinom(n, size = 1, prob = p) * 1:3
table(x[x != 0])
# 1    2    3 
# 987 1967 7046 



samedi 19 mars 2022

Using element in vector as index in array?

I'm writing code that randomly generates a vector of indices, fetches a random one, then uses that index to fetch another index, and so on. However, my code seems to repeat a cycle of indices. Here is my full code:

vector<uint16_t>* genBuffer() {
    vector<uint16_t>* buffer = new vector<uint16_t>(256);
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distr(0, 255);
    for (uint16_t i = 0; i < 256; i++) {
        (*buffer)[i] = distr(gen);
    }
    shuffle(buffer->begin(), buffer->end(), gen);
    return buffer;
}

double timeAccess(vector<uint16_t>* buff, uint64_t buffSize) {
    struct timespec start, stop;
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> distr(0, 255);
    auto index = distr(gen);
    auto nextIndex = (*buff)[index];
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (uint64_t i = 0; i <= buffSize; i++) {
        cout << nextIndex << endl;
        nextIndex = (*buff)[nextIndex];
    }    
    clock_gettime(CLOCK_MONOTONIC, &stop);
    double time_taken = (stop.tv_sec - start.tv_sec) - (double)(stop.tv_nsec - start.tv_nsec);
    double avgTime = time_taken/buffSize;
    return avgTime;
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        cout << "Please enter only one numerical argument." << endl;
        return -1;
    }
    uint64_t buffSize = atoi(argv[1]);
    auto randBuff = genBuffer();
    auto timeTaken = timeAccess(randBuff, buffSize);
    cout << "Average time per buffer read = " << timeTaken << " ns" << endl;
    return 0;
}

Here is an example run with an argument of 25:

35
218
157
9
4
214
225
246
123
92
195
114
200
33
138
13
17
35
218
157
9
4
214
225
246
123

As you can see, the pattern eventually repeats, although it shouldn't do that.

This code is part of a cache benchmark I was asked to write for class. Here is the full code for anyone willing to try:

https://github.com/aabagdi/CacheBenchmark

As well, I'm trying to time the average time per read in ns. Am I doing that correctly? Thanks!




Why does my functions generate always the same "randomness"? [duplicate]

I thought that the shuffle_string function would have generated a new seed each time gets called (so every time the cycle repeats), but something is wrong.

What could I do to circumvent this problem?

(COMPILER: g++, OS: Windows 10 x64)

Edit: Compiling with Visual Studio my code is actually running as expected.

Edit2: As suggest in the comments by @Eljay , adding 'static' before

std::random_device rd;

and before

std::mt19937_64 mt64{ rd() };

makes my program run fine even if comping with g++.

#include <iostream>
#include <random>

using std::cin; using std::cout;

void shuffle_string(std::string& s) {
    auto size = s.size();
    std::random_device rd;
    std::mt19937_64 mt64{ rd() };
    std::uniform_int_distribution<unsigned long long int> ind_range (0, size-1);
    for (auto i = 0; i < size; ++i) {
        std::swap(s[i], s[ind_range(mt64)]);
    }
}
int main() {
    while (true) {
    std::string string;
    cout << "Enter the string you want to randomly shuffle:\n";
    std::getline(cin, string);
    if (string == "exit") { return 0; }

    shuffle_string(string);

    cout << string << '\n';
    }
}

P.S.: I know i should always prefer std::shuffle, but i'm writing this only with the aim of learn something new (and actually this problem is something new).

Thanks, good evening.




Python random walks for COVID infections

I'm trying to implement a random walk algorithm in 2D to model COVID infections at a party/festival. The main body of my code is shown below, excluding some plots and initial conditions where I define all the initial positions (using a random uniform sampling) and initial parameters. My problem is, when I run my code and plot the various populations at different steps, for whatever reason the population of moving infected people ends up looking like the green data after several steps: Why does this happen? Is this something to do with the random uniform sampling? Any help is appreciated.

import numpy as np
import pandas as pd
from numpy import random
import matplotlib.pyplot as plt
from random import uniform
import itertools as itr
import time

nsteps = 10
xlim = ylim = [10, 0]
npeople = 100
npeople_move = 90
ninfected = 2
ninfected_move = 1
size = 5


fig, axs = plt.subplots(1, nsteps, figsize = [30, 5])
plt.rcParams['axes.grid'] = True
plt.setp(axs, xlim=[xlim[-1], xlim[0]], ylim=[ylim[-1], ylim[0]])

peoplex_move = np.array([uniform(xlim[-1], xlim[0]) for i in np.arange(0, npeople_move, 1)])
peopley_move = np.array([uniform(ylim[-1], ylim[0]) for i in np.arange(0, npeople_move, 1)])

peoplepos_move = np.sqrt(np.square(peoplex_move), np.square(peopley_move))

peoplex = np.array([uniform(xlim[-1], xlim[0]) for i in np.arange(0, npeople - npeople_move, 1)])
peopley = np.array([uniform(ylim[-1], ylim[0]) for i in np.arange(0, npeople - npeople_move, 1)])

peoplepos = np.sqrt(np.square(peoplex), np.square(peopley))


infx_move = np.array([uniform(xlim[-1], xlim[0]) for i in np.arange(0, ninfected_move, 1)])
infy_move = np.array([uniform(ylim[-1], ylim[0]) for i in np.arange(0, ninfected_move, 1)])

infpos_move = np.sqrt(np.square(infx_move), np.square(infy_move))


infx = np.array([uniform(xlim[-1], xlim[0]) for i in np.arange(0, ninfected - ninfected_move, 1)])
infy = np.array([uniform(ylim[-1], ylim[0]) for i in np.arange(0, ninfected - ninfected_move, 1)])

infpos = np.sqrt(np.square(infx), np.square(infy))
df = pd.DataFrame({'Number of people':[], 'Number of infected':[], 'Step Number':[]})

cough_sneeze = False
cough_sneeze_loc = []
size = 10

start = time.process_time()



for step in np.arange(1, nsteps, 1):
    
    
    theta = 2*np.pi*np.random.uniform(0, 1, npeople_move + ninfected_move)
    
    if bool(cough_sneeze_loc)!=False:
        
        for item in cough_sneeze_loc:
            
            item[1]-=1
            
            if item[1]==0:
                
                cough_sneeze_loc.remove(item)
                
            else:
                
                continue
        
                
                
    peoplex_move = peoplex_move + size*np.cos(theta[0:npeople_move])
    peopley_move = peopley_move + size*np.sin(theta[0:npeople_move])
    
    peoplex_move = np.where(peoplex_move>=xlim[0], peoplex_move - size, peoplex_move)
    peoplex_move = np.where(peoplex_move<=xlim[-1], peoplex_move + size, peoplex_move)
    peopley_move = np.where(peoplex_move>=ylim[0], peopley_move - size, peopley_move)
    peopley_move = np.where(peoplex_move<=ylim[-1], peopley_move + size, peopley_move)
    
    infx_move = infx_move + size*np.cos(theta[npeople_move:npeople_move + ninfected_move])
    infy_move = infx_move + size*np.sin(theta[npeople_move:npeople_move + ninfected_move])
    
    infx_move = np.where(infx_move>=xlim[0], infx_move - size, infx_move)
    infx_move = np.where(infx_move<=xlim[-1], infx_move + size, infx_move)
    infy_move = np.where(infy_move>=ylim[0], infy_move - size, infy_move)
    infy_move = np.where(infy_move<=ylim[-1], infy_move + size, infy_move)

    peoplepos_move = np.sqrt(np.square(peoplex_move), np.square(peopley_move))
    
    infpos_move = np.sqrt(np.square(infx_move), np.square(infy_move))
    

            

                
    if bool(cough_sneeze_loc)!=False:
        
        for item in peoplepos:
            
            if np.any(np.abs(item - np.stack(cough_sneeze_loc)[:,0]) <= 5):
                
                
                
                bad = np.where(peoplepos == item)
                
                infpos = np.append(infpos, item)
                
                peoplepos = np.delete(peoplepos, bad)
                
                infx = np.append(infx, peoplex[bad])
                
                infy = np.append(infy, peopley[bad])
                
                peoplex = np.delete(peoplex, bad)
                
                peopley = np.delete(peopley, bad)
                
                npeople-=1
                ninfected+=1
                

                
            else:

            
                continue
                
                
        for item in peoplepos_move:
            
            if np.any(np.abs(item - np.stack(cough_sneeze_loc)[:,0]) <=5):
                
                
                bad = np.where(peoplepos_move == item)
                
                infpos_move = np.append(infpos_move, item)
                
                peoplepos_move = np.delete(peoplepos_move, bad)
                
                infx_move = np.append(infx_move, peoplex_move[bad])
                
                infy_move = np.append(infy_move, peopley_move[bad])
                
                peoplex_move = np.delete(peoplex_move, bad)
                
                peopley_move = np.delete(peopley_move, bad)
                
                ninfected_move+=1
                npeople_move-=1
                npeople-=1
                ninfected+=1
                
            else:
                
                continue
                
        
    cough_sneeze1 = np.random.choice(infpos_move, 2)

    cough_sneeze2 = np.random.choice(infpos, 2)
    
    

        
    cough_sneeze_loc.append([cough_sneeze1.astype(float)[0], 2])
        
    cough_sneeze_loc.append([cough_sneeze2.astype(float)[0], 2])

        
    for pos in peoplepos_move:
            
        if np.any(np.abs(pos - infpos)<=1) or np.any(np.abs(pos - infpos_move)<=1):
                
            bad = np.where(peoplepos_move == pos)
                
            infpos_move = np.append(infpos_move, pos)
                
            peoplepos_move = np.delete(peoplepos_move, bad)
                
            infx_move = np.append(infx_move, peoplex_move[bad])
                
            infy_move = np.append(infy_move, peopley_move[bad])
                
            peoplex_move = np.delete(peoplex_move, bad)
                
            peopley_move = np.delete(peopley_move, bad)
                
            npeople_move-=1
            ninfected_move+=1
            npeople-=1
            ninfected+=1
                
        else:
                
            continue
                
                
    for pos in peoplepos:
            
        if np.any(np.abs(pos - infpos)<=1) or np.any(np.abs(pos - infpos_move)<=1):
                
            bad = np.where(peoplepos == pos)
                
            infpos = np.append(infpos, pos)
                
            peoplepos = np.delete(peoplepos, bad)
                
            infx = np.append(infx, peoplex[bad])
                
            infy = np.append(infy, peopley[bad])
                
            peoplex = np.delete(peoplex, bad)
                
            peopley = np.delete(peopley, bad)
        
            npeople-=1
            ninfected+=1
                
        else:
                
            continue
            



how do I write a random user who is on the server to the "user" variable?

I need to write the name of a random user on the server to a variable.

this is about how I present this code:

import discord
from discord.ext import commands
import random

@client.command()
async def hi(ctx):

    user = discord.utils.get(ctx.guild.members, name = random)

    await ctx.send(user + ' hi!')



(Java) Made an ArrayList and I'm looking to randomize the names, numbers, and positions. How do I make them not repeat? [duplicate]

I made an array list with the following names, positions, and numbers.

ArrayList<Player> playerInfo = new ArrayList<Player>();

playerInfo.add(new Player("Wilson", 'F', 14));
playerInfo.add(new Player("Johnson", 'F', 22));
playerInfo.add(new Player("Terry", 'D', 27));
playerInfo.add(new Player("Price", 'G', 34));
playerInfo.add(new Player("Stamkos", 'F', 26));

I'm looking to make something that outputs a random name, position, and number. For example having it choose Wilson, G, 26.

I have the following to make it choose a random one of each but I don't know how to stop them from from duplicating (Positions can duplicate since there's only 3 options and I'm only showing the code on how it gets the name but the exact same code is used to get the number and position).

for(Player name:playerInfo)
    {
      Random genSurname = new Random();
      int randSurname = genSurname.nextInt(5);
      System.out.println(playerInfo.get(randSurname).getSurname());
    }

Any direction would be appreciated. Thanks!




jeudi 17 mars 2022

why xorshift random number generator uses the same "amount" of SBR in all examples?

I was going through a book that explained the xorshift algorithm (I know, basic stuff). Then, while searching a little bit more on the Internet, I found that all the basic examples seem to shift the bits right the same "amount" (13, 17, 5).

For instance:

struct xorshift32_state {
  uint32_t a;
};

uint32_t xorshiftTransform(struct xorshift32_state *state) {
    uint32_t x = state->a;

    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    
    return state->a = x;
}

Is there a particular reason why in all examples they use 13, 17 and 5? Yep, I found other examples too, but this one keeps repeating, and I don't know if the numbers choose is trivial or not.




Why aiohttp-socks does not accept the value that was retrieved by using random library?

import aiohttp
import asyncio
import random
from aiohttp_socks import ProxyType, ProxyConnector, ChainProxyConnector

_goodsocks = []
_loop = asyncio.get_event_loop()

for socks in open("C:\\Users\\user\\Desktop\\python\\goodsocks.txt","r").read().split("\n"):
    _goodsocks.append(socks)

async def randomfunction():
    conn = ProxyConnector.from_url(f"socks5://{str(random.choice(_goodsocks))}")
    session = await createsession(conn)
    response = await session.get("http://www.google.com")
    print(response.status)

i = 0
while i <= 10:
    loop.create_task(randomfunction())

try:
    loop.run_forever()
except:
    loop.stop()
finally:
    loop.close()

output:

conn = ProxyConnector.from_url(f"socks5://{prox}")

proxy_type, host, port, username, password = parse_proxy_url(url)

raise ValueError('Empty host component')  # pragma: no cover

ValueError: Empty host component

**Im trying to send a request with a random proxy. Im able to send the request by typing manually the host and port but when i use the random library it gives a error that says empty host component. **




If one knows the population size by age range and mean and std for each range , how does one get the random sample out of it in python?

I have googled and read up on random sampling from a given population , both in probability and in python , but each of the examples have data then extraction of random samples out of population data generated.

But if I don't have the population data but just the mean and std ?

For example

Age Size Mean (of Salary) Std Mean (of Salary)
20-25 15000 5000 600
25-30 20000 6000 700

From the data above , how can I extract out the random sample of 200 with python ?

What I been seeing is something like "rs.append(np.random.choice(X, 5))" but I have no X , or population to choose from.

Thanks in advanced.




How do I reset a random value after pressing a key in p5.js?

I have to make a "choose your own adventure" type code for one of my classes and for my idea, I decided to make the setting take place in a carnival and have the user choose a game to play. I'm currently trying to recreate the first carnival game I chose, which is balloon pop. For this, I simply have 6 ellipses representing balloons and I want the user to press "t" to throw a dart, and there would be a 50/50 chance for them to score. How I tried doing this is by setting a variable called "outcome" equal to "int(random(1, 10))" and if the generated value is between 1-5, then they pop a balloon but if it's between 6-10, then they miss. The problem is I have the random value in the setup function and it only generates a value once. I want it so that the value would generate a new number every time the user presses "t" to throw a dart, and I'm having trouble figuring out how to do that. Is there a way generate a new value each time?

Here's the balloon pop portion of my code:

let scenes = [];
let currentScene = 0;
let outcome;
let popp = 0;

function setup() {
  createCanvas(windowWidth, windowHeight);
  colorMode(HSB);
  
  outcome = int(random(1, 10));
  
  textFont("Paytone One");
  textSize(width/50);
  
  scenes[0] = {
    text: "Throw darts at the balloons in order to pop them. \nWhat would you like to do? \n(T)hrow Dart",
    keys: ["t"],
    nextPages: [1],
  }
  
  scenes[1] = {
    text: "Throw darts at the balloons in order to pop them. \nWhat would you like to do? \n(T)hrow Dart",
    keys: ["t"],
    nextPages: [0, 1],
  }
  
}

function draw() {
  background(185,100,100);
  noStroke();
  
  highScore();
  
  
  fill("black");
  text(scenes[currentScene].text, 40, 40);
  
  if (key == "t"){
    if(outcome >= 1 && outcome <= 5){
      fill(0,100,100);
      rectMode(CENTER);
      rect(width/2, height/2 + 50, width/1.5, height/2);
      balloons(tL);
      popp = 1;
    }else{
      text("You missed!", width/2.25, height/3.5)
      fill(0,100,100);
      rectMode(CENTER);
      rect(width/2, height/2 + 50, width/1.5, height/2);
      balloons();
    }
  }
  else {
    fill(0,100,100);
    rectMode(CENTER);
    rect(width/2, height/2 + 50, width/1.5, height/2);
    
    balloons();
  }
  console.log(outcome);
}

function keyPressed() {
  for (let i = 0; i < scenes[currentScene].keys.length; i++) {
    if (key == scenes[currentScene].keys[i]) {
      currentScene = scenes[currentScene].nextPages[i];
    }
  }
}

function highScore(points = 0) {
  fill("black");
  text("Points: " + points, width - 100, 20);
}

function balloons(tL = 1, tM = 1, tR = 1, bL = 1, bM = 1, bR = 1){
  push();
  fill(60, 100, 100, tL);
  ellipse(width/3.5, height/2.6+50, 120, 100);
  
  fill(175, 100, 100, tM);
  ellipse(width/2, height/2.6+50, 120, 100);
  
  fill(300, 100, 100, tR);
  ellipse(width/1.4, height/2.6+50, 120, 100);
  
  fill(90, 100, 100, bL);
  ellipse(width/3.5, height/1.6+50, 120, 100);

  fill(45, 100, 100, bM);
  ellipse(width/2, height/1.6+50, 120, 100);
  
  fill(215, 100, 100, bR);
  ellipse(width/1.4, height/1.6+50, 120, 100);
  pop();
}

let tL = 0; let tM = 0;
let tR = 0; let bL = 0;
let bM = 0; let bR = 0;



randint not random enough. Creating slot machine [closed]

I am trying to recreate an actual slot machine. This slot machine has 72 possibilities on each reel. I set the payout for the combinations in the slot machine. This slot machine should have a payback of 95.13% if it were perfectly random. After several million spins, my code keeps coming back with like 99%. WAAAY out of tolerance. With that many spins, it should be plus or minus .4%. I kept double checking my code over and over for the past week. I figured there had to be an error in the pay table somewhere. Finally, i decided to iterate over every possible combination. 373,248 spins later, it came back with 95.13% exactly like it should. So, the problem is not with my pay table. It is with the randomness of it

the important bit of code i am using is:

R1=random.randint(1,72)

R2=random.randint(1,72)

R3=random.randint(1,72)



Assign a consistent random number to id in SAS across datasets

I have two datasets data1 and data2 with an id column. I want to assign a random id to each id, but this random number needs to be consistent across datasets. (rand_id for id=1 must be the same in both datasets). The objective is to get:

id rand_id
1 0.4212
2 0.5124
3 0.1231
id rand_id
1 0.4212
3 0.1231
2 0.5124
4 0.9102

I thought

DATA data1;
SET data1;
CALL STREAMINIT(id);
rand_id=RAND('uniform');
RUN;

and the same for data2 would do the job, but it does not. It just takes as seed the first id and generates a sequence of random numbers. From the STREAMINIT documentation, it seems it's only called once per data setp. I'd like to be called it in every row. Is this possible?




Returning collection of random elements from ArrayList using functional programming

Currently working on a card dealing project. I want a method that deals poker hands. It should randomly pick n(5) elements and return these in a collection(?). Also desired to use Random class to achieve randomness - school orders...

public ArrayList<PlayingCard> dealHand(int n){
        ArrayList<PlayingCard> hand = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            PlayingCard card = this.deck.get(random.nextInt(this.deck.size()));
            if (!hand.contains(card)){
                hand.add(card);
            }
        }
        return hand;
    }

Assignment: "Create a "dealHand (int n)" method in the DeckOfCards class that randomly picks n cards from the deck and returns them in a collection. "N" is a number between 1 and 52 that is submitted as a parameter to the assign function. This feature can be used, for example, to draw n random cards from the deck. You again choose which class / interface from the Java library you use as the return type of the method."

How do I make this method fulfill the requirements mentioned earlier, using streams, filters and what not (functional programming and lambda)?

Thanks




'random' is not call callable error message; unable to print the value when number3 is not > than number1 [closed]

Create program called reallyrandom.py that has a function that takes in three arguments and prints one integer.

  • Your random seed should be set to 42.
  • The first argument should correspond to the size of a np.randint - values from 0 to 10.
  • The second is an integer that you will multiply the randint by.
  • The third argument is a value you will index the result of the multiplication by.

You will print the integer that was indexed as ‘Your random value is x’ where x = the result of the indexing.

The program should not crash if the third value is larger than the first; it should not print anything to the screen.

Code

import sys
import numpy
import random

numpy.random.seed(42)

number1 = int(sys.argv[1])
number2 = int(sys.argv[2])
number3 = int(sys.argv[3])


def randomized(a, b, c):
    arg1 = numpy.random.randint(0, 10, size=a)
    arg2 = arg1 * b
    return arg2[c]


if number3 > number1:
    pass
else:
    random_value = random(number1, number2, number3)
    print(f"Your random value is {random_value}")

randomized(number1, number2, number3)

Test Case Examples:

python3 reallyrandom.py 1 2 9 
python3 reallyrandom.py 44 3 17
python3 reallyrandom.py 77 -3 55
python3 reallyrandom.py 2 4 10 

Expected Output:

Your random value is 21
Your random value is -9

Error Message

'random' is not callable



Code will not print the random output to the screen when the third value is not greater than the first

Create program called reallyrandom.py that has a function that takes in three arguments and prints one integer.

  • Your random seed should be set to 42.
  • The first argument should correspond to the size of a np.randint - values from 0 to 10.
  • The second is an integer that you will multiply the randint by.
  • The third argument is a value you will index the result of the multiplication by.

You will print the integer that was indexed as ‘Your random value is x’ where x = the result of the indexing.

The program should not crash if the third value is larger than the first; it should not print anything to the screen.

Code

import sys
import numpy
import random

numpy.random.seed(42)

number1 = int(sys.argv[1])
number2 = int(sys.argv[2])
number3 = int(sys.argv[3])

def random(a, b, c):
    arg1 = numpy.random.randint(0, 10, size = a)
    arg2 = arg1 * b
    random_value = arg2[c]
    
if number3 > number1:
    pass
else:
    print(f"Your random value is {random_value}")
    random(number1, number2, number3)

Test Case Examples:

python3 reallyrandom.py 1 2 9 
python3 reallyrandom.py 44 3 17
python3 reallyrandom.py 77 -3 55
python3 reallyrandom.py 2 4 10 

Expected Output:

Your random value is 21
Your random value is -9



Random shapes of haing equal area using Bezier curve

I am trying to generate random shapes of equal areas. I am following another post where random shapes are created https://stackoverflow.com/a/50751932/11078529

Is it possible to put a constraint like equal surface area while generating shaped using Bezier curve.




mercredi 16 mars 2022

How to get previous Tkinter value to delete when user clicks a button and generate a new value?

from tkinter import *
import random as r
from collections import Counter

root = Tk()
root.title("Simple Mafs")
root.geometry("600x400")
root.resizable(False, False)


def open_gn():
    gn_wn = Tk()
    gn_wn.title("Simple Mafs - Generate a number")
    gn_wn.geometry("600x400")
    gn_wn.resizable(False, False)

    Label(gn_wn, text='                                                      ').grid(row=0, column=0)
    inst_gn = Label(gn_wn, text='Enter a minimum and maximum value(below 100)')
    inst_gn.config(font=("Yu Gothic UI", 12))
    inst_gn.grid(row=0, column=1)

    Label(gn_wn, text=" Enter a minimum value: ").place(x=295, y=100)
    entry_min = Entry(gn_wn)
    entry_min.insert(0, "0")
    entry_min.place(x=450, y=100)

    Label(gn_wn, text=" Enter a maximum value: ").place(x=295, y=200)
    entry_max = Entry(gn_wn)
    entry_max.insert(0, "99")
    entry_max.place(x=450, y=200)

    Label(gn_wn, text="Random value is: ").place(x=40, y=40)

    def generate_number():
        min_ = int(entry_min.get())
        max_ = int(entry_max.get())

        random_num = r.randint(min_, max_)
        d_rn = Label(gn_wn, text=random_num)
        d_rn.config(text=random_num, font=("Yu Gothic UI", 30))
        d_rn.place(x=40, y=100)

    Button(gn_wn, text="Generate", padx=220, pady=25, command=generate_number).place(x=25, y=280)

    gn_wn.mainloop()


def open_coin():
    c_wn = Tk()
    c_wn.title("Simple Mafs - Flip a Coin")
    c_wn.geometry("600x400")
    c_wn.resizable(False, False)

    Label(c_wn, text="                                                                                ").grid(row=0,
                                                                                                              column=0)
    Label(c_wn, text="Flip the coin below!", font=("Yu Gothic UI", 12)).grid(row=0, column=1)

    Label(c_wn, text='                    ').grid(row=1, column=1)

    coin_label = Label(c_wn, text="")
    coin_label.place(relx=0.5, rely=0.2, anchor='s')

    def flip():
        coin_values = ["Heads", "Tails"]
        coin_face = r.choice(coin_values)
        if coin_face == "Heads":
            coin_label.config(text="Coin: Heads")
        else:
            coin_label.config(text="Coin: Tails")

    coin = Button(c_wn, text='coin', padx=100, pady=90, command=flip)
    coin.place(relx=0.5, rely=0.5, anchor=CENTER)

    c_wn.mainloop()


def open_average():
    avg_wn = Tk()
    avg_wn.title("Simple Mafs - Averages")
    avg_wn.geometry("840x300")

    Label(avg_wn, text="              ").grid(row=0, column=0)
    avg_instruct = Label(avg_wn, text="Enter your values below to get the averages in mean, median, and mode(put a "
                                      "space between commas")
    avg_instruct.config(font=("Yu Gothic UI", 10))
    avg_instruct.grid(row=0, column=1)

    Label(avg_wn, text="                                     ").grid(row=1, column=0)
    entry = Entry(avg_wn)
    entry.grid(row=2, column=1)

    def calculate():
        list_data = entry.get().split(', ')
        list_data = [float(i) for i in list_data]
        mean = sum(list_data) / len(list_data)
        Label(avg_wn, text='Mean').grid(row=5, column=0)
        Label(avg_wn, text=str(mean)).grid(row=6, column=0)

        list_data_len = len(list_data)
        list_data.sort()

        if list_data_len % 2 == 0:
            median1 = list_data[list_data_len // 2]
            median2 = list_data[list_data_len // 2 - 1]
            median = (median1 + median2) / 2
        else:
            median = list_data[list_data_len // 2]
        Label(avg_wn, text='Median: ').grid(row=5, column=1)
        Label(avg_wn, text=median).grid(row=6, column=1)
        list_data_for_mode = Counter(list_data)
        get_mode = dict(list_data_for_mode)
        mode = [k for k, v in get_mode.items() if v == max(list(list_data_for_mode.values()))]

        if len(mode) == list_data_len:
            get_mode = ["No mode found"]
        else:
            get_mode = [str(i) for i in mode]

        Label(avg_wn, text="Mode: ").grid(row=5, column=2)
        Label(avg_wn, text=get_mode[0]).grid(row=6, column=2)

    Label(avg_wn, text="                                     ").grid(row=3, column=0)

    Button(avg_wn, text='Enter', command=calculate).grid(row=4, column=1)


def rand_stat():
    pass


Label(root, text="                                           ").grid(row=0, column=0)

title = Label(root, text="Welcome to Simple Mafs")
title.config(font=("Yu Gothic UI", 24))
title.grid(row=0, column=1)

button1 = Button(root, text="Generate a random number", padx=80, pady=25, command=open_gn)
button1.place(x=2.25, y=100)

button2 = Button(root, text="Calculate mean, mode, median, and range", padx=20, pady=25, command=open_average)
button2.place(x=325, y=100)

button3 = Button(root, text="Flip a Coin", padx=125, pady=25, command=open_coin)
button3.place(x=2.25, y=200)

button4 = Button(root, text="Calculator", padx=105, pady=25, command=rand_stat)
button4.place(x=325, y=200)

root.mainloop()

Skip to the open_gn() one because that's where the problem is. I want to make an app that can do statistics/random related stuff and in it, I want to create an app that can generate a random number. The app generates the number but the previous value stays and interferes with the current number being generated.