dimanche 31 janvier 2021

Generating random numbers from two different intervals in R

To generate randomly distributed values in a single range, I use:

runif(number_of_numbers, lower_bound, upper_bound)

However, what if I want to generate randomly distributed values in two different intervals?

For example, I want to generate 100 random values between [-3,-2] and [2,3].
Is there an one-line elegant solution for that?




Mathematical Analysis

Two chips are drawn at random without replacement from a box that contains five chips numbered I through 5. If the sum of chips drawn is even, the random variable X equals 5; if the sum of chips drawn is odd, then X = -3. Find the Expected value and variance of X.




Random number average in a 'For' loop in C# [closed]

I'm new to programming, and wanting to figure out how to get the sum of a series of random numbers in a 'for' loop, then get the average outside the loop.




Getting Weird Outputs When Printing my 2D Array with Random Numbers, Specifically on Row 6 and 7

My output for the following code has something weird happening on rows 6 and 7, Row 6 always has 3 zeros as the last entries and row 7 always has first 4 zeros and then a large number ~480000. I dont know what is causing this and I need the code to print a full 2D array with 7 rows and 5 columns all with random numbers from 1-100.

#include <iostream>
#include <cstdlib>
using namespace std;   
 //Function precalls
   int random_num(int r);
   void printArray(int * arr, int r, int c);

int main()
{

const int length= 5; //Sets the length of the array segments
int ran=0;
int i,j;
int r=7; //Declares number of rows
int c=5; //Declares number of columns
int arr[7][5]; //Initializes the array
    for(int i=0; i < 5; i++)
    {
        for(int j=0; j < 7; j++)
        {
            arr[i][j] = random_num(ran);
        }
    }
printArray((int*)arr, r, c);
}

    void printArray(int * arr, int r, int c) //Prints the Array
{
for(int i=0; i < r; i++)
{
    for(int j=0; j < c;j++ )
    {
        cout << *(arr+i*c+j) << " ";
    }
    cout<< endl;
 }
}

  int random_num(const int r) //Assigns random numbers to Array
  {

int ran=0; //Sets the number to zero before generation

ran = rand()% 100 + 1;
return ran;

   }



C++ Primer 5th Edition Random numbers [closed]

I am at chapter 17 generating Random numbers. C++ primer 5th ed.

I am stuck at this:

Generating Numbers That Are Not Uniformly Distributed In addition to correctly generating numbers in a specified range, another advantage of the new library is that we can obtain numbers that are nonuniformly distributed. Indeed, the library defines 20 distribution types! These types are listed in § A.3 (p. 882). As an example, we’ll generate a series of normally distributed values and plot the resulting distribution. Because normal_distribution generates floating-point numbers, our program will use the lround function from the cmath header to round each result to its nearest integer. We’ll generate 200 numbers centered around a mean of 4 with a standard deviation of 1.5. Because we’re using a normal distribution, we can expect all but about 1 percent of the generated numbers to be in the range from 0 to 8, inclusive. Our program will count how many values appear that map to the integers in this range:

int main(){

    default_random_engine e;        // generates random integers
    normal_distribution<> n(4,1.5); // mean 4, standard deviation 1.5
    vector<unsigned> vals(9);       // nine elements each 0

    for (size_t i = 0; i != 200; ++i) {
        unsigned v = lround(n(e));  // round to the nearest integer
        if (v < vals.size())        // if this result is in range
            ++vals[v];              // count how often each number appears
    }

    for (size_t j = 0; j != vals.size(); ++j)
        cout << j << ": " << string(vals[j], '*') << endl;
}

The output:

0: ***
1: ********
2: ********************
3: **************************************
4: **********************************************************
5: ******************************************
6: ***********************
7: *******
8: *

It works fine but I don't know what is a "mean of 4" and "standard deviation of 1.5".

"Because we’re using a normal distribution, we can expect all but about 1 percent of the generated numbers to be in the range from 0 to 8, inclusive."

  • When I googled I've seen something I couldn't understand the Gauss rule on Normal Distribution.

  • I know in statistics what "mean".

  • Please help.




Python's random module, coin toss discrepency [duplicate]

I'm new to Python and doing a small project to simulate how often a streak of six heads or tails will come up in a random coin toss.

I came up with the code easy enough (I thought), but when I decided to try writing the code in a different way I noticed a discrepancy in the output. The first script tends to output a streak between 3% to 3.5% of the time. The second script tends to only output a streak 1.5% to 2% of the time. I've tried to think through the lines carefully to see if there is a reason for the difference in the way I've written the two scripts... but I can't see it.

Can anyone explain why the first script tends to produce more streaks than the second?

Script 1

import random

streak = 0

for number in range(10000):
    setOfSix = 0

    # Generate a random list of heads or tails.
    for tosses in range(6):
        flip = random.randint(0, 1)
        if flip == 0:
            setOfSix -= 1
        else:
            setOfSix += 1
    
    # Check if there is a streak in set of tosses
    if setOfSix == 6:
        streak += 1
    elif setOfSix == -6:
        streak += 1
    else:
        pass

print(streak)

Script 2

import random

streak = 0

for number in range(10000):
    setOfTosses = []

    # Generate a random list of heads or tails.
    for tosses in range(6):
        flip = random.randint(0, 1)
        if flip == 0:
            setOfTosses.append('T')
        else:
            setOfTosses.append('H')
        
    # Check if there is a streak in set of tosses.
    if 'H' and 'T' in setOfTosses:
        pass
    else:
        streak += 1

print(streak)



why does my list keep changing after using for loop to append?

I've created a function that produces n number of random k-combinations of tuples from the list below (example is 5 sets of 6 tuples). Though the function works as expected, every time I run the script it overwrites what was previously appended to rand_list.

list_a=[(0, 1), (0, 2), (0, 5), (0, 10), (0, 20), (0, 50), (0, 100), (2, 1), (2, 2), (2, 5), (2, 10), (2, 20), (2, 50), (2, 100), (5, 1), (5, 2), (5, 5), (5, 10), (5, 20), (5, 50), (5, 100), (10, 1), (10, 2), (10, 5), (10, 10), (10, 20), (10, 50), (10, 100), (20, 1), (20, 2), (20, 5), (20, 10), (20, 20), (20, 50), (20, 100), (50, 1), (50, 2), (50, 5), (50, 10), (50, 20), (50, 50), (50, 100), (100, 1), (100, 2), (100, 5), (100, 10), (100, 20), (100, 50), (100, 100)]
import random
rand_list=[]

def rand_gen(n):

i=[random.choices(list_a, k=6) for r in range(n)]
    for x in i:
        if x not in rand_list:
            rand_list.append(x)

rand_gen(5)
print(rand_list)

e.g. first run output:

print(rand_list) >>> [[(0, 50), (50, 10), (10, 20), (10, 1), (20, 20), (5, 2)], [(0, 5), (50, 5), (0, 50), (5, 20), (5, 100), (0, 10)], [(100, 2), (50, 10), (10, 2), (50, 100), (0, 1), (20, 10)], [(20, 2), (50, 2), (20, 100), (50, 2), (20, 10), (5, 5)], [(100, 5), (0, 20), (100, 10), (50, 100), (5, 1), (10, 50)]]

second run output

print(rand_list) >>> [[(2, 1), (5, 5), (10, 1), (5, 100), (0, 5), (0, 100)], [(5, 10), (100, 1), (100, 100), (2, 10), (0, 5), (5, 50)], [(50, 2), (5, 100), (0, 5), (100, 5), (10, 50), (20, 1)], [(20, 50), (10, 10), (2, 5), (5, 50), (100, 1), (0, 50)], [(10, 1), (0, 10), (10, 20), (10, 2), (5, 2), (10, 20)]]

How do I get it to stay the same? I want to use rand_list elsewhere but I can't if it just changes every time i run the script and so is not stable. IDE is sublime text if that's relevant.

how do i get the list to be stable i.e. only producing what was in the first run regardless of how many times the script is run?




Insert a new column in pandas with random string values

I had a DataFrame

     A B C
   0 1 2 3  
   1 2 3 3  
   2 3 2 1  

I needed to create a new column in a pandas DataFrame with 'yes' or 'no' randomly filling this column.

     A B C  NEW
   0 1 2 3  yes
   1 2 3 3  no
   2 3 2 1  no

Using random.choice results in a column with the same result for every line

     A B C  NEW
   0 1 2 3  no
   1 2 3 3  no
   2 3 2 1  no

I tried map, apply and applymap but there's a easier way to do.




Select from List of cards (strings) at random, but allow ignoring of previously chosen cards (strings) next time around?

I am trying to make a card game in android studio. I had it working completely fine before, any time I click a "roll" button in android studio it would loop through the list of cards and show them one by one. Only problem was it would repeat the output of cards

I felt making another list of selected cards via their "random" index would be the best way of doing this. However, now my code is very messy and does not handle the logic correctly.

    public String shuffleCards() {

        // Strings to return to the user
        String errorString = "ERROR: NO CARDS IN DECK" + '\n' + '\n' + "Go to 'EDIT CARDS' to add game cards to the current deck.";
        String completedString = "All cards in deck have been shown." + '\n' + '\n' + "Go back to the MAIN MENU to restart";


        List<String> allCards = this.getRandomCards();
        List<Integer> cardsDone = new ArrayList<>();

        int randIndex = new Random().nextInt(allCards.size());


        if (!allCards.isEmpty()) {
            //generate rand int [0, size]
            String randString = allCards.get(randIndex); //get random string
            //check for all cards that have been done.
            if (!cardsDone.contains(randIndex)) {
                cardsDone.add(randIndex);
                return randString;
            } else if (cardsDone.size() == allCards.size()) {
                return completedString;
                }
            else {
            }
            return randString;
        }
        return errorString;
    }
}

Can anyone help fix this code so it handles the logic correctly, as well as give me any tips to make this not as messy (I feel like it can be much simpler).

Thanks :)




Is the number pi algorithmically random in the Martin-Löf sense?

Given a formula f to compute a certain constant c - can this constant still be considered algorithmically random, if the constant is an infinite sequence?




How do I repeat a random number

I've tried searching for help but I haven't found a solution yet, I'm trying to repeat math.random. current code:

local ok = ""
for i = 0,10 do
local ok = ok..math.random(0,10)
end
print(ok)

no clue why it doesnt work, please help




how to create an array of random number, all different from each other?

The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks CODE:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
arr[i]=10+rand()%20;

for(i=0;i<N;i++)
{
    for(j=N-1;j==0;j--)
    {
        do
        {
           arr[i]=10+rand()%20;
           if(arr[i]!=arr[j])
             break;
        }
        while(arr[i]==arr[j]);
    }
   printf(">>%d\n",arr[i]);
}



R: Saving the Results of a Loop

I am using the R programming language. I am learning about loops and how to store the results of a loop. For instance, I wrote the following code that loops a function (generates random data and fits different decision trees):

#load libraries    
    library(caret)
library(rpart)

#generate data

a = rnorm(1000, 10, 10)

b = rnorm(1000, 10, 5)

c = rnorm(1000, 5, 10)

group <- sample( LETTERS[1:2], 1000, replace=TRUE, prob=c(0.5,0.5) )
group_1 <- 1:1000

#put data into a frame
d = data.frame(a,b,c, group, group_1)

