mercredi 30 novembre 2022

How can I generate pseudo random sequence of binary number using Hopefield neural network?

For some work, I need to generate a sequence of random binary patterns using the Hopefield neural network. Like I want to generate a 42-bit long binary sequence such as '11101100011100111001100011001110001010001' How can I generate it?

I have tried several ways but no proper solution is coming out.




Random intercept random slope vs Random intercept model

I had a question regarding the comparison between random intercept and random slope model. I wondel why the AIC and BIC of the random intercept and random slope is better than the random intercept while the variation of the random intercept and random slope model is trivial and the correlation between random intercept and random slope is high. I have to say in theis model the log form of the outcome is used.

enter image description here

enter image description here fhsfh




A simple way to generate a sequence of doubles within a given range? DoubleStream

I'm trying to generate an infinite sequence of doubles between 0.5, and 0.8 utilizing the DoubleStream, but I'm not sure how to do the range part?

I currently have something like this ->

public static final DoubleStream generate = DoubleStream.generate(Math::random);



Random name from select database with variable [closed]

I have a problem of randomizing the names from a Mysql select, I tried with the RAND() function but with variable it gives me an error:

$sql_recup = "SELECT name, FROM `family` ORDER BY RAND() LIMIT 1 AND WHERE `family_id` = '" . $rows_block['id_yes'] . "'";

$result_recup = mysqli_query($db, $sql_recup);

$rows_recup = mysqli_fetch_assoc($result_recup);

trying on phpMyAdmin SELECT * FROM family ORDER BY RAND() LIMIT 1; so it works great, but putting the variable I can not figure out where I'm wrong. Thank you




mardi 29 novembre 2022

pick elements from the list randomly in uniform distribution without replacement

I have a list that ranges from 0 to 30

arr = range(0,30)

I need to pick a sample of "m" elements from the list using uniform distribution without replacement. I used random.uniform() which gives the random value in float.

Can anyone tell me how to pick the "m" elements from the given list randomly using uniform distribution without replacement?




Why in CPP in some system the RAND_MAX is set to 32K while in others it is 2147483647

In my CPP system whenever I generate a random number using rand() I always get a value between 0-32k while in some online videos and codes it is generating a value between 0-INT_MAX. I know it is dependent on RAND_MAX. So it there some way to change this value such that generated random number are of the range 0-INT_MAX Thanks in advance for the help :)

#include<bits/stdc++.h>
using namespace std;

int main(){
    srand(time(NULL));
    for(int i=1;i<=10;i++){
        cout << rand() << endl;
    }
}

I used this code and the random number generated are 5594 27457 5076 5621 31096 14572 1415 25601 3110 22442

While the same code on online compiler gives 928364519 654230200 161024542 1580424748 35757021 1053491036 1968560769 1149314029 524600584 2043083516




Using Random Choice From Dictionary to Make An Image Appear?

Some preface:

I am using trinket. I am trying to make a tarot reading program for class. Using a nested dictionary, I have the name of each card, the facing of each card, and then a short (3-4 words) reading that is then outputted as a template for the user.

Example of nested dictionary:

card_names = {
"The Fool" : {"Up": "new beginnings, pleasure, & opportunity" , "Down" : "indecision, hesitation, & bad choices" }, 
  "The Magician" : {"Up" : "creativity, self-confidence, & skill" , "Down" : "delay, insecurity, & lack of self-confidence" }

I then use the random.choice function to generate both a card and it's facing, like so:

  card = random.choice(list(cards.card_names))
  facing = random.choice(list(cards.card_names[card]))

Then it outputs a reading based on answers users put in & the randomly generated card:

print(__main__.answer_list[0] + ", your past was represented by " + random.choice(list(cards.card_names)) + ", which is facing " + random.choice(list(cards.card_names[card])) + "." " This tells me that your past relationships brought " + (cards.card_names[card][facing]) + " into your life.")
  

it ends up looking something like in output: "

Em, your past was represented by The Chariot, which is facing Up. This tells me that your past relationships brought misery, greedy, & money into your life.

Now that I have the program actually working, I want to make it so that the random.choice cards that are chosen will actually show to the user, using files such as "tarot-fool.jpeg".

I made a second dictionary that looked like this:

card_images = {"The Fool": "tarot-fool.jpeg", "The Magician": "tarot-magician.jpeg"}

I hoped that I could have the program take the random.choice generated card from the card_names dictionary , parse the second dictionary for matches, and then once it found the card with matching keys, it would output the value of the second dictionary card_images, and then use the screen.bgpic() function to show users the card while they read their tarot reading output.

I tried something similar to this:

namesset = set(card_names)
imageset = set(card_images)

for name in namesset.intersection(card_images):
print name, card_images[name]

I also tried

card = random.choice(list(cards.card_names))
facing = random.choice(list(cards.card_names[card]))
key = card
key2 = cardimages.key()
value = cardimages.value()

if key in key2:
print value

just to see if I could get the program to isolate the correct value from card_images before I start trying to get them to show on screen, but I am unable to get the program to isolate the randomly selected card, remember it, and then parse the second dictionary for just that value. The code above works, but outputs every single name of every single .jpeg.

Please help! I honestly think this is something a little too complex to be using trinket for, especially with the images component. I have some experience coding outside of it but this is for a class project that we HAVE to turn in with trinket so if someone could either help me out or just tell me if this is not achievable through trinket so I can change direction a bit, it would be much appreciated.

see above for what I've tried




Why does changing the kernel_initializer lead to NaN loss?

I am running an advantage actor-critic (A2C) reinforcement learning model, but when I change the kernel_initializer, it gives me an error where my state has value. Moreover, it works only when kernel_initializer=tf.zeros_initializer().

 state =[-103.91446672 -109.            7.93509779    0.            0.
    1.        ]

The model

class Actor:
    """The actor class"""

    def __init__(self, sess, num_actions, observation_shape, config):
        self._sess = sess

        self._state = tf.placeholder(dtype=tf.float32, shape=observation_shape, name='state')
        self._action = tf.placeholder(dtype=tf.int32, name='action')
        self._target = tf.placeholder(dtype=tf.float32, name='target')

        self._hidden_layer = tf.layers.dense(inputs=tf.expand_dims(self._state, 0), units=32, activation=tf.nn.relu, kernel_initializer=tf.zeros_initializer())
        self._output_layer = tf.layers.dense(inputs=self._hidden_layer, units=num_actions, kernel_initializer=tf.zeros_initializer())
        self._action_probs = tf.squeeze(tf.nn.softmax(self._output_layer))
        self._picked_action_prob = tf.gather(self._action_probs, self._action)

        self._loss = -tf.log(self._picked_action_prob) * self._target

        self._optimizer = tf.train.AdamOptimizer(learning_rate=config.learning_rate)
        self._train_op = self._optimizer.minimize(self._loss)

    def predict(self, s):
        return self._sess.run(self._action_probs, {self._state: s})

    def update(self, s, a, target):
        self._sess.run(self._train_op, {self._state: s, self._action: a, self._target: target})


class Critic:
    """The critic class"""

    def __init__(self, sess, observation_shape, config):
        self._sess = sess
        self._config = config
        self._name = config.critic_name
        self._observation_shape = observation_shape
        self._build_model()

    def _build_model(self):
        with tf.variable_scope(self._name):
            self._state = tf.placeholder(dtype=tf.float32, shape=self._observation_shape, name='state')
            self._target = tf.placeholder(dtype=tf.float32, name='target')

            self._hidden_layer = tf.layers.dense(inputs=tf.expand_dims(self._state, 0), units=32, activation=tf.nn.relu, kernel_initializer=tf.zeros_initializer())
            self._out = tf.layers.dense(inputs=self._hidden_layer, units=1, kernel_initializer=tf.zeros_initializer())

            self._value_estimate = tf.squeeze(self._out)
            self._loss = tf.squared_difference(self._out, self._target)

            self._optimizer = tf.train.AdamOptimizer(learning_rate=self._config.learning_rate)
            self._update_step = self._optimizer.minimize(self._loss)

    def predict(self, s):
        return self._sess.run(self._value_estimate, feed_dict={self._state: s})

    def update(self, s, target):
        self._sess.run(self._update_step, feed_dict={self._state: s, self._target: target})

The problem is that I need the learning process to be improved. So, I thought if I changed the kernel_initializer, it might improve, but it gave me this error message.

 action = np.random.choice(np.arange(lenaction), p=action_prob)
      File "mtrand.pyx", line 935, in numpy.random.mtrand.RandomState.choice
    ValueError: probabilities contain NaN

Any Idea what causing this?




How to validate random choice within Python?

I've been trying to make this dumb little program that spits out a random quote to the user from either Kingdom Hearts or Alan Wake (both included in .txt files) and I've hit a snag. I've made the program select a random quote from either of the text files (residing in lists) and to finish I just need to validate whether the user input matches the random selection.

import os
import sys
import random

with open(os.path.join(sys.path[0], "alanwake.txt"), "r", encoding='utf8') as txt1:
    wake = []
    for line in txt1:
        wake.append(line)

with open(os.path.join(sys.path[0], "kh.txt"), "r", encoding='utf8') as txt2:
    kh = []
    for line in txt2:
        kh.append(line)

random_kh = random.choice(kh)
random_wake = random.choice(wake)
choices = [random_kh, random_wake]
quote = random.choice(choices)

print(quote)
print("Is this quote from Kingdom Hearts or Alan Wake?")
inp = input().lower()

This is what I've got so far. I did try something like:

if quote == choices[0] and inp == "kingdom hearts":
    print("Correct!")
if quote == choices[1] and inp == "alan wake":
    print("Correct!")
else:
    print("Incorrect")

But found that it just always printed as incorrect. Any help would be appreciated! I'm very new to programming.




lundi 28 novembre 2022

Optimized algorithm to generate a series of random numbers without repeats? [duplicate]

I need to implement an algorithm that will generate random numbers, take into account already generated numbers, and discard them.

For example:

  • We have a series of integers from 1 to 10
  • At the first generation of a random number in a given range, we get 3
  • Next, we should get a number from 1 to 2 or from 4 to 10
  • During the second random number generation, we get 7
  • Next, we should get a number from 1 to 2 or from 4 to 6 or from 8 to 10
  • And so on until we have generated all the numbers from the original range

Naive implementation:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

var numbersForRandom []int
var min, max int

func main() {
    // This will show the generation of numbers from 0 to 9 for simplicity
    numbersForRandom = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    min, max = 0, len(numbersForRandom)-1

    rand.Seed(time.Now().UnixNano())

    generatedNumbers := make([]int, 0)
    for len(generatedNumbers) < len(numbersForRandom) {
        generatedNumbers = GenerateRandomWithoutRepeats(generatedNumbers)
    }

    fmt.Println(generatedNumbers)
}

func GenerateRandomWithoutRepeats(generatedNumbers []int) []int {
    result := rand.Intn(max-min+1) + min

    for _, i := range generatedNumbers {
        if result == i {
            return generatedNumbers
        }
    }

    return append(generatedNumbers, result)
}

Link to this code on Go Playground: https://go.dev/play/p/wSj6nuOCtBN
Is there an algorithm that optimizes the solution of this problem?




How to shuffle data frame entries in R

I have a data frame with dimension 24,523x3,468 and I want to shuffle the entries of this dataframe. For example, I have a simple data frame

df <- data.frame(c1=c(1, 1.5, 2, 4), c2=c(1.1, 1.6, 3, 3.2), c3=c(2.1, 2.4, 1.4, 1.7)) 
df_shuffled = transform(df, c2 = sample(c2))

It works for one column, but I want to shuffle all column, or all rows. I tried

col = colnames(df)
for (i in 1:ncol(df)){
  df2 = transform(df, col[i] = sample(col[i]))
}
df2

It will produce an error like this

error

I have tried this too to shuffle, but it only shuffles rows and columns

df_shuf = df[sample(rownames(df), nrow(df)), sample(colnames(df), ncol(df))]
df_shuf

shuffle

How can I shuffle the entries of the data frame df using a loop for I by rows and columns?




dimanche 27 novembre 2022

How do I print Not Available instead of a price with a 50% chance?

I have this buy and sell game and on of its functions is to list down the items and its randomized prices. I want it to have a 50 percent chance to show "NOT AVAILABLE" while the other 50 percent, it will show the randomized price. Also, did I randomize ir correctly? there needs to be a 50 perccent chance of showing either the text or the price. Thank you!

This is my code right now but I think there is a way to simplify it more and a way for me to not code it like this.

if((pItem1 = rand() % (70000 - 40000 + 1) + 40000) % 100 > 50)
    {    printf("ITEM 1                                       %dG\n", pItem1);}
else
    {    printf("ITEM 1                                   NOT AVAILABLE\n");}



How can I get the eigenvectors and eigenvalues of the matrix and ordering them by `lambda_1

I use the following code to get a random matrix (normalized GOE) in Python:

pip install scikit-rmt

from skrmt.ensemble import GaussianEnsemble

# sampling a GOE matrix of size 1000x1000
goe = GaussianEnsemble(beta=1, n=1000)
# plotting its spectral distribution in the interval (-2,2)
goe.plot_eigval_hist(bins=80, interval=(-2,2), density=True)

But how can I get the eigenvectors and eigenvalues? And ordering them by lambda_1<lambda_2<...<lambda_n and their eigenvectors.


I try to use

from numpy.linalg import eig
l, v=eig(goe)

But it shows that LinAlgError: 0-dimensional array given. Array must be at least two-dimensional




How to make a random vector in R?

I need to create a vector of random integers with randomised lenght WITHOUT limits. Is there any way I can do it?

I tried sample(), but it seems tk require set limits




samedi 26 novembre 2022

How to get a random 4 digit number from a digit range 1-6

From a range of [1,2,3,4,5,6] how can I get a random 4 digit number .

Example - 2451




Random employee generator

i am currently working on a program that randomly generates first names, last names, date of birth, working hours for a certain number of employees. I'm stuck on not knowing how to write out a nice clear output. For example :

const dtoOut = [
  {
    gender: "male",
    birthdate: "1993-08-07T00:00:00.000Z",
    name: "John",
    surname: "Doe",
    workload: 40
  },

Next, I need to write the date of birth by min and max age, but but I need to put it on the input and not on the console.log


function getRandomDate(startDate, endDate) {
    const minValue = startDate.getTime();
    const maxValue = endDate.getTime();
    const timestamp = Math.floor(Math.random() * (maxValue - minValue + 1) + minValue);
    return new Date(timestamp);
}

console.log(getRandomDate(new Date(1987,0,1), new Date(2003,11,31)));

Here is the full program :


const females = ["LIST OF FEMALE NAMES"]

const males = ["LIST OF MALE NAMES"]

const maleSurname = ["LIST OF MALE SURNAMES"]

const femaleSurname = ["LIST OF FEMALE SURNAMES"]

const gender = ["male", "female"];

const workload = ["10","20","30","40"];

var count = (10);

const dtoIn = {};

function main (dtoIn,dtoOut){


    let randomDateOfBirth =  {}; // -..-    


}


while (count > 0){
const randomGender = [Math.floor(Math.random() * gender.length)];  

console.log(gender[randomGender])
const randomWorkload = [Math.floor(Math.random() * workload.length)];  
console.log(workload[randomWorkload])



    if (gender[randomGender] === "female") {
    
        const randomFemaleName = [Math.floor(Math.random() * females.length)];
        const randomFemaleSurname = [Math.floor(Math.random() * femaleSurname.length)];
        
        console.log(females[randomFemaleName])
        console.log(femaleSurname[randomFemaleSurname])
        count = count - 1;

    }

    else {
        
        const randomMaleName = [Math.floor(Math.random() * males.length)];
        const randomMaleSurname = [Math.floor(Math.random() * maleSurname.length)];
        
        console.log(males[randomMaleName])
        console.log(maleSurname[randomMaleSurname])
        count = count - 1;
}
}


Thanks you for every help .. David.

So if someone could possibly help me out i will pay with gold, if i have some LMAO . :D




Recursion function, random choices with probability from list

I need to make a simulator which makes, for the input list, a list (elements are random choices from rdm_lst) of lists. I have:

lst = ["a", "a", "a"]
rdm_lst = ["a", "b", "c"]

def simulator(lst, rdm_lst):
    sim = []
    for i in lst:
        if i == "a":
            sim.append(np.random.choice(rdm_lst, size=1, p=[0.6, 0.2, 0.2]).tolist()[0])
        elif i == "b":
            sim.append(np.random.choice(rdm_lst, size=1, p=[0.2, 0.6, 0.2]).tolist()[0])
        elif i == "c":
            sim.append(np.random.choice(rdm_lst, size=1, p=[0.2, 0.2, 0.6]).tolist()[0])
    return sim

simulator(rdm_lst)

The output is one list, the problem I have is, that I do not know how to repete this function k time, having as a result list of lists, where the input of a simulator() will be the previous list, not the first one. I tried, put:

return simulator(sim)

instead:

return sim

bun an error occurs. Kindly help.




vendredi 25 novembre 2022

How to sample normalized GOE and get their eigenvectors with ordering?

In Mathematica, I can sample a n=1000 normalized Gaussian Orthogonal Ensemble GOE matrix:

n = 1000; m = 
 RandomVariate[
  GaussianOrthogonalMatrixDistribution[Sqrt[2]/Sqrt[n], n]]; 

And I can get eigenvectors and eigenvalues and ordering them:

{eval, evec} = Eigensystem[m];
imin = Ordering[eval, 1][[1]];
lambda2minlambda1 = Sort[eval][[2]] - Sort[eval][[1]];

How can do this one in Python?

pip install scikit-rmt

# sampling a GOE matrix of size 1000x1000
n=1000
goe = GaussianEnsemble(beta=1, n=n)
# plotting its spectral distribution in the interval (-2,2)
goe.plot_eigval_hist(bins=80, interval=(-2,2), density=True)

But I am not sure if it is normalized. And how to get the eigenvalues and order them?




jeudi 24 novembre 2022

Exclude certain numbers from a range of random numbers in JavaScript [duplicate]

I am trying to generate random numbers. I do it like this:

function getRandom(min, max) {
        return  Math.random() * (max - min) + min;
}

I'm trying to get a number in the range from 0 to 100. Excluding the range from 40 to 60 from the answer How to do it?




Calling shortcode from within shortcode in Wordpress

I'm using a php plugin in wordpress that allows you to shortcode php and have it post. My PHP script then calls a random line from a text file. In this file, I want there to be another call on some lines that pull from yet another file, or run a shortcode themselves. Issue is, I run the first shortcode, and it posts the 1st lv just fine, but the codes then in that one don't post. Is there a way to have random lines in a file echoed, that also can pull random lines? (or call a shortcode)

The code stored in XYZ PHP SNIPPIT, in shortcode [stage1]

<?php
$file = "scenarios.txt";
$file_arr = file($file);
$num_lines = count($file_arr);
$last_arr_index = $num_lines - 1;
$rand_index = rand(0, $last_arr_index);
$rand_text = $file_arr[$rand_index];
echo $rand_text;
?>

in the scenarios file it has something like, say "[person1] and [person2] go for a walk" with both of those being shortcodes for other php list calls. the issue is, it just shows the [person1] and doesn's call the shortcode. So I also tried making the lines more like this:

<?php echo do_shortcode('[person1]'); ?> and <?php echo do_shortcode('[person2]'); ?> go for a walk

Again it calls up the first Scenario short code, but the person1/2 ones end up just showing blank and not being called up. How do I embed layers of shortcode or php shortcode calls in wordpress?




How to place 5 ships randomly in a list of 20 positions for battleship game?

I need to put 5 ships randomly (numbers 1 to 5 witout repetition) in a list of 20 positions. I need to place a 0 where no ships are placed. e.g Please, I'm stuck here!

for (int i = 0; i < barcosComputadora.length; i++) {
            if (i > 0) {
                barcosComputadora[i] = rnd.nextInt(6);

            }
        }
    

    static void imprimirArreglo(int[] pValores) {
        for (int i = 0; i < pValores.length; i++) {
            out.print(pValores[i] + "\t");
        }
    }

    public static void main(String[] args) throws Exception {
        int tam = 20;

        // tam = rnd.nextInt(20);
        int barcosComputadora[] = new int[tam];
        inicializarBarcosComputadora(barcosComputadora);
        out.println("\nValores del arreglo: ");
        imprimirArreglo(barcosComputadora);
    }


I got something like this:

0       0       5       2       2       0       2       2       5       2       1       0       0       4       5       3       0       0       3       4



How to return one item from this list?

I need to use the nextInt method of Random to select and return one item from the list. I need the method to return any of the strings in the list, regardless of the size of the list. However, the list will always have at least one item in it.

Here is my method at the moment but it gives me errors that variable choices is already defined in this method and variables ArrayList and String are undeclared.

    /**

    * Return a random one of the strings in the given list.

    * The list will have at least one item in it.

    * @param choices A list of strings.

    * @return One of the strings in the given list.

    */

    public String chooseOne(ArrayList<String> choices)

    {

    Random rand = new Random();

    ArrayList<String>choices;

    return rand.nextString(ArrayList<String>choices);



Display only one gameobject from list

I have 3(A) game object I want when game start to display random only one another to hide,

enter image description here

I tried below code but is only change position please help

    public GameObject player;
   public float placex;
   public float placez;
   private void Start() {
    placex=Random.Range(209,-70);
    placez=Random.Range(-179,108);

    player.transform.position=new Vector3(placex,0,placez);
   }



Nonzero for integers

My problem is as follows. I am generating a random bitstring of size n, and need to iterate over the indices for which the random bit is 1. For example, if my random bitstring ends up being 00101, I want to retrieve [2, 4] (on which I will iterate over). The goal is to do so in the fastest way possible with Python/NumPy.

One of the fast methods is to use NumPy and do

bitstring = np.random.randint(2, size=(n,))
l = np.nonzero(bitstring)[0]

The advantage with np.non_zero is that it finds indices of bits set to 1 much faster than if one iterates (with a for loop) over each bit and checks if it is set to 1.

Now, NumPy can generate a random bitstring faster via np.random.bit_generator.randbits(n). The problem is that it returns it as an integer, on which I cannot use np.nonzero anymore. I saw that for integers one can get the count of bits set to 1 in an integer x by using x.bit_count(), however there is no function to get the indices where bits are set to 1. So currently, I have to resort to a slow for loop, hence losing the initial speedup given by np.random.bit_generator.randbits(n).

How would you do something similar to (and as fast as) np.non_zero, but on integers instead?

Thank you in advance for your suggestions!




mercredi 23 novembre 2022

Quasi Random Number generation Scatter plot

Require python code for Quasi random number generation scatter plot. Tried this method but getting name not found error as shown below error code code I tries to obtain quasi random number generator scatter plot. But got name not found error as shown in above images




Replace Items in List with Random Items from Dictionary of Lists

I have a list of items that may repeat multiple times. Let us say for example

list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a']

I also have a dictionary of lists that defines multiple values for each key. Suppose:

dict = {'a':[1, 2], 'b':[3, 4], 'c':[5, 6], 'd':[7, 8]}

I want to be able to:

  1. randomly select a value from the dictionary where the key is equal to the value in the original list, and

  2. have this value be randomly selected at each key occurrence in the list.

I attempted to use Pandas to create a DataFrame from my list and leverage pd.Series.map() to randomly map my dictionary like in the following:

df = pd.DataFrame(list, index = [0,1,2,3,4,5,6,7], columns = ['Letters'])
df['Random_Values'] = df['Letters'].map({k:random.choice(v) for k,v in dict.items()})

Output:

         Letters      Random_Values
    0       a              1
    1       b              3
    2       c              5
    3       d              7
    4       b              3
    5       a              1
    6       c              5
    7       a              1

This code is successful in randomly selecting a value where the key matches, but it currently randomly selects the same value for every key (i.e., all instances of 'a' will always be 1 or 2, not a mixture).

How can I alter this code to randomly select the values each time the key is matched? Any advice appreciate, Pandas not essential -- if you have a better way with just lists I want to hear it!




mardi 22 novembre 2022

Python - Random.sample from a range with excluded values (array)

I am currently using the random.sample function to extract individuals from a population.

ex:

n = range(1,1501)

result = random.sample(n, 500) print(result)

in this example I draw 500 persons among 1500. So far, so good..

Now, I want to go further and launch a search with a list of exclude people.

exclude = [122,506,1100,56,76,1301]

So I want to get a list of people (1494 persons) while excluding this array (exclude)

I must confess that I am stuck on this question. Do you have an idea ? thank you in advance!

I am learning Python language. I do a lot of exercise to train. Nevertheless I block ue on this one.




Draw sample from "binned" distribution in R

Suppose I have a vector of counts binned into classes i=1...k, i.e.

v = c(n_1, n_2, ... n_k)

for a total N = Sum n_i. I want to sample n < N without replacement. The naive approach to this is to use v to create a vector vnew with n1 1's, n2 2's, ... nk k's, and then apply

s1 = sample(vnew, n)
t1 = table(s1)

and then re-bin.

Surely there is a simpler way to do this in R. It's basically down-sampling, but with respect to a single distribution and a specified sample size (rather than two distributions).




How can I generate a random string, out of a pre prepared list of strings in C#?

I need to generate a random string from a pool of 6 pre-generated strings. I created a list, but I don't understand how to use "random" to generate one random string out of that list.

This is what I have so far:

string RandomPowerSentence()
{
    Random rnd = new Random();
  
    List<string> powerStrings = new List<string>()
    {
        "You are kind!",
        "You are beautiful!",
        "You are smart!",
        "You are awesome!",
        "You are funny!",
        "You're a f*cking A!"
    };

    //I assume that here I put the code that generates a random string out of the list with rnd
    

    return  "the random string from the list";

Help will be very appreciated!

I used the random class, but I don't understand/know how to use it with strings and not ints.




Creating a Random Harry Potter Quote Discord Bot in CPP (DPP)

I just have a general question.

I'm trying to create a discord bot that responds to slash commands and the book title within the Harry Potter series (e.g /Prince of Azkaban) and it will generate a random quote from the book to the channel (it would be nice to have it display a random image from the movie scene it derived the quote from ...but.... that seems too complicated lol).

I've set up the default discord bot that is within the set-up articles (/ping and get ping pong!--------that is embedded down below) but I actually have no idea where to start.

Should I be starting with creating the random generator and then later on finding out how to link it so random quotes can be chosen (i.e a text doc?) or should I figure out where/how I am going to get the book quotes?

Any help is appreciated on how to start!

`

#include "MyBot.h"
#include <dpp/dpp.h>

/* Be sure to place your token in the line below.
 * Follow steps here to get a token:
 * https://dpp.dev/creating-a-bot-application.html
 * When you invite the bot, be sure to invite it with the 
 * scopes 'bot' and 'applications.commands', e.g.
 * https://discord.com/oauth2/authorize?client_id=940762342495518720&scope=bot+applications.commands&permissions=139586816064
 */
const std::string    BOT_TOKEN    = "MY TOKEN";

int main()
{
    /* Create bot cluster */
    dpp::cluster bot(BOT_TOKEN);

    /* Output simple log messages to stdout */
    bot.on_log(dpp::utility::cout_logger());

    /* Handle slash command */
    bot.on_slashcommand([](const dpp::slashcommand_t& event) {
         if (event.command.get_command_name() == "ping") {
            event.reply("Pong!");
        }
    });

    /* Register slash command here in on_ready */
    bot.on_ready([&bot](const dpp::ready_t& event) {
        /* Wrap command registration in run_once to make sure it doesnt run on every full reconnection */
        if (dpp::run_once<struct register_bot_commands>()) {
            bot.global_command_create(dpp::slashcommand("ping", "Ping pong!", bot.me.id));
        }
    });
}

`




lundi 21 novembre 2022

Is there a way to make a random number matrix in R where all rows = a given value?

I am trying to make a dummy dataset to test a model I have built on real data. I want to make a matrix of 11 columns, each row of which sums to 100 as its percentage data.

I can make a sample matrix of the right dimensions, for example, 100 rows by 11 columns

set.seed(42) ranMat <- matrix(sample(seq(0:100), 1100, replace = TRUE), ncol = 11)

but I don't know where to start to ask it to make each row sum to 100.

The related examples I have found on stackoverflow are in languages I don't know (i.e. Python and Matlab), and so can't port over so to speak. Close, but not the same are for example this question but I don't want to take them from a normal distribution and I don't want negative numbers.




trying to guess letter in the randomly choosen cpu word from wordbank and return it

im trying to guess letter in the word and return it with "if letter in cpu_choice:" the desired output is you guess a letter thats in the cpus word and it will return if your guess is in the cpus word or not. sort of like hangman

 import random
test_list = ["apple", "bat","cow", "dog", "eat"]

print("Original list is : " + str(test_list))

cpu_choice=("Random letter is :", random.sample(test_list, 1))
print (cpu_choice)





userinput = input('chose a letter :')
for letter in userinput:
    if letter in cpu_choice:
            print("correct",cpu_choice.upper())
    else: 
            print ("incorrect",userinput) 
                

>> cpu_choice = apple 
>> userchoice = p 
>>print correct 


>> cpu_choice = apple 
>> userchoice = c 
>> print incorrect 



dimanche 20 novembre 2022

Filling 2D ARRAY with characters from string

I'm trying to fill an array with some selected characters from string. 2 columns have to stay empty, but this is how it's working for me. Every symbol should be equal to number of rows. Like ball sort game.. Some advice? Thanks.

void generator(const int rows, const int columns, char field[rows][columns]){  
    // seed
    srand(time(NULL));

    int random_index;

    // choosing empty columns (they'll be by side)
    int clear_column[2];
    // choosing random number in range of columns
    clear_column[0] = rand() % (columns+1);
    // adding +1 index to already choosen number
    clear_column[1] = clear_column[0]+1;
    // if choosen number is equal to number of columns => second empty column will be on the left side
    if ( clear_column[0] == columns)
    {
        clear_column[1] = clear_column[0]-1;
    }

    // variable to store all symbols 
    char store_symbol[10] = "^@#&*+-/$";
    // variable to store used symbols
    int store_index[10] = {0,0,0,0,0,0,0,0,0};
    
    

    // ** i = columns; k = rows

    // loops all columns
    for (int i = 0; i < columns; i++)
    {
        // loops all rows
        for (int k = 0; k < rows; k++)
        {
            // adding empty columns
            if ( i == clear_column[0] || i == clear_column[1])
            {
                field[k][i] = ' ';
            }
            else{
                int got_symbol = 0;
                while (got_symbol == 0)
                {
                    random_index = rand() % rows;

                    if ( store_index[random_index] <= rows)
                    {
                        field[i][k] = store_symbol[random_index];
                        store_index[random_index] += 1;
                        got_symbol = 1;
                        break;
                    }
                    
                }
                
            }
            
        }
        
    }

This is how it should look.

result




Setting a conditional for a random item selected from a list in Python

I'm working on a text-based Choose Your Own Adventure game in Python for an online class. The game has a list of random "villains" that you may encounter. The original project just has you going to the cave and finding a magical sword that you use to fight the villain. I wanted to set it so that the "weapon" would change according to whatever villian is selected randomly for the list. I listed the code I came up with (below), but it is not recognizing the choice of creature. Instead, it is returning the sword each time. What am I doing wrong?

import random
import time

creatures = ["wicked fairy", "gorgon", "troll", "dragon", "small child", "Karen", "ex-wife"]
weapons = ["Sword of Ogoroth", "Nintendo Switch", "social media", "alimony"]
creature = random.choice(creatures)
items = []

def print_pause(message):
    print(message)
    time.sleep(1)
    
def intro():
    print_pause("You find yourself standing in an open field, filled with grass and yellow wildflowers.")
    print_pause(f"Rumor has it that a {creature} is somewhere around here, and has been terrifying the nearby village.")
    print_pause("In front of you is a house.")
    print_pause("To your right is a dark cave.")
    print_pause("In your hand, you hold your trusty (but not very effective) dagger.")

def house_or_cave_choice():
    print_pause("Enter 1 to knock on the door of the house.")
    print_pause("Enter 2 to peer into the cave.")
    print_pause("What would you like to do?")
    user_choice = input("(Please enter 1 or 2.)\n")
    if user_choice == "1":
        house()
        house_choice()
    elif user_choice == "2":
        if "sword" in items:
            #if I go back into the cave a second time
            print_pause("You peer cautiously into the cave.")
            print_pause("You've been here before and gotten all the good stuff. It's just an empty cave now.")
            print_pause("You walk back out to the field.")
            house_or_cave_choice()
        else: 
            cave()
            house_or_cave_choice()
    else:
        house_or_cave_choice()

def house():
    print_pause("You approach the door of the house.")
    print_pause(f"You are about to knock when the door opens and out steps a {creature}.")
    print_pause(f"Eep! This is the {creature}'s house!")
    print_pause(f"The {creature} attacks you!")
    if "sword" or "Switch" or "phone" or "money" not in items:
        print_pause("You feel a bit under-prepared for this, what with only having a tiny dagger.")
        
    
def house_choice():
    fight_or_run = input("Would you like to (1) fight or (2) run away?\n")
    if fight_or_run == "1":
        if "sword" in items:
            #if user chooses to fight and already has gone to the cave and gotten the weapon
            print_pause(f"As the {creature} moves to attack, you unsheath your new sword.")
            print_pause("The Sword of Ogoroth shines brightly in your hand as you brace yourself for the attack.")
            print_pause(f"But the {creature} takes one look at your shiny new toy and runs away.")
            print_pause(f"You have rid the town of the {creature}. You are victorious!")
            play_again()
        elif "Switch" in items:
            #if user chooses to fight and already has gone to the cave and gotten the weapon
            print_pause(f"As the {creature} moves to attack, you pull out your new Nintendo Switch.")
            print_pause("The Switch shines brightly in your hand, and the game playing on the screen plays distracting sounds.")
            print_pause(f"The {creature} grabs your shiny new toy and runs away.")
            print_pause(f"You have rid the town of the {creature}. You are victorious!")
            play_again()
        elif "phone" in items:
            #if user chooses to fight and already has gone to the cave and gotten the weapon
            print_pause(f"As the {creature} moves to attack, you hold up your new phone, which is already live streaming.")
            print_pause("The phone is recording every word she is about to say.")
            print_pause(f"{creature} takes one look at phone and runs away.")
            print_pause(f"You have rid the town of the {creature}. You are victorious!")
            play_again()
        if "money" in items:
            #if user chooses to fight and already has gone to the cave and gotten the weapon
            print_pause(f"As the {creature} moves to attack, you pull out your fresh stack of cash.")
            print_pause("You have the money for your overdue alimony.")
            print_pause(f"Your {creature} grabs the cash and runs away.")
            print_pause(f"You have rid the town of the {creature} -- at least for this month. You are victorious!")
            play_again()
        else:
            #if user chooses to fight without having gone to the cave first
            print_pause("You do your best...")
            print_pause(f"But your dagger is no match for the {creature}.")
            print_pause("You have been defeated!")
            play_again()
    elif fight_or_run == "2":
        #if user chooses to run away
        print_pause("You run back into the field. Luckily, you don't seem to have been followed.")
        house_or_cave_choice()
    else: 
        #if user puts in something other than a '1' or '2'
        house_choice()
        

def play_again():
    play_again = input("Would you like to play again? (y/n)\n").lower
    if play_again == "y":
        #if user chooses to play again
        "Excellent! Restarting the game..."
        game()
    elif play_again == "n":
        #if user chooses not to play
        "Thanks for playing! See you next time."
        
    else:
        #if user chooses something other than 'y' or 'n'
        play_again()

def cave():
    print_pause("You peer cautiously into the cave.")
    print_pause("It turns out to be only a very small cave.")
    print_pause("Your eye catches a glint of something behind a rock.")
    if {creature} == "wicked fairy" or "gorgon" or "troll" or "dragon":
        print_pause("You find the magical Sword of Ogoroth!")
        print_pause("You discard your silly old dagger and take the sword with you.")
        print_pause("You walk back out to the field.")
        items.append("sword")
    elif {creature} == "small child":
        print_pause("You find a shiny new Nintendo Switch.")
        print_pause("You discard your silly old dagger and take the Switch with you.")
        print_pause("You walk back out to the field.")
        items.append("Switch")
    elif {creature} == "Karen":
        print_pause("You find a shiny new iPhone with a live stream already open on it.")
        print_pause("You discard your silly old dagger and take the phone with you, live streaming as you go.")
        print_pause("You walk back out to the field.")
        items.append("phone")
    else: 
        print_pause("You find a stack of fresh cash.")
        print_pause("You discard your silly old dagger and take the money with you.")
        print_pause("You walk back out to the field.")
        items.append("money")
    
def game():
    intro()
    house_or_cave_choice()
    
game()    




I tried using random choice and conditional statements.




How to get two random numbers with the same limit

I want to get two random numbers or variables respectively within the same range, taking into account that the sum of the two numbers does not exceed the limit imposed by Math.random(). How can I do that?

For example there are three million snowflakes that land randomly either on the roof or on the ground




Drawing trials from asymmetric error distribution (Numpy)

I'm running a quick Monte Carlo error analysis. One of the parameters I'm looking at has a non-Gaussian error distribution; let's say Log10[param] = 9.33 +0.21 -0.01. In NumPy, how would I draw trials from a distribution centered at the parameter representing these asymmetric errors?




Hi I cant export the random created data in Python to SQL

Hi below code create random the data but I am not able to move it to excel or sql how can I do it ?

#import modules
import pandas as pd
import numpy as np
import random

Disease_type = ['Covid']
vaccine_type = ['Sinovac','Pfizer','AstraZeneca','Jonson']
dose_number = [1]
dfs = []

#create loop to randomly generate data
for x in np.arange(50):
    df_tmp = pd.DataFrame({
        "Date": np.random.choice(pd.date_range('2021-01-01', '2021-12-31', freq='D')),
        "card_id": random.randrange(4168427,5168472),
        "latitude": random.uniform(40.00,41.00),
        "Longitute": random.uniform(40.70,48.59),
        "disease type": [random.choice(Disease_type)],
        "vaccine type": [random.choice(vaccine_type)],
        "Dose number": random.randrange(1,2)
    })

    dfs.append(df_tmp)

#print the data
df = pd.concat(dfs).set_index("Date")
print(df)



samedi 19 novembre 2022

Sort 100 random numbers with out using sort fuction

My son has a project that has not been taught so looking for some guidance how do you sort 1-100 random numbers from lowest to highest with out using sort I have no idea and it was never taught in the class he is taking

No idea where to start other than import random Or Ranint




Falling objects from random places in pygame

I want to make a program where objects fall from top of the screen and when reached bottom then turn left or right. Eventually then object in this case ball image is out of screen to the left or right. In other words to make objects fall like a rain drops and continue this until screen is closed. Here is my code so far:

import pygame
from random import randint

pygame.init()
width, height = 680, 480
display = pygame.display.set_mode((width, height))

clock = pygame.time.Clock()
ball = pygame.image.load("ball.png")
speed_y = 1

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           exit()  

    list_of_balls = []
    for t in range(10):
        x = randint(0, width-ball.get_width())
        y = 0-ball.get_height()
        list_of_balls.append((x, y))

    display.fill((0, 0, 0))
    for b in list_of_balls:
        display.blit(ball, b)
    pygame.display.flip()

    if y < height-ball.get_height():
        y += speed_y
    else:
        direction = randint(0, 1)
        if direction == 0:
            x += 1
        if direction == 1:
            x -= 1

    clock.tick(60)

I've tried to make a list of balls and then randomly make them fall.




How Can I randomly display/print/select 4 elements in a list without repetition in C#?

 
            List<string> topLevel = new List<string>();
            

          


            topLevel.Add("000");
            topLevel.Add("100");
            topLevel.Add("200");
            topLevel.Add("300");
            topLevel.Add("400");
            topLevel.Add("500");
            topLevel.Add("600");
            topLevel.Add("700");
            topLevel.Add("800");
            topLevel.Add("900");

I tried with while loops, for loops and LINQ, but got nothing to work




vendredi 18 novembre 2022

Error while using numpy random.normalvariate()

I tried to generate random probs by using the following line code:

probs = [np.clip(random.normalvariate(0.1, 0.05), 0, 1) for x in range(1000)]

Unexpectedly I faced the following error message:

AttributeError: module 'numpy.random' has no attribute 'normalvariate'

Any idea how to solve this? I checked out the docs I find that this attribute exists in the numpy.random however it doesn't work when I used it in above code.

Any help to fix this issue will be appreciated.




Counting probabilities based on a set of possible outcomes and previous outcomes

How do I calculate the probability of the RNG picking the next result from the set based on previous results? Are there any methods to analyse this type of RNG activity?

For example, we know the 50 possible options that the generator can choose and the last 10,000 results. I would like to calculate the probabilities for the next selection. Thanks for any help and suggestion.




How can a single (or multiple) number(s) from a randomly generated list be used separately with no repeating values in either set? [Python]

I am trying to separate a single number (or multiple) from a list of randomly generated list without any repeating values. This random list can be, for example, a range of 7 values from 1-45, then take one or more of those values from the list and use the same range but cannot be the same as the values inside the main list.

import random

rndList = []

rndList = random.sample(range(1,45), 7)
rndList.sort()
print("Some numbers...", rndList[0:6])
print("Separate number...", rndList[6])    

This will output a random and sorted list, e.g. [5,12,28,35,39,41] and the last separate value from the list, e.g. [43]. The problem is that the last number will always be greater than the previous whereas I need it to be between 1-45 but never use repeated values from the list.

Is it possible to select the separate value randomly from the list instead of creating another list? Appreciate the help!




jeudi 17 novembre 2022

Rnadomly allocate files to folders in python

I have a list with 200 unique identifiers and I want to randomly move this identifiers to different folders.

Each folder to contain 20 unique identifiers with 1 identifier appearing in other folders.

So say a folder 1 has 19 identifiers, I want to copy 1 identifier from folder 1 to folder 3 so that folder 3 to have 20 images.

Then I will copy one identifier from folder 2 which has 19 identifiers to folder 4 and the process continues like that upto the end.

The last folder being that it wont have any remaining folder to copy identifier to , I will copy identifier from last folder to folder one and that should complete the circle.

Here is how this identifiers look like:

list_ids = [04120, 04121,04125, 05100, 05101, ....]

Not that this process, I will just be copying identifiers from one folder to another, not moving them.

End result is each folder should have 20 identifiers but among the 20, one Identifier has been repeated from another folder.

folder structure : folder 1 - 20 ids (1 id repeated from another folder)
                   folder 2 - 20 ids (1 id repeated from another folder)
                   folder 3 - 20 ids (1 id repeated from another folder)
                   folder 6 - 20 ids (1 id repeated from another folder)
                   folder 5 - 20 ids (1 id repeated from another folder)

I am struggling on how to write a python code to randomly create this identifiers. Any help will be appreciated




Why am I not able to see the random numbers generated using python for large input values?

So I am trying to generate my own adjacency list using random.randint. I am not able to view the output.

Its just few values and then dots. I want to input these values into my algorithm. How to view these generated values.

This is the output I'am getting.

Thank you for your help!




beginner python on looping back to the start of my simple number guessing game

This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9. I am still trying to master thought & flow as well as loops, and I hit a roadblock:

import random


Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))


def number_game():
    if guess == random_num:
        print(f"You guessed right, the number is confirmed to be {random_num}.")
    else:
        print(f"You guessed the wrong number. Try again.\n")


number_game()

I called the function and ran the code... everything appears to be working except I really can't figure out how to keep the game going in a loop until the player gets the right number out of 1-9...and end it when I need to. I tried searching all my resources and am quite stuck on this beginner practice coding. Any help is appreciated.

What I wrote and tried is above... googling and stackoverflow just confused me more.




mercredi 16 novembre 2022

I'm trying to preview random photos on the site's share link

I used this function in js to open the variable in the head of the html, I don't know if there is a solution or if there is another way to do it.

function randomlink() {
  var links = new Array(3)
  links[0] = "https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr.jpeg"
  links[1] = "https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr0.jpeg"
  links[2] = "https://raw.githubusercontent.com/vonkoln/clubenoturno/clubenoturno/pr1.jpeg"
 

  var num = Math.round(Math.random() * 2))
}
randomlink()

In html <meta property="og:image" content=links[num]/>




The rand() function generate ridiculous numbers [closed]

I don't understand why rand() function is returning so ridiculous integers. The first 4 generated numbers seems to be ok, but what's going on after them?

There is fragment of code:

int i=0, j=0;
int tab[4][3];
srand(time(0));

    for(i;i<=3;i++) {
        for(j;j<=2;j++) {
            tab[i][j] = rand() % 50;
        }
    }


    for(i=0;i<=3;i++) {
        for(j=0;j<=2;j++) {
            printf("%d\t", tab[i][j]);
        }
        printf("\n");
    }

And the output is:

16      31      24
24      65535   -1068880744
-1068880744     65535   1358574848
1358574848      1323076347      -1068880848



mardi 15 novembre 2022

How to sample data in R, within specific amount of cases

I'm trying to resample data, but I don't know how to tell the "sample" function to do it within a condition or specific amount of cases.

The objective is to resample a statistic from a Wald test, balancing the amount of cases of two conditions: control vs the treatment, as the original data is unbalanced.

For this I have 48 "control_IDs" (corresponding to 228 observations across time), and 326 "treatments_IDs", corresponding to 4531 observations. The ID corresponds to the individual subject to the treatment or not.

Overall, one part of the structure is pretty straightforward, and I'm able with the attached code to sample 228 from the 4531 observations of my "treatment", to run the model and Wald test.

The problem that I have is that when I run the code, the 48 IDs of the "control" are fix, but the ones from the "treatment" are not. So I end with 228 observations of 48 control_IDs, but 228 observations of a varying amount of "treatment_IDs" (from ~60 to ~180) depending on the run.

Any idea of how to properly code that the random 228 treatment observations comes from a random sample of 48 "treatment_IDs"?

Thanks!

df2<-subset(original_df,treatment =="control")

resampling<-replicate(5000,{resampled.data=sample(1:nrow(df), 0.0504*nrow(df), replace=F)
x1=df[resampled.data,]
x2=rbind(x1,df2)
Model= glmer(response ~ treatment*var1*var2+var3
            + (1|ID), data=x2, family="binomial",
            control=glmerControl(optimizer="bobyqa", optCtrl=list(maxfun=2e5)))
Anova(Model)[1,-1:-2]
})



I want generate random list of numbers with javascript

I want generate random list like this

09125856769
09126516511
09127455132
09122318715
09127841522

this is my code

let numbers="0123456789";
let all=null;
let howMuch=prompt("how much you want?");
let countryCode=prompt("enter countrycode");
let numberLentgh=prompt("enter number lentgh");
for(let x=0;x<howMuch;x++){
    for(let i=0;i<numberLentgh;i++){
        let random=Math.floor(Math.random()*numbers.length);
        all=countryCode+=numbers[random];
    };
    console.log(all);
}



How exactly does one make random numbers add up to a declared sum?

I'm confused as to how exactly I would make 9 random numbers add to whatever number the user may input. Let's say the user inputs "200" as the number, how do I make it so that I could get 9 random numbers add up exactly to 200?

Obviously, the code below doesn't work the way I want it to because it's literally just 9 random numbers that don't add up to a specific number. I just have no idea how to get this built properly.

public static void RandomStats()
{
    Random RandomClass = new Random();

    int[] intRandomStats = {
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101), 
        RandomClass.Next(0, 101)
    };

    // ...
}



Reset random call

I am making a blackjack game for class, my code works and there are no errors persay, but every time I call the play function it doesn't reset the cards you are dealt. It works if you stop and run the program again but when you say yes to try again it gives you and the dealer the same cards everytime. It isn't the same as that other question do doen't suggest it, this a different situation with a specific fix.

Here is the code:

import random

playerIn = True
dealerIn = True

    

deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10,
       'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A']
Typecard = ['Of Hearts', 'Of Spades', 'Of Clubs', 'Of Diamonds']
playerHand = []
dealerHand = []

def dealCard(turn):
    card = random.choice(deck)
    turn.append(card)
    deck.remove(card)

def total(turn):
     total = 0
     face = ['J', 'K', 'Q' ]
     for card in turn:
         if card in range(1, 11):
             total += card
         elif card in face:
             total += 10
         else:
             if total > 11:
                 total += 1
             else:
                total += 11
     return total

def tryAgain():
    again = input("Would you like to play again, type yes or no: ").lower()

    if again == "yes":
        print("Ok")
        play()

    elif again == "no":
        print(f"Bye {name}")

def revealDealerHand():
     if len (dealerHand) == 2:
         return dealerHand[0]
     elif len (dealerHand) > 2:
         return dealerHand[0], dealerHand[1]

for _ in range(2):
    dealCard(dealerHand)
    dealCard(playerHand)

def play():
    while playerIn or dealerIn:
        print(f"\nDealer has {revealDealerHand()} and X")
        print(f"\nYou have {playerHand} for a total of {total(playerHand)}")
        if playerIn:
            stayOrHit = input("\nWould you like to stay or hit (type 1 for stay and 2 for hit): ").lower()
        if total(dealerHand) > 16:
            dealerIn = False

        else:
            dealCard(dealerHand)
        
        if stayOrHit == "1":
            break

        else:
            dealCard(playerHand)
        if total(playerHand) >= 21:
            break
        elif total(dealerHand) >= 21:
            break


    if total(playerHand) == 21:
        print(f"\nYou have a hand of {playerHand} for a total of {total(playerHand)} and the dealer has {dealerHand} for a total of {total(dealerHand)}")
        print(f"BLACKJAAACK! Nice one {name}")
        tryAgain()

    elif total(dealerHand) == 21:
        print(f"\nYou have a hand of {playerHand} for a total of {total(playerHand)} and the dealer has {dealerHand} for a total of {total(dealerHand)}")
        print("BLACKJACK, Dealer wins you lose, HA!")
        tryAgain()

    elif total(playerHand) > 21:
        print(f"\nYou have a hand of {playerHand} for a total of {total(playerHand)} and the dealer has {dealerHand} for a total of {total(dealerHand)}")
        print("You bust loser, Dealer wins.")
        tryAgain()

    elif total(dealerHand) > 21:
        print(f"\nYou have a hand of {playerHand} for a total of {total(playerHand)} and the dealer has {dealerHand} for a total of {total(dealerHand)}")
        print(f"The dealer busts, You win {name}!")
        tryAgain()

    elif 21 - total(dealerHand) < 21 - total(playerHand):
        print(f"\nYou have a hand of {playerHand} for a total of {total(playerHand)} and the dealer has {dealerHand} for a total of {total(dealerHand)}")
        print("Dealer Wins, loser.")
        tryAgain()

    elif 21 - total(playerHand) < 21 - total(dealerHand):
        print(f"\nYou have a hand of {playerHand} for a total of {total(playerHand)} and the dealer has {dealerHand} for a total of {total(dealerHand)}")
        print(f"You Win {name}!")
        tryAgain()



name = input("Please type you name: ")
play()

I hvaen't found anything on this problem so nothing really.




lundi 14 novembre 2022

Poker test for RNG Java [closed]

Someone knows where I can find the code for the poker test on RNG, code for java. I need it to show the difference between a good random generator and a bas one but i didn't find anything.




dimanche 13 novembre 2022

Choosing random elements of a 2D array with a minimum distance between them

I have a matrix of r rows and c columns.

I will throw a sequence of bombs at this matrix, each bomb falls in a random cell and destroy a square of "radius" d. A bomb cannot fall in an already destroyed place.

For better visualization, let r = c = 15 and d = 2. The red cells are the cells where bombs fall. The red and the black cells are destroyed and new bombs cannot fall there.

⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬛️🟥⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️🟥⬛️⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬛️⬛️🟥⬛️⬛️
⬜⬛️⬛️🟥⬛️⬛️⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜

My question is: what's the fastest way to choose a sequence of random positions for bombs satisfying this condition?


One of my thoughts was to throw every cell in a hashset, getting a random element inside it, removing all the cells in a distance d of the chosen cell in the hashset and repeat this as much as I need. I don't know how badly this affects the uniformity of the choice and don't know the complexity of getting a random element in a hashset (although I suppose is linear).




Trouble with random numbers in Haskell

I now have the following code:

func = do g <- newStdGen
          randomHeight <- fst (randomR (0, 700) g)
          rand10       <- fst (randomR (0, 10) g)
          randomSpeed  <- fst (randomR (2, 5) g)
          ...

but i get all kinds of error regarding the random integer generation. Any help on how to solve this would be greatly appreciated!!




samedi 12 novembre 2022

How does scipy compute random variates for the distributions given in scipy.stats?

I am currently working on a small probability distributions package (primarily as an exercise) that I am basing on the probability distribution classes in SciPy. Specifically, scipy.stats and its continuous and discrete probability distribution classes.

Each of these classes have the "rvs" method that generates random variates for a given distribution. I scoured the SciPy GitHub repo to try and track down how this is done, but I am getting lost in the vast source code of SciPy. Here is my trail so far (using the normal distribution as an example):

scipy.stats._continuous_distns.norm_gen._rvs

scipy.stats._distn_infrastructure.rv_frozen.rvs

and this is where my reasoning ends. I assume I could use Newton's method or the bisection method with inverse transform sampling, but I sense there could be better optimized algorithms for particular distributions.

tl;dr: What is the best way to implement random variates in Python?

Is the best solution to use these numerical methods, or is there an existing catalog for specific random variate algorithms per type of distribution?




returning even or odd number in function python

I'm super stuck on this problem and dont know how to proceed with the code that I have :/ The instructions dont say to use an if / else statement when checking the value, but just to "determine" if it even or odd

here's the problem:

  1. Write a function called main that generates 20 random numbers between 1 and 300.

  2. Write a value returning function named isEven that accepts a random number as an argument and determines if the random number is even or odd.

3.Call the isEven function in the main function

4.The main function should display if the random number generated is even or odd.



def main():
    import random
    a = random.sample(range(1,300),20)

def isEven(a):
  
    

       



Choosing random elements of a 2D array with a minimum distance between them

I have a matrix of r rows and c columns.

I want to choose n random cells from the matrix but with a minimum distance from each other, called d.

For better visualization, let r = c = 15, n = 4 and d = 2. The red cells are the chosen ones. The black cells are the space in which cells cannot be selected as they are inside the distance d of an already chosen cell.

⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬛️🟥⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️🟥⬛️⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬛️⬛️⬛️
⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬛️⬛️🟥⬛️⬛️
⬜⬛️⬛️🟥⬛️⬛️⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬛️⬛️⬛️⬛️⬛️
⬜⬛️⬛️⬛️⬛️⬛️⬜⬜⬜⬜⬜⬜⬜⬜⬜
⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜

My question is: what's the fastest way to choose n cells satisfying these conditions?


Of course there are plenty of slow ways to do that. One of my thoughts was to throw every cell in a hashset, getting a random element inside it, removing all the cells in a distance d of the chosen cell in the hashset and repeat this n times. I don't know how badly this affects the uniformity of the choice and don't know the complexity of getting a random element in a hashset (although I suppose is linear).




How to create a function which tells how far Turtle has travelled in Python?

import math
import turtle
import random

# Starting Code
def moveTurtle():
 for count in range(10):
   choice = move.randint(1,2)
   if (choice==1):
     turtle.forward(move.randint(3, 30))

   elif(choice==2):
     turtle.right(move.randint(1,234))

def testTurtle():
 turtle.forward(100)
 turtle.left(90)
 turtle.forward(100)

moveTurtle()

testTurtle()

def distance(x,y):

I am new to Python and I'm not quite sure how to write a function that returns the turtle's total distance from random. The function needs to return the distance back to the main program and print it out. Can someone help?




Random password generator using chr function in python

I was searching for this as i had an assignment on it hope it helps i wrote it myslef im new to python but it works:

#RandomPasswordGenerator



import random


def main():
    #random lenght from 8 to 16
        random.randint(8, 16)
var = random.randint(8,16)
print('This is your random password of',var,'characters is:')
#a random number from 33 to 126 for each number in range
for i in range(var):
    num = random.randint(33, 126)
    
    #convert the random num to chr
    letter = chr(num)
    #print the password
    print(letter,end='')



main()

I searched for this specific problem and i didnt find it so here you go




vendredi 11 novembre 2022

How to generate a random 0's and 1's Matrix in which the sum of each row equals 10 in python

How can I generate a Random (N*M) 0's and 1's Matrix in which the sum of each row equals to 10? (in python using numpy)

for example for 10*10(N*M) matrix we can use:

import numpy as np
np.random.randint(2, size=(10, 10))

but I want sum of each rows equals to 10




c : How to generate random numbers without duplication in a two-dimensional array of languages

I want to put random numbers from 1 to 16 in a two-dimensional array without duplication.

I made a code that eliminates duplicates and puts new random numbers back into the array, but it keeps printing duplicate numbers.

Which part is wrong and why?



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

int main()
{
        int A[4][4];
        int i, j, k, l;
        int num;
        srand(time(NULL));
        int count;

        for(i = 0; i < 4; i++)
        {
                for(j = 0; j < 4; j++)
                {
                        //Re:
                        num = rand() % 16 + 1;
                        A[i][j] = num;

                        for(k = 0; k <= i; k++)
                        {
                                count = 0;

                                for(l = 0; l <= j; l++)
                                {
                                        if(A[k][l] == num)
                                        {
                                                if(k != i && l != j)
                                                {
                                                        j--;
                                                        count = 1;
                                                        break;
                                                //      goto Re;
                                                }
                                        }
                                }

                                if(count == 1)
                                        break;
                        }
                }
        }

        for(i = 0; i < 4; i++)
        {
                for(j = 0; j < 4; j++)
                {
                       printf("%3d", A[i][j]);
                }
                printf("\n");
        }

}

I want to put random numbers from 1 to 16 in a two-dimensional array without duplication. I made a code that eliminates duplicates and puts new random numbers back into the array, but it keeps printing duplicate numbers.




Making random string in c#

How can i to make a random srring with c#??

I try this: Random randomnumber = new random(); Var myrandomnumber = random.next(1, 4);

String [] words = {"ROCK", "PAPER", "SCISSORS"}; Console.writeline($"computer:{myrandomnumber}");




How to pick a random number from a collection that doesn't support indexing?

I have a variable of a customly-written collection based on BTreeMap. The keys are GUID-s and the values are some structs.

How will I pick a random element from a said collection based on a random number that's been generated somehow or obtained from an external source?




Discord.py Random Variabel Input / Ouput

I would like to expand my Discord Bot with a new randomizer function. I always want to enter the values/variables manually, for example:

Input: !random text1 text2 text3 Output: The result is "text2"

I need the whole thing in Discord.py (Python) and without slash (/) commands. I tried:

@bot.command()
async def r(ctx, str, name1: str, name2):
    list = [str(name1), str(name2)];
    embed = discord.Embed(
        colour=0xc81f9f,
        title="Rating",
        description=f"{ctx.author.mention} {random.choice(list)} is your rating"
    )
    await ctx.send(embed=embed)



How can I make my Random Math Game loop in Java

So I've been searching on the internet on how to make my Random Math Game loop instead of exit the program when reaching the end of the game, and make the program go back to the start where we can choose the menu available, but I can't seem to find the answer. I've been watching some tutorials on YouTube explaining that I can achieve what I want by using the while loop, but I still can't find a right way to put the while loop in my code.

Here is my code:

package main;

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

public class Main {
    
    static void gameStartStatement() {
        System.out.println();
        System.out.println("+++++++ Game start! +++++++");
        System.out.println();
    }
    static int rngGenerated() {
        Random rng = new Random();
        int generatedNumber = rng.nextInt(20) + 1;
        return generatedNumber;
    }
    
    public static void main(String[] args) {
        Scanner inputMenu = new Scanner(System.in);
        Scanner answerInput = new Scanner(System.in);

        int userInput;
        int userAnswer;
        int maxQuestion = 20;
        int question = 1;
        int scoreResult = 0;
        int x;
        int y;
        int z;

        System.out.println("++ Select your Math Game ++");
        System.out.println(":=========================:");
        System.out.println("| 1> Addition             |");
        System.out.println("| 2> Subtraction          |");
        System.out.println("| 3> Multiplication       |");
        System.out.println(":=========================:");
        System.out.print(">> ");
        userInput = inputMenu.nextInt();

        if (userInput == 1) {
            
            gameStartStatement();
            for (question = 1; question <= maxQuestion;) {

                x = rngGenerated();
                y = rngGenerated();
                z = x + y;

                System.out.println(question + ".");
                System.out.println("What is " + x + " + " + y + " ?");
                System.out.print("Answer >> ");
                userAnswer = answerInput.nextInt();

                if (userAnswer == z) {
                    System.out.println("Correct");
                    System.out.println();
                    scoreResult++;
                } else {
                    System.out.println("Incorrect");
                    System.out.println();
                }
                question++;
                
            }

        } else if (userInput == 2) {
            
            gameStartStatement();
            for (question = 1; question <= maxQuestion;) {

                x = rngGenerated();
                y = rngGenerated();
                z = x - y;

                System.out.println(question + ".");
                System.out.println("What is " + x + " - " + y + " ?");
                System.out.print("Answer >> ");
                userAnswer = answerInput.nextInt();

                if (userAnswer == z) {
                    System.out.println("Correct");
                    System.out.println();
                    scoreResult++;
                } else {
                    System.out.println("Incorrect");
                    System.out.println();
                }
                question++;
            }


        } else if (userInput == 3) {
            
            gameStartStatement();
            for (question = 1; question <= maxQuestion;) {

                x = rngGenerated();
                y = rngGenerated();
                z = x * y;

                System.out.println(question + ".");
                System.out.println("What is " + x + " x " + y + " ?");
                System.out.print("Answer >> ");
                userAnswer = answerInput.nextInt();

                if (userAnswer == z) {
                    System.out.println("Correct");
                    System.out.println();
                    scoreResult++;
                } else {
                    System.out.println("Incorrect");
                    System.out.println();
                }
                question++;
            }

        }
        System.out.println("You answered " + scoreResult + "/20 questions correct");
        System.out.println("You scored " + (scoreResult * 5));
    }
}

I can't really find the solution to my problem.




jeudi 10 novembre 2022

Randomly replacing letters, numbers, and punctuation in a string: can this code be condensed?

Writing a function to check an input string for numbers, and if there are any, to randomize every digit, letter, and punctuation mark in the string. (i.e. "hello3.14" might become "jdbme6?21")

This code works (and the goal makes sense in context, I promise) but it sure seems redundant. Not sure how to tighten it up. The ELSE is just there to make me feel better about loose ends, but it's probably disposable.

My primary question is, Can this method be condensed? Secondary question, Is there a completely different, better way I should do this? Thanks for any guidance.

import random
import string


def new_thing(old_thing):
    output_str = ''
    if any(char.isdigit() for char in old_thing):
        for char in old_thing:
            get_new = char
            if char in string.digits:
                while get_new == char:
                    get_new = random.choice(string.digits)
                output_str += get_new
            elif char in string.ascii_lowercase:
                while get_new == char:
                    get_new = random.choice(string.ascii_lowercase)
                output_str += get_new
            elif char in string.punctuation:
                while get_new == char:
                    get_new = random.choice(string.punctuation)
                output_str += get_new
            else:
                output_str += char
        print(output_str)
    else:
        print("lol no numbers gg")


new_thing(input("Type a thing: ").lower())



I want oposite seed in my list how can I solve it

for example I have this list:

lst = [[0, 1], [0, 1], [0, 1], [1, 0], [1, 0], [1, 0]]

and I shuffle it for example with seed = 42:

random.seed(42)
random.shuffle(lst)

I took this list after shuffle:

[[1, 0], [0, 1], [0, 1], [1, 0], [0, 1], [1, 0]]

I want to take oposite of this shuffle too How can I take this list:

[[0, 1], [1, 0], [1, 0], [0, 1], [1, 0], [0, 1]]

I want oposite seed




mercredi 9 novembre 2022

Random number in class repeating when printed multiple times [BEGINNER QUESTION]

`

class multiplication1d2d:
    num1 = random.randint(1, 20)
    num2 = random.randint(1, 20)
    q = f'{num1} x {num2}'
    ans = num1 * num2

`

When I print the classes num1 and num2 aspects, they repeat. How do I fix this?

print (numltiplication1d2d.num1) print (numltiplication1d2d.num1) print (numltiplication1d2d.num1)




Always Generate the Same Numbers to be Discarded Given a Percentage

I'm working with a very long list of numbers, say 1.5 billion. I need a way to specify a percentage of numbers that I want to keep, and the rest discard. Now I know I can use a Random Number Generator to randomly decide if I should keep it or not, but the problem is that I need the numbers to keep/discard to always be the same. Meaning, if I run the program and it decides to discard indexes 2, 5, and 10, the next time I run the program, it must discard 2, 5, and 10 as well. This is very important.

I'm also facing an issue with memory. To generate a huge list of bools to determine which numbers are discarded and which are not (if we decided to go that way, for example), the profiler says the program uses around 15gb of memory, which is already too much considering I have yet another list of 1.5 billion numbers. Here's my code for that if that matters:

        static bool[] GenerateShouldAddList(int totalCombos, decimal percentToAdd)
        {
            Random RNG = new Random();
            bool[] bools = new bool[totalCombos];
            int percent = (int)(percentToAdd * 100);

            for (int i = 0; i < totalCombos; i++)
            {
                int randNum = RNG.Next(0, 101);
                bools[i] = randNum < percent;
            }

            return bools;
        }

So I'm thinking, to avoid making a huge list, is there a way to make a function that will take in the index number (say index 5364), the total numbers (1.5 billion) and the percentage that you want to keep, and then return to me whether I should add that specific index or not? And if I run each index one at a time through that function, I should only be left with the percentage of numbers I specified. And most importantly, this function should always return the same result for the same index (if the totalNumbers and the percentage don't change). I'm thinking this isn't possible, but I also have hope there's people on here that are much smarter than me. Any help is appreciated!




Trying to randomly pick numbers in c# with an action

Sorry for any miswording of anything here I am not a native english speaker I have been trying to randomly pick a number between 1 - 6 in c# and for whatever reason it says System.Func`1[System.Int32] every time I try to print it out (i know usually this is done in main but this is my homework and I was ordered not to put it in main)

namespace ConsoleApp9
{
    






    internal class Program
    {
        static Random random = new Random();


        static void Main(string[] args)
        {
          
          
            Console.WriteLine(GetDice);
        }



        public static int GetDice()
        {
            Random random = new Random();
            int dice = random.Next(1, 100);
            return dice;
           
        
        
        
        }
    }
}



What is wrong with this lottery Input - Raffle C code?

What is wrong with this lottery Input - Raffle code?

I have been working on a code that when I input 7 numbers by scanf (1~45 integer), 7 numbers are randomley picked, the 2 sets of 7 numbers (mine and the random one) are compared, and the program outputs how much of my numbers are the same with the randomley picked ones. (the order of numbers doesn't matter) If I input more than one same numbers, for expample, 1 1 2 3 4 5 6, or input a number larger than 45, an error message must be printed. If both of these errors are true, there should be a seperate error message.

What is wrong with this lottery Input - Raffle code?

I have been working on a code that when I input 7 numbers by scanf (1~45 integer), 7 numbers are randomley picked, the 2

When I run the program, the radom picking of numbers (raffle) seems to be working fine, no overlapping numbers. the counting of matching number works as well. what is weird is the error messages. since the counting works, I assume the input values are well saved, but the program always outputs multiple lines of (7, exactly) "You cannot choose same number" . can anyone help me with this problem? The source code is below.

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

int main () {

int yours[7];
printf("Buy yours: ");
for (int i=0; i<7; i++){

scanf("%d", &yours[i]);

for (int j=0; j<7; j++){
for (int k=0; k<7; k++){

if (yours[j] == yours[k] && yours[k]>45){
printf("You cannot choose same number and number out of range from 1 to 45.");
printf("\n\n");
printf("Buy yours: ");
}

else if (yours[j]>45){
printf("You cannot choose number out of range from 1 to 45.");
printf("\n\n");
printf("Buy yours: ");
break;
}

else if (yours[j] == yours[k]){
printf("You cannot choose same number.");
printf("\n\n");
printf("Buy yours: ");
break;
}
break;
}
break;
}

}
printf("Lottery result: ");
int lottery[7];

for (int i=0; i<7; i++){
lottery[i] = rand() %45 + 1;

for (int j=0; j<i; j++){

if (lottery[i] == lottery[j]) {
i--;
break;
}
}
}

for (int k=0; k<7; k++){
printf("%d ", lottery[k]);
}

int a = 0;

for (int i=0; i<7; i++){
for (int j=0; j<7; j++){
if (lottery[i] == yours[j]) {
a++;
}
}
}
printf("\n");
printf("The number of yours : %d", a);

return 0;
}



mardi 8 novembre 2022

generating 1000 random samples using for loop

I am trying to generate 1000 random samples and need to put if the p-value of the test for each sample is larger than alpha in reject_collect object and if the true mean of 10 is in the CI of each sample generated. My objects currently only have 1 value. Not sure how to fix it.

reject_collect <- NULL CI_include_collect <- NULL

for ( i in c(1:1000)) { random_vector_index <- rnorm( 50, mean = 10, sd = 2)

alpha <- 0.05 mean(random_vector_index) test_results_index <- t.test(random_vector_index, mu=10, alternative = "two.sided", conf.level = 0.95) test_results_index$p.value

reject_collect <- test_results_index$p.value < alpha

CI_include_collect <- between(10, test_results_index$conf.int[1], test_results_index$conf.int[2]) }


reject_collect <- NULL
 CI_include_collect <- NULL
 
 for ( i in c(1:1000)) { 
   random_vector_index <- rnorm( 50, mean = 10, sd = 2)
   
   alpha <- 0.05
   mean(random_vector_index)
   test_results_index <- t.test(random_vector_index, mu=10, alternative = "two.sided", conf.level = 0.95)
   test_results_index$p.value
   
  reject_collect <- test_results_index$p.value < alpha
   
   CI_include_collect <- between(10, test_results_index$conf.int[1], test_results_index$conf.int[2])
   }




Writing program for guessing a number in Small basic but the program won't run

this is the code I'm using

Sub btnguess_Click
  
  randNum = Math.GetRandomNumber(10)
  FCControls.GetText(txtCels)
  
  If txtCels = randNum Then
    lblanswer = "That's correct the Madame would like to hire you!"
  ElseIf txtCels <1 or >10 Then
    lblanswer = "Please enter number between 1 and 10"
  Elseif txtCels <> randNum Then
    lblanswer = "That's incorrect the Madame asks you to leave."
    EndIf
  
endsub
  

error that I'm getting : 45,24:Expected a condition here.

I'm not sure what I'm missing here




Creating a new column as a function of probabilities stored in another column

Suppose I have a dataframe with a column p which represents the probability that an individual will choose option 1 as opposed to option 2.

id   p
A    0.2
C    0.4
B    0.7
E    0.2
D    0.9

I want to make a new column choice which captures each individual's choice, given their probability of selecting each choice.

Using random, I can do something like

df['choice'] = df['p'].apply(lambda p : random.choices(population=[1, 2], weights=[p, p-1], k=1)[0])

I am hoping to find something that is faster than this, and makes fewer calls to random.choices (I am simulating choices in the dataset many times). Does anyone know a method that could help here?

If it helps, the values of p are discrete, in that there are only so many options for p and many individuals will have the same value. I was thinking I could use some sort of groupby, but not sure exactly what it would look like.

Any help would be greatly appreciated! Thanks




lundi 7 novembre 2022

How to print random imported strings from user in C?

The assignment is as follows: Write a program that takes in courses from a user, saves them in an array, and then prints out a random course for user to complete first.

For example:

How many courses do you have homework in? 3
Course: Math
Course: English
Course: Computer Science
Math, I choose you!
// Helps a user decide which homework to do first
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    // Prompt the user for the number of courses that they have homework in
    int n = get_int("How many courses do you have homework in? ");

    // TODO: Declare an array of courses with the correct number of elements

    // TODO: Prompt the user for their course names and store it in the array
    string courses[n];
    for (int i = 0; i < n; i++)
    {
        courses[i] = get_string("Course: ");
    }
    return(0);
    // Initialize random number generator
    // (found info on https://www.tutorialspoint.com/c_standard_library/c_function_rand.htm)
    time_t t;
    srand((unsigned) time(&t));

    // Find a random number
    int r = rand() % n;

    // TODO: Print out a random course number with index r
    printf("%s/n", courses[r]);
}

This is my code above. How do I fix the print statement to print a random string that the user imported?




Create random bool array

I want to create a randomized bool array with a given length a given number of True values efficiently in Python. I could not find a single command to do so, the following does what I want (twice). Is there anything more elegant way to do it?

import numpy as np

def randbool(length,numtrue):
    index_array=np.random.choice(length,numtrue,replace=False)
    bool_array=np.zeros(length,dtype=bool)
    bool_array[index_array]=True
    return(bool_array)

def randbool2(length,numtrue):
    bool_array=np.hstack((np.tile(True,numtrue),np.tile(False,length-numtrue)))
    np.random.shuffle(bool_array)
    return(bool_array)

print(randbool(5,2))
print(randbool2(5,2))



dimanche 6 novembre 2022

Excel Random Values with 2 Constraints

I've been attempting to build a matrix in Excel with random values. However, these random values must follow two constraints, which are a limit in the column total and another in the line total.

Take this matrix as an example:

Column A Total = 180 Column B Total = 200 Column C Total = 185 Line Total
Random 1 Random 2 Random 3 250
Random 4 Random 5 Random 6 125
Random 7 Random 8 Random 9 60

I can build a formula that allows the columns or the lines to have random values and add to the required total, however I can't arrive to a formula that combines both constraints.

I used this link to define the formula that always adds to the required total.

To allow for a better explanation, see the example of the table above, where the random numbers are now replaced with actual numbers:

Column A Total = 180 Column B Total = 200 Column C Total = 185 Line Total
200 20 30 250
10 80 35 125
5 30 25 60

As you can see, the total in the lines are correct, however the totals of the first column are incorrect and add up to more than what is allowed (215 > 180).

Note that the line values must add up to the total, however the columns must be less or equal, here are the conditions to clarify:

Line Totals
Line1: SUM(Random1, Random2, Random3) = 250
Line2: SUM(Random4, Random5, Random6) = 125
Line3: SUM(Random7, Random8, Random9) = 60

Column Totals
Column1: SUM(Random1, Random4, Random7) <= 180
Column2: SUM(Random2, Random5, Random8) <= 200
Column3: SUM(Random3, Random6, Random9) <= 185

The objective is to achieve it in Excel. Is this possible using formulas only? Or is this an optimization problem for which solver is required?




Please explain what is happening in below line of code [duplicate]

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8];
arr.sort(() => Math.random() > 0.5 ? 1 : -1);