d$group = as.factor(d$group)

#place results in table
#final_table = matrix(1, nrow = 10, ncol=10)


e <- d



vec1 <- sample(200:300, 5)
vec2 <- sample(400:500,5)
vec3 <- sample(700:800,5)

for (i in seq_along(vec1)) { 
    for (j in seq_along(vec2)) {
        for (k in seq_along(vec3)) {
            # d <- e
            d$group_2 = as.integer(ifelse(d$group_1 < vec1[i] , 0, ifelse(d$group_1 >vec1[i]  & d$group_1 < vec2[j] , 1, ifelse(d$group_1 >vec2[j]  & d$group_1 < vec3[k] , 2,3))))
            
            
            
            
            d$group_2 = as.factor(d$group_2)
            
            fitControl <- trainControl(## 10-fold CV
                method = "repeatedcv",
                number = 2,
                ## repeated ten times
                repeats = 1)
            
            TreeFit <- train(group_2 ~ ., data = d[,-5],
                             method = "rpart",
                             trControl = fitControl)
            
            pred <- predict(
                TreeFit,
                d[,-5])
            
            con <- confusionMatrix(
                d$group_2,
                pred) 
            
            #update results into table
            #final_table[i,j] = con$overall[1]
            acc=c(vec1[i],vec2[j],vec3[k],con$overall[1])
            print(acc)
            
            
        }
    }
}

I am interested in saving the results of "acc" into a table (or a data frame). I am able to print all values of "acc", but when I formally view the results of "acc" : only the last line is displayed.

My question: is it possible to take the entire printed output (i.e. "acc") and store it into a table?

Thanks




samedi 30 janvier 2021

Any way to use STL algorithm to shuffle two vectors simultaneously in C++?

I am porting a Java program to C++. I have a piece of code to shuffle two arrays simultaneously in Java, which produces a way to return the indices of the shuffled array so could to used to relocate another array (of the same length) accordingly. In C++, I shuffle the vectors with the following algorithm

#include <vector>
#include <algorithm>
#include <random>
#include <iostream>

using namespace std;
int main(void) {

    vector<int> A, B;
 
    for (int n=0; n<10; n++) {
        A.push_back(n);
        B.push_back(n);
    }
    
    std::random_device rd;
    std::mt19937 gen;
    std::uniform_int_distribution<> rnd(0, A.size()-1);
    for (int n=0; n<A.size(); n++) {
        int m = rnd(gen);
        std::swap(A[n], A[m]);
        std::swap(B[n], B[m]);
    }
    
    for (auto it: A) cout << it << " ";
    cout << endl;
    for (auto it: B) cout << it << " ";
    cout << endl;
    return 0;
}

It works. But I wonder if there is any STL algorithm that can simultaneously shuffle two or more containers.




java api that generates random dictionary words

I'm trying to develop a Java program which presents Users with encrypted word and asks them to decode it. Currently I present random words from an array after encrypting them with a random Caesar shift number. I want to replace the word source with any online free random dictionary word service generator or a service containing dictionary words that I can access by index.

Could you please advise on any java apis that have this?

Thank you




Speed of random sampling from distribution in R

I was trying to investigate a probability distribution whose moments were the Catalan numbers, and came up with

qcatmo <- function(p, k=4){ (qbeta(p/2+1/2, 3/2, 3/2)*2 - 1)^2 * k } 
colMeans(outer(qcatmo(ppoints(10^6)), 0:10, "^"))
#      1     1     2     5    14    42   132   429  1430  4862 16796

which worked out nicely. But then I tried to generate random values from this distribution, and found three possible approaches (A using the quantile function I already knew worked applied to runif, B slightly more direct using the built-in rbeta function, and C using a form of rejection sampling with runif) with noticeably different speeds when used on large samples:

rcatmoA <- function(n, k=4){ qcatmo(runif(n), k) }
rcatmoB <- function(n, k=4){ (rbeta(n, 3/2, 3/2)*2 - 1)^2 * k }
rcatmoC <- function(n, k=4){
             n0 <- ceiling(n*4/pi + 7*sqrt(n) + 35)
             x0 <- runif(n0)^2 
             y0 <- runif(n0)^2 
             x0[x0 + y0 < 1][1:n] * k
             }

which when benchmarked gave

library(microbenchmark)
n <- 10^4
microbenchmark(
  rcatmoA(n,4),
  rcatmoB(n,4),
  rcatmoC(n,4)
  ) 
#Unit: microseconds
#          expr     min       lq      mean   median       uq     max neval cld
# rcatmoA(n, 4) 22817.2 23014.95 23259.688 23186.95 23322.80 25128.9   100   c
# rcatmoB(n, 4)  1526.5  1534.40  1615.255  1541.30  1607.15  4952.1   100  b 
# rcatmoC(n, 4)   781.5   788.70   884.339   795.00   813.80  7266.2   100 a  

My questions are:

  • Why is the B version so much faster than the A version?
  • If the B version is faster because it avoids applying a function to runif data, why is the C version even faster?
  • Is there any general advice on how best to make random samples in this sort of situation?



How to make Monty Hall game in Java? [closed]

I'm trying to create the Monty Hall game in Java.

You choose how many boxes it should be at the start, then you choose a number between 1 and total boxes.

A String array is created with the amount of total boxes and I fill up one randomly with "price" and the rest with "donkey".

I'm stuck with removing all arrays beside the one you choose and one that is either "donkey" or "price", which depends if you choose the "price/donkey" one.

For example:

You choose a total of 5 boxes.
You choose box number 2 as your box.

We will fill all those 5 boxes with (donkey/price); for example (donkey, donkey, price, donkey, donkey).

I need help with this.

In the example below, price is in box 3 and I choose box 2. I want a new String array to be created with box 3 and 2 in it. And then ask the person if he want to change box or not.

My code:

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        Random random = new Random();
        String price = "price";
        String donkey = "donkey";
        int boxes = 0;
        int choice = 0;
        int randomNumber ;
        String[] twoBoxes = new String[2];
        String[] totalBoxes = new String[boxes];

        System.out.print("How many boxes? (minimum 3): ");
        boxes = scanner.nextInt();
        randomNumber = random.nextInt(boxes);

        System.out.print("Choose a box between 1 and " + boxes + ": ");
        choice = scanner.nextInt();


        for (int i = 0; i < totalBoxes.length; i++) {

            if (randomNumber != i) {
                totalBoxes[i] = donkey;
            }
            else {
                totalBoxes[randomNumber] = price;
            }
        }

        System.out.println(Arrays.toString(totalBoxes));
    }
}



Why does using the Random() class to create 100 random arrays create repeating arrays? [duplicate]

I am making a program that creates 100 arrays and fills them with random numbers between 1 and 100. However, it produces repeating arrays. The amount of repeating arrays is inconsistent and changes every time I run it. How can I create 100 non-repeating random arrays? Additionally, I am using this in a program where I time different sorting techniques. Why does it take different amounts of time to sort identical arrays (the ones that are supposed to be random arrays) with the same sorting method?