Please explain what is happening by the above lines of code, why we are returning 1 or -1 and what is the use of returning them.




Efficient way to generate random numbers with weights

I need to frequently generate a large number of random numbers in my project, so I am seeking an efficient way to do this. I have tried two ways: (i) using random() and srand(); (ii) using C++ random library.

I tried on the following example: I need to generate 100000000 numbers, from {0, 1, 2, 3}, with weights {0.1, 0.2, 0.3, 0.4}. And from the example, I found that (i) is faster than (ii). (i) requires ~1.3s while (ii) requires ~4s, both using release builds. Is there any other more efficient way to generate random numbers with weights? This is exactly the bottleneck of my program.

Note that, this is just an example. The codes inside the loop in the example are just part of the codes inside the loop in my program. For example, each time generating random numbers has different weights so it seems that I cannot move std::discrete_distribution outside the loop. I just want to repeat the code and see the execution time.

(i) Using random() and srand()

    vector<int> res;
    res.resize(100000000);
    vector<double> weights{0.1, 0.2, 0.3, 0.4};

    srand((unsigned int)time(NULL));
    for (int i = 0; i < 100000000; ++i) {

        double tempSum = 0;
        double randomNnm = (double)(random()/(double)RAND_MAX);

        for(int j = 0;j < weights.size(); j++) {
            tempSum += weights[j];
            if(randomNnm <= tempSum) {
                res[i] = j;
                break;
            }
        }
    }