int[] array = null;
        for (int i = 0; i < 101; i++)
        {
           Random r = new Random();
           int length = 15;
           array = new int[length];
           for (int n = 0; n < length; n++)
           {
              int newNum = r.Next(100);
              array[n] = newNum;
           }
           Console.WriteLine();
           Console.WriteLine("#" + (i + 1));
           PrintArray(array);




Is there a way to print the sum of randomly generated numbers in a do while loop? C++

I am writing a program to very fundamentally simulate a black jack game using rand() % 11. We have to tell the players their running total as well as asking if they want another card (hit). My first problem is getting multiple random numbers and my second problem is not being able to add the two random numbers together. Strings are not allowed. Here's the block of code that I think is causing there's errors. I am very new to c++. Do I need to have multiple variables with the rand() %10 +1 to add them? I know that the add + add won't work but I can't figure out an alternative.

int add = rand() % 10 + 1;                                                  
bool hit = false;                                                           
int i = 0;                                                                  
       
do{                                                                                     
cout << "Players 1 running total is " << add;                                          
i++;                                                                        
cout << " \n ";                                                             
cout << "Would you like another number? (0-yes or 1-no) ";                  
cin >> hit;                                                             
if(hit == 0){                                                           
cout << " You got an " << add << " \n ";                            
cout << "You're running total is " << add + add;                                       
}                                                                       
                                                                                   
} while (hit == false); 



Randomly generating numbers in R with condition for the total sum AND with restrictions for specific members of the generated vector

I am looking to randomly generate a vector of numbers in R, with a specific sum but which also has a restriction for some specific members of the generated vector, e.g. that the 4th number (say, in a vector of 5) cannot exceed 50.

I am doing this within a for loop with millions of iterations in order to simulate election vote changes, where I am adding votes to one party and taking them away from other parties with equal probability. However, my issue is that in many iterations, votes turn out to be negative, which is illogical. I have figured out how to do the "sums up to X" part from other answers here, and I have made a workaround for the second restriction as follows:

 parties <- data.table(party = c("red", "green", "blue", "brown", "yellow"), votes = c(657, 359, 250, 80, 7))
    votes_to_reallocate <- 350
    immune_party <- "green"

    parties_simulation <- copy(parties)
    
    parties_simulation[party != immune_party, 
                         votes := votes - as.vector(rmultinom(1, size=votes_to_reallocate, prob=rep(1, nrow(parties)-1)))
                         ]
# Most likely there are negative votes for the last party, perhaps even the last two.
# While loop is supposed to correct this
    
    while (any(parties_simulation[, votes]<0)) {
        negative_parties <- parties_simulation[votes < 0, party]
        for (i in seq_along(negative_parties)) {
            votes_to_correct <- parties_simulation[party == negative_parties[i], abs(votes)]
            parties_to_change <- parties_simulation[party != immune_party & !party %in% negative_parties, .N]
            parties_simulation[party != immune_party & !party %in% negative_parties, 
                               votes := votes - as.vector(rmultinom(1, size=votes_to_correct, prob=rep(1, parties_to_change)))
            ]
            parties_simulation[party == negative_parties[i], votes := votes + votes_to_correct]
            }
        }

However, this seems to be a huge bottleneck as each simulation has to be corrected by the while loop. I am curious as to whether there is a solution for this that would generate the random numbers with the restriction already imposed (for instance, generate 4 random numbers, adding up to 350, and with the fourth number not exceeding 7). If not, perhaps there is a more efficient way to solve this?




IndexError: tuple index out of range walking dot

i want to create a dot using create_line in a canvas that corresponds to a random position inside the canvas shape specifically a circle one that loops until it reaches outside the circle like a walking dot scenario the code is as follows

    def movem(self, movesetx, movesety): #function for having movement
    self.movesetx = movesetx
    self.movesety = movesety
    xar.append(movesetx)
    yar.append(movesety)


    if directw == "E" :
        movesetx = centerx + 1
        movesety = centery

    elif directw == "N":
        movesetx = centerx
        movesety = centery + 1

Here is the code getting a value in a list of Directions (N for North, E for east etc.) Canva = canvas(tkinter)

p1=Full().movem(movesetx=random.choice(directw),movesety=random.choice(direction))
l = canva.create_line(p1,p2,p1,p2)



How to generate in python a random number in a range but biased toward some specific numbers?

I would like to choose a range, for example, 60 to 80, and generate a random number from it. However, between 65-72 I'd like a higher probability, while the other ranges aside from this (60-64 and 73 to 80) to have lower. I know there's lots of questions about that issue here, but I coudn't find any that could be expanded to my case, most of them people are just choosing between two things and want some bias upon it.

Also, it would be interesting a scalable solution, so that one could expand its usage for higher ranges, for example, 1000-2000, but biased toward 1400-1600.

Does anyone could help with some ideas?

Thanks beforehand for anyone willing to contribute!




Multi classification with Random Forest - how to measure the "stability" of results

I am using Random Forest (from sklearn) for a multi-classification problem, with ordered classes(say 0,...,n, with n=4 in my specific case) roughly equally distributed. I have many observations (roughly 5000) and I split them in train/test 70%/30% respectively - the classes are equally distributed also in train and test. I set random_state=None, so each time I re-run the fitting of the model (on the same training set) and then the prediction, I obtain slightly different results on my test set.

My question is how to measure if Random Forest is working well by comparing different predictions...

For example if I obtain as predictions first only 0 and then only n (where, as said, 0 and n are the most different classes), I would say that the RF is not working at all. On the contrary if only few predictions change from a class to a close one (e.g. first 0 and then 1), I would say RF is working well.

Is there a specific command to check this automatically?




How to check if you written same numbers for two times in int input?

import random

purpose = random.randint(1, 10)
attempts = []
guess = int(input("Try to guess number between 1 to 10: "))
guess2 = guess + guess

    
while purpose != guess:
    print ("Oh sorry your guess was wrong :( ")
    attempts.append (guess)
    guess = int(input("Try to guess again: "))

there I want to make that if you guessed same number for two times, for example guesses were [5, 4, 4, 7]- program writes "you have a short memory". I tried it with function but code just writes "<function short_memory at 0x7fa6d7e58430>" (short_memory was name of function)

if purpose == guess :
    print ("Your guess was right!! ")


print ("your attempts was: ", attempts)



How can I do random name picker in multiple textboxes without any dublicates in c# framwork?

enter image description hereI want random names on each of that textboxes and not duplicate! we can test by those names(Liam, Noah, Oliver, William, Elijah). I would appreciate it if someone explains...




vendredi 29 janvier 2021

R: Iterating Random Numbers in a Loop

I am using the R programming language. In a previous question (R Language: Storing Results of a Loop into a Table) I learned how to iterate a loop for fixed values of a variable "i":

  #load libraries
    
        library(caret)
        library(rpart)
    
    #generate data
        
        a = rnorm(1000, 10, 10)
        
        b = rnorm(1000, 10, 5)
        
        c = rnorm(1000, 5, 10)
        
        group <- sample( LETTERS[1:2], 1000, replace=TRUE, prob=c(0.5,0.5) )
        group_1 <- 1:1000
        
        #put data into a frame
        d = data.frame(a,b,c, group, group_1)
        
        d$group = as.factor(d$group)

 #start the loop


e <- d

#here is the "i" variable

for (i in 400:405) {
  d <- e
  d$group_1 = as.integer(d$group_1 > i)
  d$group_1 = as.factor(d$group_1)
  
  trainIndex <- createDataPartition(d$group_1, p = .8,list = FALSE,times = 1)
  training = d[ trainIndex,]
  test  <- d[-trainIndex,]
  
  
  fitControl <- trainControl(## 10-fold CV
    method = "repeatedcv",
    number = 10,
    ## repeated ten times
    repeats = 10)
  
  TreeFit <- train(group_1 ~ ., data = training,
                   method = "rpart2",
                   trControl = fitControl)
  
  pred = predict(TreeFit, test, type = "prob")
  labels = as.factor(ifelse(pred[,2]>0.5, "1", "0"))
  con = confusionMatrix(labels, test$group_1)
  
  #update results into table
  row = i - 399
  final_table[row,1] = con$overall[1]
  final_table[row,2] = i
  
}

        #place results in table
        final_table = matrix(1, nrow = 6, ncol=2)

Now, I am trying to replace "i" with a list of random numbers : (i in sample(100:400, 10))

However, this returns the following error (note: I changed final_table = matrix(1, nrow = 6, ncol=2) to final_table = matrix(1, nrow = 100, ncol=2)) :

Error in na.fail.default(list(group_1 = c(NA_integer_, NA_integer_, NA_integer_,  : 
  missing values in object

Can someone please show me what I am doing wrong? Is there an easier way to store all results from the loop into a matrix (or a table) without explicitly defining the number of rows required? Can the computer automatically keep adding a new row for every new value of "i"?

Thanks




How do I store a random variable and print it for a game?(java)

I'm trying to run the constructor with:

Main fight1 = new Main("Homeless Man", "Rusty Fork", 100, 110, 30);

I Want it to deal a random amount of damage (within a specified range), save that value for the next stage of combat, and then for the players health to drop and be stored respectively. I also want it to repeat until the enemy no loner has health. I can update the code below with the rest of the program if you want to try it yourself. The current output is:

Will you:
 -Attack (1)
 -Consume Item (2) 
 -Run (3)
1
Homeless Man hits you with a Rusty Fork, Dealing 54 damage!
You now have 903 HP left!
You hit Homeless Man With an attack using your Fists dealing 42 damage!
Homeless Man now has 60 HP left!

The actual program:

private static int playerMaxDam = 75;
private static int playerMinDam = 30;
private static int damageDelt;
private static int playerHP = 1000;
private static String currentWeapon = "Fists";

//default enemy variables
private static String enemyName;
private static String enemyItem;
private static int enemyHP;
private static int enemyMaxDam;
private static int enemyMinDam;
private static int damageTaken;

//enemy health

public int getDamageTaken() {
    
    Random rand = new Random();
    damageTaken = rand.nextInt(enemyMaxDam - enemyMinDam + 1) + enemyMinDam;
    return damageTaken;
}

public int getDamageDelt(){
    
    
    Random rand = new Random();
    damageDelt = rand.nextInt(playerMaxDam = playerMinDam + 1) + playerMinDam;
    return damageDelt;
}

public Main(String _enemyName, String _enemyItem, int _enemyHP, int _enemyMaxDam, int _enemyMinDam) {
    enemyName = _enemyName;
    enemyItem = _enemyItem; 
    enemyHP = _enemyHP;
    enemyMaxDam = _enemyMaxDam;
    enemyMinDam = _enemyMinDam;     
}

public String getPlayerWeapon() {
    
    
    String playerWeapon = null;
    String fists = "1";
    String bloody_Spoon = "0";
    
    if(fists.equals("1")) {
        playerMaxDam = 75;
        playerMinDam = 30;
        playerWeapon = "Fists";
    }else {
        if(bloody_Spoon.equals("1")) {
            playerMaxDam = 100;
            playerMinDam = 75;
            playerWeapon = "Bloody Spoon";
        }
    }
    
    return playerWeapon;
}

public void displayCombat() {
    //enemy
    int enemyHealth = (enemyHP - getDamageDelt());
    
    //player
    int playerHealth = (playerHP - getDamageTaken());
    
    //player armor
    int clothes = 1;
    int tux = 0;
    
    //player weapon
    String playerWeapon = currentWeapon;
    int fists = 1;
    int bloody_Spoon = 0;
    
    Scanner in = new Scanner(System.in);
    System.out.println("Will you:\n -Attack (1)\n -Consume Item (2) \n -Run (3)");
    String userInput = in.nextLine();
    if(userInput.equals("1")) {
        System.out.println(enemyName + " hits you with a " + enemyItem + ", Dealing " + getDamageDelt() + " damage!");
        System.out.println("You now have " + playerHealth + " HP left!");
        System.out.println("You hit " + enemyName + " With an attack using your " + playerWeapon + " dealing " + getDamageDelt() + " damage!");
        System.out.println(enemyName + " now has " + (enemyHP - getDamageDelt()) + " HP left!");
        
    }else {
        if(userInput.equals("3")) {
            System.out.println("You managed to escape the fight with " + playerHP + " left!");
        }
    }
}



Speed up a Monte Carlo in Excel

I am running a Monte Carlo in Excel. To represent the distribution of demand for each product SKU during each month, I am using the following formula over 500 times:

=IFERROR(BETA.INV(RAND(),(1+4*(D35-D31)/(D27-D31)),(1+4*(D27-D35)/(D27-D31)),D31,D27),0)

So, that's over 500 RAND() volatile functions at a time.

The output from each iteration of a formula is stored in a table. I have a VBA to handle that:

Sub QARLO_Products()
'runs on QARLO_P!, for forecasting product
    Range("Q7:OC100000").ClearContents
    For Iteration = 1 To Range("G1").Value
        Range("I1").Value = Range("G1").Value - Iteration
        'For QMIN Zinc-Bulk
        Cells(6 + Iteration, 17) = Iteration
        Cells(6 + Iteration, 18) = Cells(39, 4)
        Cells(6 + Iteration, 19) = Cells(39, 5)
        Cells(6 + Iteration, 20) = Cells(39, 6)
        Cells(6 + Iteration, 21) = Cells(39, 7)
        Cells(6 + Iteration, 22) = Cells(39, 8)
        Cells(6 + Iteration, 23) = Cells(39, 9)
        Cells(6 + Iteration, 24) = Cells(39, 10)
        Cells(6 + Iteration, 25) = Cells(39, 11)
        Cells(6 + Iteration, 26) = Cells(39, 12)
        Cells(6 + Iteration, 27) = Cells(39, 13)
        Cells(6 + Iteration, 28) = Cells(39, 14)
        Cells(6 + Iteration, 29) = Cells(39, 15)
        'For QMIN Zinc-Jugs
        Cells(6 + Iteration, 30) = Iteration
        Cells(6 + Iteration, 31) = Cells(40, 4)
.... blah, blah, blah and so on for all products....
        Cells(6 + Iteration, 444) = Cells(561, 14)
        Cells(6 + Iteration, 445) = Cells(561, 15)
   Next Iteration
End Sub

The left-hand side of these statements represent the table location for recording output data, the right-hand side are the outputs from the above mentioned formula.

I notice that this VBA runs through each and every line in series. Each line causes all 500 volatile RAND() functions to recalculate. One iteration of this VBA takes 30 seconds on all 8 cores of a Core i7/ 32GB RAM. I want to run 5,000 iterations on a regular basis.

Can you suggest methods to make this model run more efficiently?

  • Make one cell a RAND() and then have all 500 reference it?
  • Restructure the VBA?

I have done all the basic/general things to make Excel run more efficiently.




Random number showing in every few seconds Wordpress Shortcode

I need help to create shortcode for my wordpress site..

What I would like to add is: “(random number) calories”

And the random number shows in range of 1300 - 5000 and it changes every 3-4 seconds.

I think I have to add code in functions.php in Wordpress theme to create shortcode..

Could anyone help to create code that I can add in fundctions.php to add shortcode?




Error "rand" was not declared in this scope

I'm having a problem with the rand() function in C.

The code looks something like this:

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

int main()
{
    int c = 10;
    int i = 0;
    int cn[10];

    srand(time(NULL));

    while(i < c)
    {
        cn[i] = rand() % 10 + 1;
        printf("%d ", cn[i]);
        i++;
    }
}

When I execute the code, i get this error: [Error] "rand" was not declared in this scope.

I think this is a stdlib issue, because if i don't include stdlib but i include cstdlib, it opens cstdlib and the error: [Error] "rand" was not declared in this scope, appears there too.

When i try to Run it only with cstdlib it opens a different Dev C++ window that looks like this:

enter image description here




how to solve the runtime problem without getting a result while solving the vehicle routing problem using java

I wanto to resolve the vehicle routing problem while respecting the constraint of times window. I have the following class

  public class VrpProblem {

private static int maxLocomotives=3;
private int numRames;
private int[] serviceTimes;
private int[] windowStartTimes;
private int[] windowEndTimes;
public double[][] rameTimes;
public double[] timesFromMultimodal;

private double maxTime;

public VrpProblem(int numRames,double[][] rameTimes,double[] timesFromMultimodal,int[] serviceTimes,int[] windowStartTimes, int[] windowEndTimes) {

    this.numRames = numRames;
    this.serviceTimes = serviceTimes;
    this.windowStartTimes = windowStartTimes;
    this.windowEndTimes = windowEndTimes;
    this.timesFromMultimodal = timesFromMultimodal;
    double[][] mat=new double[numRames][];
    for (int i=0 ; i<mat.length; i++)
        mat[i]=new double[numRames];
    for (int i = 0; i < numRames; i++) {
          
          for (int j = 0; j < numRames; j++) {
            mat [i][j] = rameTimes[i][j];
            if (rameTimes[i][j] > maxTime) {
              maxTime= rameTimes[i][j];
            }
          }
        }
    
    this.rameTimes = mat;


      }

public int[] getServiceTimes() {
    return serviceTimes;
}

public int[] getWindowStartTimes() {
    return windowStartTimes;
}

public double getMaxTime() {
    return maxTime;
}

//si Id est negatif, Il refere au multimodal
  public double getTime(int custId1, int custId2) {
    if (custId1 >= 0 && custId2 >= 0) {
      return rameTimes[custId1][custId2];
    } else if (custId1 >= 0) {
      return timesFromMultimodal[custId1];
    } else if (custId2 >= 0){
      return timesFromMultimodal[custId2];
    } else {
      return 0; //les 2 multimodal
    }
  }

public int[] getWindowEndTimes() {
    return windowEndTimes;
}

public double[][] getRameTimes() {
    return rameTimes;
}
public double[] getTimesFromMultimodal() {
    return timesFromMultimodal;
}

public int getNumRames() {
        return this.numRames;
      }}

And the class VrpReader

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

  public class VrpReader {

private static File f;

public static  VrpProblem readSolomon(String FilePath, int numRames) throws IOException{

        
    f = new File(FilePath);
    BufferedReader br = new BufferedReader(new FileReader(f));
    String line = br.readLine();
     String[] tokens = line.trim().split("\\s+");
        int depotX = (int)(Double.parseDouble(tokens[1]));
        int depotY = (int)(Double.parseDouble(tokens[2]));
        List<String> lines = new ArrayList<String>();
        for (int i = 0; i < numRames && (line = br.readLine()) != null; i++) {
          lines.add(line);
        }
        numRames = lines.size();
        int[] xCoors = new int[numRames];
        int[] yCoors = new int[numRames];
        int[] demands = new int[numRames];
        int[] windowStarts = new int[numRames];
        int[] windowEnds = new int[numRames];
        int[] serviceTimes = new int[numRames];
        double[][] rameTimes = new double[numRames][numRames];
        double[] timesFromMultimodal = new double[numRames];
        
        for (int i = 0; i < numRames; i++) {
            tokens = lines.get(i).trim().split("\\s+");
            //CUST NO.   XCOORD.   YCOORD.    DEMAND   READY TIME   DUE DATE   SERVICE TIME
            int x = (int)(Double.parseDouble(tokens[1]));
            xCoors[i] = (x);
            int y = (int)(Double.parseDouble(tokens[2]));
            yCoors[i] = (y);
            int windowStart = (int)(Double.parseDouble(tokens[4]));
            windowStarts[i] = (windowStart);
            int windowEnd = (int)(Double.parseDouble(tokens[5]));
            windowEnds[i] = (windowEnd);
            int serviceTime = (int)(Double.parseDouble(tokens[6]));
            serviceTimes[i] = (serviceTime);
          }
        
        for (int i = 0; i < numRames; i++) {
            for (int j = 0; j < numRames; j++) {
            int xDiff = xCoors[i] - xCoors[j];
            int yDiff = yCoors[i] - yCoors[j];
            rameTimes[i][j] = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
            
          }
        }
    
        for (int i = 0; i < numRames; i++) {
              int xDiffFromDepot = xCoors[i] - depotX;
              int yDiffFromDepot = yCoors[i] - depotY;
              timesFromMultimodal[i] = Math.sqrt(xDiffFromDepot * xDiffFromDepot + yDiffFromDepot * yDiffFromDepot);
        }
        
        VrpProblem problem = new VrpProblem(numRames, rameTimes, timesFromMultimodal, serviceTimes, windowStarts, windowEnds);
        return problem;
        } }

And the class Solution

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

 public class Solution{

private List<List<Integer>> routes;
private List<Integer> unrouted;
private int numLocomotives;
private VrpProblem problem;
private double toursCost = -1;

public Solution(VrpProblem problem) {
    this.problem = problem;
    this.routes = new ArrayList<List<Integer>>();
    this.unrouted = new ArrayList<Integer>();
}

public Solution(VrpProblem problem, List<List<Integer>> routes) {
    this.problem = problem;
    this.routes = routes;
    this.unrouted = new ArrayList<Integer>();

}

public Solution(VrpProblem problem, List<List<Integer>> routes, List<Integer> unrouted) {
    this.problem = problem;
    this.routes = routes;
    this.unrouted = unrouted;

}

public void setNumLocomotives(int numLocomotives) {
    this.numLocomotives = numLocomotives;
}

public void setRoutes(List<List<Integer>> routes) {

    this.routes = routes;
}

public void setUnrouted(List<Integer> unrouted) {
    this.unrouted = unrouted;
}

private double calcToursCost(List<List<Integer>> routes, VrpProblem problem) {
    double[][] times = problem.getRameTimes();
    double[] timesFromMultimodal = problem.getTimesFromMultimodal();

    double toursCost = 0;
    for (List<Integer> route : routes) {
        Iterator<Integer> iter = route.iterator();
        if (!iter.hasNext()) {
            continue;
        }
        int prev = iter.next();
        toursCost += timesFromMultimodal[prev];
        while (iter.hasNext()) {
            int cur = iter.next();
            toursCost += times[prev][cur];
            prev = cur;
        }
        toursCost += timesFromMultimodal[prev];
    }
    return toursCost;
}

public VrpProblem getProblem() {
    return problem;
}

public List<List<Integer>> getRoutes() {
    return routes;
}

public List<Integer> getUninsertedNodes() {
    return unrouted;
}

public int getNumLocomotives() {
    return numLocomotives;
}

public double getToursCost() {
    if (toursCost >= 0) {
        return toursCost;
    } else {
        return toursCost = calcToursCost(this.getRoutes(), this.getProblem());
    }
}

public void SolutionInitiale()

{
    VrpProblem problem=this.getProblem(); 
     int[] windowEndTimes = problem.getWindowEndTimes();
     int[] windowStartTimes = problem.getWindowEndTimes();
     double[] timesFromMultimodal = problem.getTimesFromMultimodal();
     int[] serviceTimes = problem.getServiceTimes();
     double[][] times = problem.getRameTimes();
    List<List<Integer>> routes =  new ArrayList<List<Integer>>();
     double[] timesFromDepot = problem.getTimesFromMultimodal();
    routes = this.getRoutes(); 
    HashSet<Integer> remainingNodes = new HashSet<Integer>();
    for (int i = 0; i < problem.getNumRames(); i++) {
        remainingNodes.add(i);
        }
        for (List<Integer> route : routes) {
          for (Integer node : route) {
            remainingNodes.remove(node);
          }
        }
        List<Integer> curRoute = new ArrayList<Integer>();
        routes.add(curRoute);
        int curNodeId = -1;
        double curVisitTime = 0;
        while (remainingNodes.size() > 0) {
            Iterator<Integer> iter = remainingNodes.iterator();
            while (iter.hasNext()) {
              int nextnodeId = iter.next();
              double distance = (curNodeId == -1) ? timesFromDepot[nextnodeId] : times[curNodeId][nextnodeId];
              int curLastServiceTime = (curNodeId == -1) ? 0 : serviceTimes[curNodeId];
              double minVisitTime = curVisitTime + curLastServiceTime + distance;
              
              if (minVisitTime < windowStartTimes[nextnodeId]) {
                  nextnodeId = curNodeId;
              }
              if (nextnodeId != -1) {
                    remainingNodes.remove(nextnodeId);
                    curRoute.add(nextnodeId);
                    curNodeId = nextnodeId;
                    curVisitTime = minVisitTime;
                  } else {
                    curRoute = new ArrayList<Integer>();
                    routes.add(curRoute);
                    curVisitTime = 0;
                    curNodeId = -1;
                  }
        }
     }
    
        this.setRoutes(routes);
        this.setNumLocomotives(routes.size());
    }}

And the main class

import java.io.IOException;
import java.util.ArrayList;
 import java.lang.management.ThreadMXBean;

       public class Test {

public static void main(String[] args) {
           VrpReader vr = new VrpReader();
          VrpProblem problem;
       try {
        problem =vr.readSolomon("D:\\c102.txt", 100);
          Solution initial = new Solution(problem);
    
        initial.SolutionInitiale();
        toString(initial);
        System.out.println("Pour test :"+initial.getToursCost());
        System.out.println("Pour test :"+initial.getNumLocomotives());
        System.out.println("-----------------------");




      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
  public static void toString(Solution sol) {
           System.out.println("La solution : " + sol.getRoutes()); 
  }
     }
         }

Example of data :
0 40 50 0 0 1236 0
1 45 68 10 0 1127 90
2 45 70 30 0 1125 90
3 42 66 10 0 1129 90
4 42 68 10 727 782 90

When I run my code it takes a long time without getting a result , I don't know what to do and where is the problem.




How to generate a random event-graph?

Require

There is a need for me to implement an eventGroup generator. eventGroup means one event must happen after collection A but can be concurrent happen with some others. Let's say generate graph with N ( N < 1000) events.

For example

    e1 --- e2 ---- e4 --- e5
        \-- e3 --/   \--- e6

Means that, e2 happen after e1, e3 after e1, e4 happen after both e2 and e3, e5/e6 happen after e4. So e2 and e3 (e5 and e6) can be concurrent.

Go playground

This is part of my working code, and you can test your algorithm here.

https://play.golang.org/p/xuoz1XrMH1l

My solution

Step1

generate N/2 level and tag event with level

Step2

For each event of each level, generate happen after relation, which 'big level after small level'. Generate this relation randomly.

Questions

  1. Is there a classic algorithm to do this job?
  2. Does my solution have a bug?
  3. Can you provide a better solution? (code or pseudo will be OK)



Making a PRNG class usable both on the CPU and GPU

I have a class (minimal example below) which is used to estimate certain probabilities, and uses random sampling extensively

#ifndef _MYCLASS_CUH_
#define _MYCLASS_CUH_

#include "curand_kernel.h"
#include <thrust/device_vector.h>
#include "tml.cuh"

class MyClass
{
private:
    
    // Number of samples to generate
    int n;

    curandState prng_state;
    
    // Normal distribution mean and covariance
    TML::Vector2f mu;
    TML::Matrix2f sigma;

    // Other variables below
    // ...
public:
    __host__ __device__ MyClass();

    // Other methods below
    // ...
};

#endif

where TML is a custom matrix library made for use on the GPU. The thing is I want this class to be usable both on the CPU and the GPU, but the curandState complicates things, as it cannot be used on the host side. Using e.g. the mersenne-twister std::mt19937 or other host implemented PRNGs on the other hand are not usable on the GPU.

I am looking for tips on various ways of making this class usable on both host/device side so I dont have to duplicate the class, like say MyClass_CPU and MyClass_GPU. How can I do this? I would also ideally want to use e.g. the Eigen library on the CPU, and my own TML library on the GPU, due to computational efficiency.




jeudi 28 janvier 2021

Android random text string

  • Everything is perfect but there is something missing!

  • Program error-free random works properly

  • but I want it to do the random inside the string. How can I do this? Can you give code directly

  • these are the current codes I use

Main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:id="@+id/tw1"
        android:textSize="50dp"
        android:text="0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <Button 
        android:id="@+id/btn1"
        android:text="random"
        android:textSize="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    

</LinearLayout>

Strings.xml

I want the words here to random

    <string name="app_name">JarTest</string>
    <string-array name="status">
        <item>Available</item>
        <item>Busy</item>
    </string-array>

Mainactivity.Java

Ex

String name[] = {"pls","sld","ohg","oug","tpp","ohf","yyyyyyy6",};

Buton click

Random m = new Random();
                        int index = m.nextInt(name.length - 0) + 0;
                        tw1.setText(name[index]);



Cant get my java class to display correct values (game) (getting all random damage to work, along with health)

I'm new to java and trying my hand at making a game. Here is what I have so far in my "combat class." Right now, if this was displayed with:

Combat fight1 = new Combat("Homeless Man", "Rusty Fork", 100, 110, 30); 

I would get the output:

Homeless Man hits you with a Rusty Fork, Dealing 0 damage!
You now have 0 HP left!
You hit Homeless Man With an attack using your null dealing 0 damage!
Homeless Man now has 100 HP left! 

Is there any way that I can fix this to make it display the right values (random damage, health values, damage values, etc.)

I know that this is a lot of code (and work) to look through, so all help is greatly appreciated!

The code for the "Combat" class is below:

package Walking;
import java.util.Random;
import java.util.Scanner;

public class Combat {

//enemy
String enemyName;
String enemyItem;
int enemyHP;
int enemyMaxDam;
int enemyMinDam;

public int damageDelt;

//player
public int playerHP;
public int playerMaxDam;
public int playerMinDam;

public int damageTaken;

//player armor
int clothes = 1;
int tux = 0;

//player weapon
String playerWeapon;
int fists = 1;
int bloodySpoon = 0;


public Combat() {
    if(clothes == 1) {
        playerHP = 1000;
    }else {
        if(tux == 1) {
            playerHP = 1100;
        }
    }
    
    if(fists == 1) {
        playerMaxDam = 75;
        playerMinDam = 30;
    }else {
        if(bloodySpoon == 1) {
            playerMaxDam = 100;
            playerMinDam = 75;
        }
    }
    
}

public Combat(String _enemyName, String _enemyItem, int _enemyHP, int _enemyMaxDam, int _enemyMinDam) {
    enemyName = _enemyName;
    enemyItem = _enemyItem; 
    enemyHP = _enemyHP;
    enemyMaxDam = _enemyMaxDam;
    enemyMinDam = _enemyMinDam;     
}

public int getDamageDelt() {
    Random rand = new Random();
    damageDelt = rand.nextInt(playerMaxDam = playerMinDam + 1) + playerMinDam;
    return damageDelt;
}

public int getDamageTaken() {
    Random rand = new Random();
    damageTaken = rand.nextInt(enemyMaxDam - enemyMinDam + 1) + enemyMinDam;
    return damageTaken;
}

public void displayCombat() {
    
    Scanner in = new Scanner(System.in);
    System.out.println("Will you:\n -Attack (1)\n -Consume Item (2) \n -Run (3)");
    String userInput = in.nextLine();
    if(userInput.equals("1")) {
        System.out.println(enemyName + " hits you with a " + enemyItem + ", Dealing " + damageTaken + " damage!");
        System.out.println("You now have " + (playerHP - damageDelt) + " HP left!");
        System.out.println("You hit " + enemyName + " With an attack using your " + playerWeapon + " dealing " + damageDelt + " damage!");
        System.out.println(enemyName + " now has " + (enemyHP - damageDelt) + " HP left!");
        
    }else {
        if(userInput.equals("3")) {
            System.out.println("You managed to escape the fight with " + playerHP + " left!");
        }
    }
    
}
}



How do I make 2 or more variable never be equal in Python?

First of all, sorry for any vocabulary mistake, I'm brazillian.

I'm new at programming and I've heard that one thing to do to improve your programming skills is try to create some projects, just for fun, and I'm trying to create some kind of Q&A game using the random function to shuffle the alternatives (A, B, C, D, E) at each try. Here is an example of what I want to do.

import random

list = [1, 2, 3, 4, 5]

n1 = (random.choice(list))
n2 = (random.choice(list))
n3 = (random.choice(list))
n4 = (random.choice(list))
n5 = (random.choice(list))

print("Question 1 - What is the result of 2+2?")

print("A){}.".format(n1))
print("B){}.".format(n2))
print("C){}.".format(n3))
print("D){}.".format(n4))
print("E){}.".format(n5))

The output is:

Question 1 - What is the result of 2+2?

A)4.
B)1.
C)2.
D)2.
E)4.

Process finished with exit code 0

I know its barely impossible to make each alternative be different every time with this code, and my question is: How can i make sure the alternatives will never be equal?




Random choosing 2 dictionaries: with same value

From a dictionary I wanna choose 2 dictionaries randomly who have their value[0] == 'C'.

d = {"1": ('B', [3, 4, 8]), "2": ('C', [2, 6, 8]), "3": ('C', [9, 10, 11, 13]), "4": ("E", [14, 15, 16, 17]), "5": ("C", [20])}
for key, val in d.items():
        if val[0] == 'B':

            b = val[0] == 'C'
            res = key, val = random.choice(list(d.items()))
            print(res)

e = {"2": ('C', [2, 6, 8]), "3": ('C', [9, 10, 11, 13])}
e = {"2, 3": ('C', [2, 6, 8] , [9, 10, 11, 13])}



how can i do random name picker in multiple textboxes in c# framwork

I need help with random name picker in multiple textboxes in c# framwork. can someone help me with how I can get started? how to think? I would appreciate the help! Have a Good day!!!




Python random square movement not working

I am trying to make a square that repeatedly moves forward a random amount of pixels, but here's what happens:

gui.move(ai, random.randint(10, 100, 10), 0) # gui is the tkinter canvas

then I get:

TypeError: randint() takes 3 positional arguments but 4 were given