(ii) Using C++ random library

    vector<int> res;
    res.resize(100000000);
    vector<double> weights{0.1, 0.2, 0.3, 0.4};

    for (int i = 0; i < 100000000; ++i) {
        unsigned seed = chrono::system_clock::now().time_since_epoch().count();
        default_random_engine randGen(seed);
        discrete_distribution<int> thisDistribution(weights.begin(), weights.end());
        res[i] = thisDistribution(randGen); // get the final value
    }



samedi 5 novembre 2022

Python3, Random entries into a format string problem

I am making a program that generates the phrase, "The enemy of my friend is my enemy!" actually, I want this phrase to print out a random permutation of (Friend/Enemy) in each place every time it is re-ran.

so far I got the code to print out the same word 3 times in each, but not a different word in each place.

I couldn't get python to access each string individually from a list. Any ideas?

Thanks!

`

import random

en = 'Enemy'
fr = 'Friend'
words = en, fr

for word in words:
    sentence = f"The {word} of my {word} is my {word}!"
    print(sentence)

`




Hello, how can i make my bot sending a dm to random people like every 5 minutes?

how can i make my bot sending a dm to random people like every 5 minutes ? I requested to many discord server but no one responded to me




Why the most random method (or function) returns from zero(0) to one(1) by default?

I am wonder why the most random method, such as random() method in random module in Python or random() method in Math package in Java, returns a range from zero to one by default?