How can I have 3 parameters but keep it the same?




How to get output of a normally distributed random number using python function in a range?

The question is related to:

  • How to get output of a normally distributed random number useing python function in a range?

Touching conditions:

  • Call python file with python function by bash
  • Give parameter from bash to python
  • Echo output of python function by bash

I already know the following:

bash.sh

#!/bin/bash
var_output= $(echo $'./python.py ')
echo $var_output

python.py

#!/usr/bin/env python3

import random

def normally_distributed_random_number():
    mu=10
    sigma=100
    print(random.normalvariate(mu, sigma))

normally_distributed_random_number()



JavaScript: Generate a unique 'x' numbers base on the range & set given

I am making a function that will generate a unique 'x' numbers base on the range & set given.

Examples

  • randomizer({ range: 50, set: 5 }) = [8, 16, 32, 40, 48]
  • randomizer({ range: 15, set: 3 }) = [4, 11, 15]
  • randomizer() = [2, 4, 5, 3, 1]

      function randomizer(data) {
          const dataRange = data && data.range
              ? data.range
              : 5;
          const dataSet = data && data.set
              ? data.set
              : 5;
    
          if (dataRange < dataSet) {
              console.log('Range cannot be lower than the Set!');
              return;
          }
    
          const randomizerRange = [];
          for (let r = 1; r <= dataRange; r++) {
              randomizerRange.push(r);
          }
    
          const randomizerSet = [];
          let randomNumber;
          for (let s = 1; s <= dataSet; s++) {
              randomNumber = Math.floor((Math.random() * (dataRange - s)) + 1);
              if (randomizerSet.includes(randomizerRange[randomNumber])) {
    
                  /*
                  make sure that the next number on randomizerSet is unique
                  this loop is crashing the browser 😔
                  */
                  let isUnique = false;
                  do {
                      randomNumber = Math.floor((Math.random() * (dataRange - s)) + 1);
                      if (!randomizerSet.includes(randomizerRange[randomNumber])) {
                          isUnique = true;
                      }
                  } while (!isUnique);
    
              }
              randomizerSet.push(randomizerRange[randomNumber]);
          }
    
          return randomizerSet;
      }

My issue is on the while loop, the browser is crashing 😔
I need help to make sure that the returned array will never have a repeated value? Thank you.




i want to make a program with c++ that choose 6 numbers randomly between 1 and 25 [closed]

I really want help with that how to make a code that choose 6 numbers randomly between 25 and 1 and every each time show 6 defrent numbers




How can I choose random items and write them in flutter

I create a specific pattern about persons and i have several persons how can i choose randomly and write it in specific pattern




How do I create a column with two values (or names) at a given weight in R

I'm trying to create a column in my data in .dbf. I need to create a column in which 70% is 0 (or TRUE) and 30% is 1 (or FALSE), only at random.

How can I do this?




How to access a random generated integer from other class without generating other random number

I have two classes

Class 1

public class Random {

    public static int random() {
        Random random = new Random();
        return random.nextInt(10);
    }
    public static int number = random();
}

and Class 2

public class FirstClass {
    
    static int generatedNumber = Random.number;

    public static void main(String[] args) {

            System.out.println(generatedNumber);
    }
}

Every time I try to access the generatedNumber variable of Class 2 from a third Class, the number I get is different and not the one received in Class 2.

My question is how I can make the number generated in Class 2 persist to be able to call it from other Classes and that it is always the same number generated in Class 2.

Thank you!




How do I change the order of solutions with my Discord bot?

Some time ago I received help here. This code is about making replies always appear in a different order in a message. But in the process everything gets mixed up. A random.choice event for each of the answers (A, B, C, D) and the questions was created. I would like however only that the answer possibilities remain random, speak:

1st attempt:

(9 is correct here)

A) 9

B) 8

C) 7

The answer given is "A", correct.

2nd run-up:

A) 8

B) 9

C) 7

Now "B" is given as the answer, that should also be counted as correct. How do I proceed?

My code:

        question_one = "How many lives do cat's have?"
        answers_one = {"9": "A", "1": "B", "10": "C"}


        questions = {question_one: {"9": answers_one}, "Is this working now?": {"A": {"Yes!": "A",
                                                                                       "No!": "B", "Maybe...": "C"}}}

        # get a question
        question = random.choice(list(questions.keys()))
        data = questions.get(question)
        correct_answer = list(data.keys())[0]
        answers = list(list(data.values())[0].items())
        question_msg = ""
        answers_msg = ""

        numbers_list = []
        answers_list = []

        for answer, number in answers:
            numbers_list.append(number)
            answers_list.append(answer)

        while numbers_list:
            num = numbers_list
            ans = random.choice(answers_list)
            answers_msg += f "**{num}) {ans}**\n"
            answers_list.remove(ans)
            numbers_list.remove(num)

My attempt was simply to remove the random function, but accordingly there is then no more list and nothing can be selected. My attempt to create a list also failed.




idle python 3.9.1 randint not defined

so I am running a code about two random numbers added together and you need to find an answer but it is saying that I have not defined randint and nothing I have tried worked thanks in advance and there may be more problems after this so if you notice anything else wrong please tell me




Everything is perfect but there is something missing

  • Everything is perfect but there is something missing!

  • Program error-free random works properly

  • but I want it to do the random inside the string. How can I do this? Can you give code directly

  • these are the current codes I use

Main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:id="@+id/tw1"
        android:textSize="50dp"
        android:text="0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <Button 
        android:id="@+id/btn1"
        android:text="random"
        android:textSize="50dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    

</LinearLayout>

Strings.xml

    <string name="app_name">JarTest</string>
    <string-array name="status">
        <item>Available</item>
        <item>Busy</item>
    </string-array>

Mainactivity.Java

Ex

String name[] = {"pls","sld","ohg","oug","tpp","ohf","yyyyyyy6",};

Buton click

Random m = new Random();
                        int index = m.nextInt(name.length - 0) + 0;
                        tw1.setText(name[index]);



discord.js random image is always the same

I'm making a grogu discord bot and want to send a random comic picture in an embed, when someone uses g!comic.

So far I have this:

client.on('message', message =>{
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        client.commands.get('ping').execute(message, args);
    }else if (command === 'comic') {    
        const random = new Discord.MessageEmbed()
          .setTitle('Here is your random grogu comic')
          .setImage(image)
    
        message.channel.send(random);
    }
});

The problem is, when I test it, it always sends the same picture/link and I don't know how to fix it.

This is where the images are stored:

const images = ["https://i.pinimg.com/originals/4d/2e/f3/4d2ef3052fab7b613733f56cd224118b.jpg", "https://red.elbenwald.de/media/image/a5/f8/e9/E1064005_1_600x600.jpg", "https://i.pinimg.com/736x/29/43/39/2943397229b5fb42cf12e8a1302d1821.jpg", "https://i.kym-cdn.com/photos/images/original/001/755/387/09f.jpg" ];
const image = images[Math.floor(Math.random() * images.length)];

*update: after restarting the bot, it shows a different picture, but it posts always the same until I restart the bot




Jspych- How to use randomization module in feedback variable following a image-button-response trial?

I am creating a task using Jpsych in which participants are shown an image and decide to either press either one of two buttons (PRESS vs NO PRESS). Depending on the button they press, they will be shown another image (stimuli A or stimuli B) drawn at random. I have the following code:

var button_pressed= [light_on1, light_on2, light_on3, light_on4, light_on5, light_on6, light_off1, light_off2, light_off3, light_off4];
var button_notpressed= [light_on7,light_on8,light_on9,light_on10,light_on11,light_on12,light_off5,light_off6,light_off7,light_off8];
var button_pressed_sample = jsPsych.randomization.sampleWithoutReplacement(button_pressed, 1);
var button_notpressed_sample = jsPsych.randomization.sampleWithoutReplacement(button_notpressed, 1);

 var timeline= [];

var trial_one = {
    type: 'image-button-response',
    stimulus: light_off,
    choices: ['PRESS','NO PRESS'],
    trial_duration: 3000,
    on_finish: function(data){
        if(data.key_press== 0){
        data.correct= true;
    } else {
        data.correct=false;
    }
}
}
var feedback_one = {
    type: "image-keyboard-response",
    trial_duration: 2000,
    stimulus:function(){
        var last_trial_correct=jsPsych.data.get().last(1).values()[0].correct;
        if (last_trial_correct){
            return button_pressed_sample;
        } else {
            return button_notpressed_sample
    }
    }
}
timeline.push(trial_one,feedback_one);

As of now, the code executes, but the stimuli are not being randomized in response to button press. Either all of the feedback stimuli are feedback A or all are feedback B. The code does not seem to be randomly sampling without replacement as I tried to indicate. Any help would be greatly appreciated!!




mercredi 27 janvier 2021

How to get random child from Firebase Database in Go?

I have a Firebase database with the following structure:

{
  "School" : {
    "Class A" : {
      "Student K" : [ "Language1", "Language2" ],
      "Student L" : [ "Language1", "Language2", "Language3 ],
    },
    "Class B" : {
      "Student M" : [ "Language1", "Language2" ],
      "Student N" : [ "Language1", "Language3 ],
      "Student O" : [ "Language1", "Language2", "Language3 ],
    },
  },
}

Here all languages are different and none of them are same for any student.

Now I want to retrieve a random Student and Languages pair from this database. I have reference upto the Class node.

Currently I am retrieving all the children of School/Class and then storing them in a map. To get a random key, value pair from them I just traverse the map once using range to get an arbitrary pair.

My code looks like this:

q := constants.GlobalClient.NewRef("School/" + className)
result := make(map[string][]string)
lang, studName := "", ""

if err := q.Get(constants.GlobalCtx, &result); err != nil {
    return nil, err
}

var allLang []string
for key, value := range result {
    studName = key
    allLang = value
    break
}

But, this is not providing the amount of randomness I would want, so I want to just retrieve a random Student, Languages pair from the database query itself.

I am new to using firebase with Go and can't seem to find a solution for this.




For loop repeats and generates more values than what is specified

I am trying to paste 3 rectangular images on a canvas. The goal is that the images are within the canvas and they do not overlap. For this, I decided to generate 3 two-tuple values that will serve as the locations of the xy coordinates of the image's top-left corner. Something like this:

locations_used = [(950, 916), (1097, 119), (1290, 526)]

What it instead does is that it repeats the first value 3x and then adds the 2 new values, giving me a total of 5 positions when I've specified 3. Like this:

[(950, 916), (950, 916), (950, 916), (1097, 119), (1290, 526)]

This is an MRE of my code:


    n = 3
    canvas_width = 500
    canvas_height = 300
    logo_width = 50
    logo_height = 30
    locations_used = []
    
    for i in range(0, n):
        
        logo_location_x, logo_location_y = logo_position(canvas_width, canvas_height, logo_width, logo_height)
        locations_used.append((logo_location_x, logo_location_y))

        for img in locations_used:
            if logo_location_x in range(img[0], logo_width) or logo_location_y in range(img[1], logo_height):
                pass
        else:
            while len(locations_used) < n:
                locations_used.append((logo_location_x, logo_location_y))

     print(len(locations_used))
     print(locations_used)
     print('\n')

The output:

5
[(950, 916), (950, 916), (950, 916), (1097, 119), (1290, 526)]



Odd Repetitions of Patterns When Using Rand()

Sample random password/string generator which generates 32 character strings. So, generates random numbers and keep those which are between 33 and 127 as these are the ASCII values which constitute valid text.

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

int main()
{
    srand(time(0));
    clock_t start = clock();

    long long iterations = 0;

    printf("Generating String...\n\n\t\" ");

    for (int i = 0; i < 32; i++)
    {
        long long holder = 0;
        while(holder < 33 || holder > 126)
        {
            holder = rand();
            iterations++;
        }
        putchar(holder);
    }

    clock_t end = clock();

    printf(" \"\n\n%.2lf s , %lld iterations & %lld avg\n",(double)(end - start)/CLOCKS_PER_SEC,iterations,iterations/32);

    return 0;
}

Output repeats the string DEX&H1_(okd/YVf8;49=el%<j:@"T,NU in one form or another.

Some Outputs :

Generating String...

    " DEX&H1_(okd/YVf8;49=el%<j:@"T,NU "

9.11 s , 893836506 iterations & 27932390 avg
Generating String...

    " xq?!#O]tDEX&H1_(okd/YVf8;49=el%< "

7.59 s , 768749018 iterations & 24023406 avg
Generating String...

    " MJxq?!#O]tDEX&H1_(okd/YVf8;49=el "

7.63 s , 748742990 iterations & 23398218 avg

Compiled with cc file.c -o file on Clang/macOS.




java, Generate n random non-zero numbers that add up to a specific sum with each random number is a multiple of 0.5

I'm having trouble trying to generate n non-zero numbers adding up to a specific sum with each random number is a multiple of 0.5 . For example, generate 3 numbers that add up to 6, the output can be : 1.5, 2.5, 2.

Could someone help me with it please. Thanks in advance.




why cant I keep my randomly generated elements in list? [closed]

I have the following function which generates 'n' random combinations of k tuples from a main list, list_1:

list_1=[(0, 1), (0, 2), (0, 5), (0, 10), (0, 20), (0, 50), (0, 100), (2, 1), (2, 2), (2, 5), (2, 10), (2, 20), (2, 50), (2, 100), (5, 1), (5, 2), (5, 5), (5, 10), (5, 20), (5, 50), (5, 100), (10, 1), (10, 2), (10, 5), (10, 10), (10, 20), (10, 50), (10, 100), (20, 1), (20, 2), (20, 5), (20, 10), (20, 20), (20, 50), (20, 100), (50, 1), (50, 2), (50, 5), (50, 10), (50, 20), (50, 50), (50, 100), (100, 1), (100, 2), (100, 5), (100, 10), (100, 20), (100, 50), (100, 100)]

rand_list=[]
def rand_gen(n):

    for i in range(n):
        i=random.choices(list_1, k=6)
        if i not in rand_list:
            rand_list.append(i)

rand_gen(3)

print(rand_list)

which gets the following output:

print(rand_list)
>>>[[(50, 2), (20, 5), (50, 20), (2, 1), (2, 100), (5, 2)], [(50, 20), (20, 1), (20, 50), (2, 20), (20, 100), (20, 20)], [(50, 20), (2, 5), (2, 100), (100, 50), (100, 2), (100, 10)]]

My issue is that when I run the function again to get another n lists of k tuples, I get a whole new list, instead of keeping the old values and appending the new ones, like so:

[[(100, 100), (100, 10), (0, 5), (0, 1), (0, 10), (50, 2)], [(0, 50), (100, 20), (2, 100), (20, 10), (100, 50), (0, 100)], [(0, 2), (0, 5), (20, 10), (2, 50), (5, 10), (0, 1)]]

As you can see its a new list and the ones originally generated have vanished.

Does anyone know how i can keep the original combinations for subsequent runs of the function, rather than just replacing them over and over?




Generating 3 random tuples within specified ranges

My goal is to generate locations for where I will be drawing rectangular images on a canvas. I want to generate 3 locations that will stay within the canvas while preventing overlap-. This is my approach:

for i in range(0, len(logos)):

    # Opens the first logo in the random sample as a PIL image
    logo = Image.open(current_dir + '/Logos/' + logos[i], 'r').convert('RGBA')
    logos_used.append(logos[i]) # Adds the current logo inside logos_used

    logo_width, logo_height = logo.size  # Gets the dimensions of the current augmented logo

    # A random position for the 1st logo
    logo_location_x, logo_location_y = logo_position(canvas_width, canvas_height, logo_width, logo_height)
    locations_used.append((logo_location_x, logo_location_y))

    # Working to generate positions for the logos. The logic inside this while loop is incomplete.
    # Because I already have 1 location tuple saved, I now have to get n-1 locations more.
    while len(locations_used) < n-1:
        # Here, I am generating random locations
        logo_location_x = random.randint(0, canvas_width - logo_width)
        logo_location_y = random.randint(0, canvas_height - logo_height)
        
        # I am traversing through every generated location
        for i in range(0, len(locations_used)):

            # Here, I am checking for overlaps.
            if logo_location_x not in range(locations_used[i][0], logo_width) 
           and logo_location_y not in range(locations_used[i][1], logo_height):
                locations_used.append((logo_location_x, logo_location_y))

    print(locations_used)

The main for loop has more code than what you see. It also takes care of drawing the logos on the canvas one by one. len(logos) is at most 3. I removed most of that code to keep it brief and to the point. My goal, as I said, is to generate 3 locations on the canvas that don't overlap the images.

However, this is my output:

[(45, 14)]
[(45, 14), (467, 401)]
[(596, 638)]
[(596, 638), (127, 50)]
[(396, 419)]
[(396, 419), (709, 173)]
[(370, 42)]
[(370, 42), (570, 95)]
[(25, 124)]
[(25, 124), (765, 189)]
[(631, 544)]
[(631, 544), (430, 445)]
[(1688, 149)]
[(1688, 149), (862, 123)]

The output should be 3 two-tuples of locations on the canvas. Not what I have above.




randomizing numbers found in text doesn't find all numbers

My goal is to search a text, find all numbers, and randomize each number. The numbers are not written as digits, but as words. I've written a small test script, and this gives me the correct result. But in the actual text, my code doesn't find each word that is a number, it only finds one word. The text in my file is this:

    [{"text": "ZIP code for your address? Three, zero, zero five, eight. bye.", "s": 1090, "speaker": "Unknown", "e": 1787571}]

The code is like this:

    def digit_randomize_json(list_path, jsonDir, output):


        digits = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", 
    "ten", "zero"]
        generated_digit = (random.choice(digits))

        with open (list_path, 'r') as list_file:
            for raw_filename in list_file:
                filename = raw_filename.rstrip()
                pathandfile = os.path.join(jsonDir, filename)
                f = open(pathandfile)
                data = json.load(f)
                f.close()
                words = data['transcript']['turns'][0]['text']
                words = words.split()

                for word in words:
                    word = word.lower()
                    if word in digits:
                        word = generated_digit

                        with open(os.path.join(output, filename), 'w' ) as outfile:
                            print("processing", filename)
                            json.dump(data, outfile)

What I would expect to have as a result is "[{"text": "ZIP code for your address? four, four, five nine, zero. bye.", "s": 1090, "speaker": "Unknown", "e": 1787571}]

Instead, I get a result that is unchanged. But even if I try inserting a print statement to print out the "word" variable, I'll only get one digit back.

Here's my test code that works:

    import random

    x = ['one','two','three','four','five','six']
    y = 'once i was three and then i was four'
    y_split = y.split()
    for word in y_split:
        if word in x:
            word = random.choice(x)
            print word

I've looked at these over and over and can't see what is the thing that is preventing the actual code from working. Can someone point out what I'm doing wrong?




How to fill an Array with random numbers and search through them [closed]

Im working on an assignment where we have to fill an array with random numbers then search through the array to see if a certain number exists, all of it works except whenever I run it, it says the number im looking for is In the array 10,000 times (which is how many numbers I fill the array with)

public class MethodResource {
        
    public static void fillTheArray(int[] iTempArray, int SIZE) {
        // Finished - Don't alter!
        final int RANGE = 2500;
        Random rand = new Random();
    
        for (int index = 0; index <= SIZE - 1; index++){
            iTempArray[index] = rand.nextInt(RANGE);
        }
    }//end of fillTheArray



Java Math random() to print only one number

How could i get this code to just give me ONE number between 0-9.

At the moment it prints 10 numbers between that 0-9 but i need it to just pick one number from 0-9

import java.lang.Math;

public class random {
public static void main(String args[])
{
  int max = 9;
  int min = 0;
  int range = max - min + 1;

for (int i = 0; i < 9; i++) {
    int rand = (int)(Math.random() * range) + min;

System.out.println(rand);
}
}
}



Calculate random variables from grouped dataframe

I have a data frame called stats. I'd like to group by month_name and item and generate a random variable drawn from a normal distribution in a new column called rv.

This is the code I tried but it repeats the generation of 1 random variable in the rv column:

stats %>%
  group_by(month_name, item) %>%
  mutate(rv = rnorm(1, mean = mean, sd = sd))

The goal is to eventually replicate the rv output 10,000 times. How can I modify my code to generate the random variable for every row once and 10,000 times?

This is my data:

structure(list(month_name = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 
5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 
8L, 8L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 11L, 11L, 
11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L), .Label = c("January", 
"February", "March", "April", "May", "June", "July", "August", 
"September", "October", "November", "December"), class = c("ordered", 
"factor")), item = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 
2L, 3L, 4L, 5L), .Label = c("a", "b", "e", "d", "c"), class = "factor"), 
    min = c(39853.3676768762, 11963.7336771844, 28475.0829411315, 
    36241.9007031999, 35743.7750504859, 16092.552892924, 12528.9369640133, 
    28363.8516762228, 29557.1911907891, 20577.9268503088, 26012.6643332399, 
    43743.1386573406, 33757.0104608081, 24012.3644652027, 29987.8232384625, 
    26663.1671529956, 50724.1357441692, 33156.7203254077, 36604.0975795671, 
    32448.5497811945, 47818.2983698804, 25173.5205474241, 29648.7882981325, 
    39034.0329768052, 15083.5548610647, 41560.8896893507, 40563.2944650284, 
    48794.4526055819, 35895.1783353774, 30085.4271923688, 39675.7305889162, 
    33628.9557047603, 36950.5993766457, 30593.5091646214, 28957.5398056329, 
    37080.7178800747, 45454.3924797489, 28755.6280571895, 34733.1340290652, 
    37227.9361452194, 21493.809533368, 33292.9944106622, 28137.6372068055, 
    25582.8046285949, 23073.0637573296, 28846.9082264882, 19454.182866794, 
    33869.2858697563, 19016.7538627489, 30647.6876387916, 35123.8965500988, 
    34146.2780735908, 40593.6508043686, 26908.3734089905, 47178.2458120079, 
    24665.5899193578, 22701.4906439165, 50735.1331088719, 36108.7624278488, 
    21415.5715318508), lower = c(54524.7101912146, 26928.6804993352, 
    25119.8847919585, 45942.5372327181, 52100.762800828, 23399.2712234262, 
    14178.7907654734, 71366.6268933559, 49209.2124037853, 54643.7588467776, 
    48369.7944054794, 29515.3335011807, 41577.635577101, 25357.3837384686, 
    43253.4733925982, 43401.4748829102, 37741.3586860236, 52294.4029786582, 
    58136.6122795486, 43617.5523486807, 46648.1777348884, 47822.6060157009, 
    37122.0182632065, 65447.4620274838, 29544.1919272749, 54822.3562275875, 
    64814.4174753617, 65538.2587526896, 39975.4034746898, 59117.6049731313, 
    49024.4324422717, 25273.7368374795, 56946.7596272533, 50660.5745923196, 
    37221.8185672126, 30508.2772838287, 47172.6674212663, 52956.1465111511, 
    45488.8349086128, 52660.1832157037, 37406.8854102724, 25601.012749268, 
    41414.610113642, 41145.7009104373, 26879.9690641376, 69323.7347440924, 
    59453.3099916568, 19260.9187209561, 14090.2250971317, 41778.9038974128, 
    35013.9160392596, 39672.0871995261, 57517.2881078087, 52765.3573599843, 
    57267.2271717807, 54869.720268229, 58525.9231470629, 44610.285805162, 
    47317.3995094377, 17599.590085043), mean = c(58549.8098049081, 
    56374.4327553941, 39864.1715264267, 85333.1530921059, 64454.2358008729, 
    63343.4098283811, 69838.6859070403, 41935.3881398536, 40239.4399412696, 
    70073.2291007902, 57535.295477502, 76197.4454180647, 60836.2074195693, 
    64601.7379215889, 51599.3556004457, 49092.0124309883, 47319.767991988, 
    63121.0872241636, 43048.0322965586, 77405.4987695189, 64320.8901918307, 
    53059.7915920758, 63712.4934804165, 37248.933469329, 48285.12302248, 
    60352.1030623367, 67648.010113929, 52282.8579266665, 63868.4373429784, 
    71370.1455147326, 59275.2217698193, 74524.7831867724, 62464.1935824186, 
    50255.8945012446, 31094.1686136834, 75833.6439248775, 32190.7391406323, 
    77010.5148506178, 69635.0888164364, 65885.8987213858, 54022.7135642953, 
    35801.3865465657, 60637.9983665307, 90783.7721781328, 57264.0603250172, 
    59977.2976696403, 71712.656969139, 76705.4011709067, 89462.5059367925, 
    76714.0458753254, 56859.5782454854, 66820.0053236744, 58243.7435076688, 
    52843.8704599132, 77247.3384533588, 55515.7748808548, 75004.3165800858, 
    88370.1869726297, 68628.9281194796, 53895.0496305422), median = c(42352.1610450345, 
    57330.3183802072, 55273.2047201131, 82351.3852530883, 46370.4898234873, 
    52386.0432388715, 47943.0683307536, 53897.781347776, 67858.0064600009, 
    73013.024717384, 83116.7356352266, 44401.5903576421, 69025.6068023045, 
    81625.3403276092, 43344.4404418446, 49701.9746204065, 44889.5603216509, 
    86449.7649043697, 52150.9769065634, 58675.8138647348, 55665.7047792249, 
    44566.4888204713, 50517.7492643733, 73778.9515308994, 60652.1631558926, 
    87345.0069311662, 68268.9807235179, 41356.3226356087, 41585.1763113502, 
    75144.8373297139, 81967.7788670882, 66041.6207332688, 55103.8870449834, 
    77301.4195253735, 54130.4774678618, 65176.7990367632, 46834.9652749994, 
    65134.3889325556, 76621.5018669346, 89066.7483257445, 79344.8597627239, 
    50867.4889878177, 51326.3717332736, 74843.6262595514, 66235.6184875188, 
    98300.5112442494, 51378.9240605971, 61277.8214283028, 48915.1245226839, 
    52765.9194941648, 47028.8412992194, 74841.2039136489, 70896.5761749783, 
    67414.0877191645, 60655.1682545525, 42707.2850070942, 51244.6187187212, 
    70889.9732948709, 82834.1260629236, 56029.4540887989), upper = c(96808.9361470916, 
    72722.9262056796, 89079.513341868, 84709.1878768955, 87694.368834914, 
    87860.8548839792, 80996.3827453218, 84247.9259137302, 95585.6388675179, 
    57338.746606262, 88681.3926853573, 87957.989278465, 87360.6574510974, 
    92664.4254709955, 73493.0826366849, 84230.5990186054, 81442.2517006442, 
    87801.9592453634, 107883.319372054, 101919.939543795, 78090.4252899963, 
    70239.1417329303, 100675.767786787, 99806.9236049608, 71452.5071326737, 
    73879.3479602876, 106131.22309752, 125238.035074805, 76731.6350473027, 
    105563.285669622, 98604.105083167, 88657.8428176833, 81133.2031578456, 
    92495.2957986084, 104836.803460225, 102419.6178137, 86160.3548401189, 
    87287.9179449312, 72987.3973022452, 73185.0732579627, 90916.179982239, 
    111282.33982277, 142168.512194455, 100479.774695548, 118375.00968986, 
    116099.107730658, 105747.461541425, 106715.198136428, 128585.197217447, 
    87996.5319472346, 67831.1501517932, 109713.080164634, 78535.3157822644, 
    128602.704986898, 82213.8086826659, 118591.773718681, 66518.2467960131, 
    91250.5061727746, 117072.914540123, 114524.034290364), max = c(137612.711045413, 
    142519.370905613, 137456.124250483, 149209.014602568, 158745.717583772, 
    144886.189765236, 168837.723206789, 148308.890270968, 158590.65413993, 
    152288.303209753, 154042.306686713, 143922.848061827, 147477.579594905, 
    147438.066965268, 141502.628117831, 150285.096748915, 148713.594899874, 
    156656.255445038, 151517.357942321, 146177.731181398, 130056.291991729, 
    150991.849546995, 150476.190905448, 140149.802748207, 162573.574139209, 
    124218.878401843, 140313.610415297, 156852.359228369, 147676.550419975, 
    139922.178103581, 131822.195549853, 143008.968758112, 142237.425864494, 
    148756.818388612, 123905.560034301, 157126.60664862, 132868.19652461, 
    137884.902850549, 142164.212835827, 144616.429331364, 154277.663061656, 
    156870.781144851, 170948.478868233, 154970.297432983, 144661.430142095, 
    151193.528913062, 136056.623739965, 132695.069145067, 144366.408646971, 
    154456.483407293, 143518.023088591, 145811.265404348, 139900.024678788, 
    127547.709882734, 149995.24047052, 145400.958382574, 159524.480570906, 
    118905.663549293, 161631.72583606, 147524.546274058), sd = c(9989.37951375166, 
    9906.50689980405, 9903.6852849217, 10008.3321579478, 10075.4653993515, 
    10063.7122293343, 10053.0016932606, 9826.1129055558, 9855.88655389009, 
    10028.7176055065, 10070.3833732403, 9941.07465801432, 10094.2667749602, 
    9910.53181242413, 10104.5889493016, 9851.70104229335, 9972.91821342281, 
    10080.4485086333, 10044.5102818099, 10037.3707232711, 10025.1107006076, 
    10022.3659427419, 9941.51637265177, 9873.12826319285, 10027.9036424549, 
    10033.6518983864, 9970.47127759776, 9937.3319252128, 10013.3439414305, 
    10030.3125017708, 10168.5115559098, 10213.3568382367, 9990.24289183087, 
    9968.82189362707, 10048.7504375345, 10015.8411633632, 10037.6851291425, 
    9925.92765463682, 9835.81447415085, 9782.6505066721, 10033.5360418173, 
    9991.76186224687, 9924.86818104305, 9970.41809893224, 9980.55197551292, 
    9886.97032019385, 9925.73912143071, 9971.01687402101, 9858.19281102242, 
    9969.19466304141, 9955.12658457894, 10139.5950943687, 9967.09479735319, 
    10168.1650679826, 10023.9501235604, 9821.41776472295, 10064.1149573067, 
    10134.8532916488, 9943.57024828908, 9833.93164357077)), row.names = c(NA, 
-60L), groups = structure(list(month_name = structure(1:12, .Label = c("January", 
"February", "March", "April", "May", "June", "July", "August", 
"September", "October", "November", "December"), class = c("ordered", 
"factor")), .rows = structure(list(1:5, 6:10, 11:15, 16:20, 21:25, 
    26:30, 31:35, 36:40, 41:45, 46:50, 51:55, 56:60), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, 12L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))



List Input Problems [closed]

I am trying to make a password cracker, by asking the user for different information. After the user inputs this information, the code is supposed to give a list of different passwords, by randomly mixing the information the user gave. However, when I tried to put the different variables into a list, it says "NameError: undefined". I'm thinking this is because the variable is equal to input instead of something else. If I put quotation marks around the variable, it becomes a string. I'm a beginner and I'm still confused about how to fix this.

enter image description here enter image description here




Restart Countdown Timer with New Random Variable - Javascript

I found this countdown timer somewhere online and am trying to combine it with a random number generator. I'm also trying to restart the timer automatically while generating a new random number to base the timer off of. For example, first random number would be around 5 seconds, a countdown would commence down to 0, then it would generate a new random number, reset the countdown based on that new random number, and commence to countdown to 0, etc. (Timer "EXPIRED" isn't necessary to have - I left it as a placeholder for me to make sure the code was working.)

Most of what I have Googled shows a start/stop/restart button of some sort, which I am trying to avoid - or uses a static variable that doesn't change. Any assistance is appreciated.

r = 5*Math.random();
document.getElementById("rv").innerHTML = r


// Set the date we're counting down to
var countDownDate = new Date().getTime();
countDownDate = countDownDate + (r*1000);

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();
    
  // Find the distance between now and the count down date
  var distance = countDownDate - now;
    
  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

}, 200);