I assume that it is related with probability or the peeking the limitation of the range. For instance, if we set the default range as natural number, the end of limitation would be positive infinity. Thus, it is much clear to set the range from zero to one for the readability and clarity.

What do you think?

I assume that it is related with probability or the peeking the limitation of the range. For instance, if we set the default range as natural number, the end of limitation would be positive infinity. Thus, it is much clear to set the range from zero to one for the readability and clarity.

What do you think?




How do I create a random VECTOR

I'm completely new to Python, in fact the last time I knew any programming it was commodor-64 basic (apologies).

I'm trying to create random vectors in PYHON. The vector is 52 digits bit only containing 0 - 12 and the vector itself must not repeat. I tried this...

from random import randint
        vector = [randint(0, 12) for p in range(0, 52)]

...but I suspect (although it kind of does the job), I have no way of telling if it isn't repeating the full 52 digit vector at any point. I ran it for several hours and it generated over 44 million times but didn't match the number I wanted it to...I don't even know how many permitations there would be... I'm guessing 52! (51 x 50 x 49...etc) so 44 million is a drop in the (VERY BIG) ocean (my maths isn't up to that).

Or am I wasting my time?

Thanks folks

from random import randint
        vector = [randint(0, 12) for p in range(0, 52)]

I want to repeatedly create a 52 digit vector/matrix of numbers 0 - 12 with no repeat of whole vector (simulated deck of cards shuffle) in Python.




random numbers (using random.randint) returning None [duplicate]

I'm trying to get a random number that is not used (already printed). here's my code:

import random
used_numbers = []

def generate_random_number():
    num = random.randint(1, 90)
    if num not in used_numbers:
        used_numbers.append(num)
        return num
    elif num in used_numbers and num == generate_random_number():
        generate_random_number()

for i in range(90):
    print(generate_random_number())

For some reason after like 20 numbers it returning "None"..

Even if I tried switching to set, I'm still getting alot of "None"s.

What I'm Expecting to get:

A random number from 1 to 90 that is not used, for example:

1
90
82
53
34
65
21
86

ex.

Before I was getting something like this:

34
34
34
12
53
34
12
12
17
18
10
23
12

ex.




vendredi 4 novembre 2022

My if statement is not working only the else statement prints in C [duplicate]

I'm trying to build a word guesser where you guess a word from the given choice. The words are stored in an array. The player is losing even though they must win.


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


void guess(int N) {
  int number, guess, numberofguess = 0;
  int myval[] = {"R22", "B3", "R33", "B232", "R12",
                 "B45", "R2", "B12", "R45",  "B32"};
  srand(time(NULL));

  number = rand() % N;
  printf("choose a number "
         "{'R22','B3','R33','B232','R12','B45','R2','B12','R45','B32'}\n");

  char str[20];
  gets(str);
  printf("your guess is %s\n", str);

  if (str == myval[number]) {
    printf("you win\n");
  } else
    printf("you lose\n");

  printf("the number is %s", myval[number]);
}

main() {
  int N = 9;

  guess(N);

  return 0;
}

I want to make the code in such a way when the player enters the code and it matches with the random output the if statement works.




java.lang.StackOverflowError on a recursive function

I want to draw a random card from a deck and validates that it's always unique. I'm using the cardGenerator() recursive function to do that. If the random card picked has been shown then it calls itself again. Need a work around or if any of yall got a better logic please let me know.

import java.util.ArrayList;
import java.util.Random;

public class App {
    static ArrayList<Integer[]> deck = new ArrayList<>();
    static ArrayList<Integer[]> dealer = new ArrayList<>();

    static Integer[] cardGenerator() throws Exception{
        Random random = new Random();
        Integer[] card = {0, 0};
        Integer num = random.nextInt(13);
        Integer shape = random.nextInt(4);
        Integer[] deckSet = deck.get(num);
        if(deckSet[shape] == 1){
            deckSet[shape] = 0;
            deck.set(num, deckSet);
            card[0] = num;
            card[1] = shape;
            return card;
        }
        else return cardGenerator();
    }

    public static void main(String[] args) throws Exception {
        for(int i = 0; i < 13; i++){
            deck.add(deckSet);
        }
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
    }
}

expecting for dealer to store 5 unique cards, but java.lang.StackOverflowError occured on the cardGenerator function.




Generate a randomized hitori board that can be solved with python

I have successfully created a clingo asp to solve hitori and it works well for examples of hitori boards found online but on trying to generate a hitori puzzle with random values for my clingo solver, it returns unsatisfiable, below is the code I am using for creating the board

import clingo
import random
N = clingo.Number

def randNum(R, n):
    n = n.number
    val = random.randint(1, n)
    if random.randint(0, 9) > 5:
        if val != n:
            n += 1
    else:
        if val != 1:
            val -= 1
    return N(val)

I then reference the value for the board with

board(1..n, 1..n, @RandNum(R,n)). 

The table is created successfully and populated with random values but the solver returns unsatisfialbe Is there a specific method required to create a valid solvable table