JAVA choose a random object

Hi there im new with Java and i cant find the way to get or choose a random object from my list products.I tried so many different ways but is always giving me an error.

    
public class VendingWorking {
    
    List<Product> products= new ArrayList<>();
    
    
public void registerProducts() {
    CStamp stampOne=new CStamp("1 Jan 2000", "Collectable Stamp");
    CStamp stampTwo=new CStamp("1 Jan 2000", "Collectable Stamp");
    CStamp stampThree=new CStamp("14 Feb 2000", "Collectable Stamp");
    CCoin coinOne= new CCoin("25 Jan 2019", "Collectable coin");
    Ccar carOne= new Ccar(2015, "Tin Car Toy");
    Ccar carTwo= new Ccar(2018, "Tin Car Toy");
        
        products.add(stampOne);
        products.add(stampTwo);
        products.add(stampThree);
        products.add(coinOne);
        products.add(carOne);
        products.add(carTwo);
    
    }
    public void getRandomElement(List<Product> products){ 
        Random random = new Random(); 
        Product index=products.get(random.nextInt(products.size())); 
    } 

    public List<Product> getRegProducts() {
        return products;
    }
}
    



Julia, function to replicate "rbinom()" in R

I have dug around and googled but not found an example. I'm sure Julia has a powerful function (in base?) to generate random binomial (bernoulli?) "successes" with a given probability. I can't find it or figure out how to do the equivalent to in Julia:

> rbinom(20,1,0.3)
 [1] 1 1 1 0 0 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0

Thx. J




Replacing all duplicate numbers in an Array, so that every element is unique in C

The elements in the array are created using rand().

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

int main(void){
    int array[6] = { 0 };
    
    srand(time(NULL));
    
    for(int i = 0; i < 6; i++){
        array[i] = rand() % 49 + 1;
    }
    
    /*
        Code to check for duplicates
        if duplicate found
            duplicate = rand(49);
    */
    
    for(int i = 0; i<6; i++){
            printf("[%d]",array[i]);
        }
    
    return 0;
}

I don´t really want to sort the array if it makes it easier to find duplicates because the array is for a lottery ticket. I have tried different methods, but all of them are inefficient and includes a lot of loops. I had different approaches, but all of them didn´t really work, because what if, the newly created number, is yet again a duplicate? Or if the last number in the array is a duplicate. So I came with the following approach: The algorithm will create as many areas, as long no number in the array is a duplicate

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define TRUE 1

int main(void) {
    int a[6] = {0};
    srand(time(NULL));

    while (TRUE) {

        int c = 0;

        for (int i = 0; i < 6; i++) {
            a[i] = rand() % 49 + 1;
        }

        for (int i = 0; i < 6; i++) {
            for (int j = i + 1; j < 6; j++) {
                if (a[i] == a[j]) {
                    c++;
                }
            }
        }
        if (c == 0) {
            break;
        }
    }
    
    for (int i = 0; i < 6; i++) {
        printf("%d\n", a[i]);
    }

    return 0;
}

Any Ideas, how to make an easy, efficient, but not so complex algorithm for a beginner?

Thanks :)




mmdetection cannot get the same results among multi runs after setting the random seed

Even though I set the random seed, and deterministic is true, the values of losses are different among multi runs. enter image description here




mardi 26 janvier 2021

If statement that will generate 5 random numbers that sum to 210 and then write these numbers to excel openpyxl

I need to write a script that will generate 5 random whole numbers that sum up to 210 and then take these 5 generated numbers and write them to excel using openpyxl, the excel sheet will then check to see if a certain cell's content is less than a certain number and if it isn't then the program will run again until it checks out.

so far I have defined my workbook and worksheet in question I have tried the following to generate the random numbers

a = np.random.random(210)

a /= a.sum()

The numbers returned aren't whole numbers...that's the first problem.

My other problem is going to be storing the 5 random numbers in a way that I can use them with an if statement to write to my excel sheet.

I've written many scripts that interact with excel but I haven't tried to do anything like this where it will be constantly looping and checking and i'm a bit in over my head.

If you have any helpful info it would be very much appreciated!! Thank you!!




How to obtain all possible values returnable by Random.nextLong?

The Random#nextLong() documentation states that this method will not return all possible long values:

Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. The general contract of nextLong is that one long value is pseudorandomly generated and returned. The method nextLong is implemented by class Random as if by:

public long nextLong() {
    return ((long) next(32) << 32) + next(32);
}

Because class Random uses a seed with only 48 bits, this algorithm will not return all possible long values.

For example, the number 8090327796378429294 is generatable, but the number 8090327796378429295 is not, even though their only difference is one least significant bit, and the value itself is 63 bits long.

There's a way to know whether or not a value can be returned by nextLong() using the following algorithm:

public class JavaRandom {
    private static final long ADD = 0xBL;
    private static final long MULT = 0x5DEECE66DL;
    private static final long TWO16 = 1L << 16;
    private static final long MASK_31 = (1L << 31) - 1;
    private static final long MASK_32 = (1L << 32) - 1;
    private static final long MASK_48 = (1L << 48) - 1;

    public static boolean canBeGeneratedByJavaRandom(long randomValue) {
        long i1 = (randomValue >> 32) & MASK_32;
        long i2 = (randomValue & MASK_32);
        if (i2 > MASK_31) {
            i1 = i1 + 1;
        }

        long front = i1 << 16;
        for (long i = 0; i < TWO16; i++) {
            long seed = front | i;
            long i22 = (((seed * MULT) + ADD) & MASK_48) >> 16;
            if (i22 == i2) {
                return true;
            }
        }

        return false;
    }
}

How can I get all values that can be generated by nextLong() without running this check for every possible 64-bit number? Calling nextLong() until all values are collected doesn't feel reasonable as well as there can be collisions.