I have two Strings with a number. I like to randomize beetween these two. With this code : let random = Int.random(in: myvar1…myvar2)
it wont work. How can i do this?
samedi 31 juillet 2021
Swift randomizer with variables
JS Shuffle the array of obj [closed]
"financings" is an array of objects. I want to scramble it and press the result array into the "plan" array, but the problem I encountered is: all "items" are consistent, I originally wanted to " Use "math.random" to replace the decimal after "return". The results of scrambled are all consistent, but it was scrambled once. I want to know how to make this "financings" scrambled five times.my code
console.log(financings)
var item= financings.sort(function(){return 0.2515775912009759>0.5?-1:1;});
console.log("item",item)
plan.push(item)
var item1= financings.sort(function(){return 0.6191500571921469>0.5?-1:1;});
console.log("item1",item1)
plan.push(item1)
var item2 = financings.sort(function(){return 0.5689188611053764>0.5?-1:1;});
console.log("item2",item2)
plan.push(item2)
var item3 = financings.sort(function(){return 0.8989393604075584>0.5?-1:1;});
console.log("item3",item3)
plan.push(item3)
var item4= financings.sort(function(){return 0.6471469188965746>0.5?-1:1;});
console.log("item4",item4)
plan.push(item4)
rolling multiple dice and taking the max value observed and plotting a histogram
Considering an event where you roll multiple dice and take the max value observed. I am writing a function that will randomly simulate this event multiple times and return the maximum value obtained in each trial.
Not really sure what I have done is correct. Also, I would like to plot a histogram of resulting max values but plt.hist dosen't seem right. Any insights will be appreciated
import random
def multipleRolls(numberoftrials, numberofdice):
trial_list=[]
min = 1
max = 6
for i in range (1,numberoftrials+1):
m=0
for j in range(1,numberofdice+1):
k = random.randint(min, max)
if m<k:
m=k
trial_list.append(m)
plt.hist(trial_list)
plt.show()
print(trial_list)
multipleRolls(3,5)
How to extract some elements randomly from two dimensional list? / Python
I have a 6 x 6 list.
list = [[i for i in range(6)] for j in range(6)]
And I want to extract some elements randomly and then, I wand to change that elements to other character (for example, 'x').
list = [[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]]
randomed_list = [[0, 1, x, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, x, 2, 3, 4, 5],
[0, 1, x, 3, 4, 5],
[0, x, x, 3, x, 5],
[0, 1, 2, 3, x, x]]
How can I do? Thanks! :-)
How do I not get whitespaces while generating a random string which should contain special characters in python?
I have been working on a password management system and need to auto-generate a password which should be alphanumeric and have special characters but no whitespaces.
password = ''.join(random.choice(string.ascii_letters + string.digits + string.printable) for _ in range(14))
But this causes some problems and also generates '\n' and ' ' Any way by which I can fix this? Or any other simple method to generate a string meeting the requirements? Thank you
vendredi 30 juillet 2021
Assigning keys and storing in a dictionary Python
For an event of rolling a six-sided die. I need to randomly simulate the event 1000 times and plot a histogram of results for each number on the dice. I want to assign the results for each number to a key of the same value (1 for number of 1s{1:164...}).
I need help assigning keys and storing everyting in a dictionary
import random
test_data = [0, 0, 0, 0, 0, 0] #this will keep track of the results
n = 1000 # number of simulations
for i in range(n):
result = random.randint(1, 6)
test_data[result - 1] = test_data[result - 1] + 1
for i in range(len(test_data)):
print ("Number of ", i+1, "'s: ", test_data[i])
Shuffling an array using random-choice method instead of using Fisher-Yates
I am stuck with an apparently simple problem. I have written a subroutine that accepts an array of length n
and another number m
as inputs, and then outputs an array with size m
which contains uniformly randomly chosen numbers from the original array. I can pass replace=False
option, and then the numbers in the output array are always distinct given that there are no repetitions in the original array. My question is, can I use the same routine to randomly shuffle an array? At first sight this looks possible if I input m=n
. The problem is that I am not sure whether this will output every possible permutation of the input array with equal probability (Although I would be surprised if it doesn't!). If that doesn't happen, I will write another routine for Fisher-Yates shuffle.
how to generate no-repetetive numbers in c langage?
I want to do the distribution of high school classes on teachers of a subject in a random way, my only condition is not to exceed 21 hours of work for each teacher. For this I have declared a structure TAB which contains each class (filliere) as well as its number of hours. another structure TAB1 contains the classes as well as an integer 0 or 1 which allows to know if I have assigned this class to a teacher or not yet.
my program compiles and runs but it doesn't print anything.
I want to generate randomly different numbers from 0 to 18. for example if the function rand() gives the number 15, I want to be sure sure that the next number shouldnt be 15,and so on, instead of TAB1 structure.
#include <string.h>
#include <stdio.h>
#include <time.h>
typedef struct nombreheure
{
char *classe;
int nombreheure;
}nombreheure;
typedef struct nombreclasses
{
char *classe;
int affecte;
}nombreclasses;
int main ()
{
nombreheure TAB[19];
TAB[0].classe="TCLF1";
TAB[1].classe="TCLF2";
TAB[2].classe="TCSF1";
TAB[3].classe="TCSF2";
TAB[4].classe="TCSF3";
TAB[5].classe="TCSF4";
TAB[6].classe="1LSHF1";
TAB[7].classe="1LSHF2";
TAB[8].classe="1LSHF3";
TAB[9].classe="1SEF1";
TAB[10].classe="1SEF2";
TAB[11].classe="1SEF3";
TAB[12].classe="2BACSP1";
TAB[13].classe="2BACSP2";
TAB[14].classe="2BACL1";
TAB[15].classe="2BACL2";
TAB[16].classe="2BACSVT1";
TAB[17].classe="2BACSVT2";
TAB[18].classe="TCSF5";
TAB[0].nombreheure=5;
TAB[1].nombreheure=5;
TAB[2].nombreheure=2;
TAB[3].nombreheure=2;
TAB[4].nombreheure=2;
TAB[5].nombreheure=2;
TAB[6].nombreheure=5;
TAB[7].nombreheure=5;
TAB[8].nombreheure=5;
TAB[9].nombreheure=2;
TAB[10].nombreheure=2;
TAB[11].nombreheure=2;
TAB[12].nombreheure=5;
TAB[13].nombreheure=5;
TAB[14].nombreheure=2;
TAB[15].nombreheure=2;
TAB[16].nombreheure=2;
TAB[17].nombreheure=2;
TAB[18].nombreheure=2;
nombreclasses TAB1[19];
TAB1[0].classe="TCLF1";
TAB1[1].classe="TCLF2";
TAB1[2].classe="TCSF1";
TAB1[3].classe="TCSF2";
TAB1[4].classe="TCSF3";
TAB1[5].classe="TCSF4";
TAB1[6].classe="1LSHF1";
TAB1[7].classe="1LSHF2";
TAB1[8].classe="1LSHF3";
TAB1[9].classe="1SEF1";
TAB1[10].classe="1SEF2";
TAB1[11].classe="1SEF3";
TAB1[12].classe="2BACSP1";
TAB1[13].classe="2BACSP2";
TAB1[14].classe="2BACL1";
TAB1[15].classe="2BACL2";
TAB1[16].classe="2BACSVT1";
TAB1[17].classe="2BACSVT2";
TAB1[18].classe="TCSF5";
TAB1[0].affecte=0;
TAB1[1].affecte=0;
TAB1[2].affecte=0;
TAB1[3].affecte=0;
TAB1[4].affecte=0;
TAB1[5].affecte=0;
TAB1[6].affecte=0;
TAB1[7].affecte=0;
TAB1[8].affecte=0;
TAB1[9].affecte=0;
TAB1[10].affecte=0;
TAB1[11].affecte=0;
TAB1[12].affecte=0;
TAB1[13].affecte=0;
TAB1[14].affecte=0;
TAB1[15].affecte=0;
TAB1[16].affecte=0;
TAB1[17].affecte=0;
TAB1[18].affecte=0;
int heuremax=21;
int n=0;
char *classe;
srand(time(NULL));
do
{
int val= rand()%19;
if (TAB1[val].affecte=0)
{
TAB1[val].affecte=1;
classe=TAB[val].classe;
n=n+TAB[val].nombreheure;
printf("\n la classe est %s , et le nombre totol d'heures est %d \n ",classe,n);
}
} while(n<21);
}
Randomly sample non-empty column values for each row of a pandas dataframe
For each row, I would like to randomly sample k columnar indices that correspond to non-null values.
If I start with this dataframe,
A = pd.DataFrame([
[1, np.nan, 3, 5],
[np.nan, 2, np.nan, 7],
[4, 8, 9]
])
>>> A
0 1 2 3
0 1.0 NaN 3.0 5.0
1 NaN 2.0 NaN 7.0
2 4.0 8.0 9.0 NaN
If I wanted to randomly sample 2 non-null values for each row and change them to the value -1, one way that can be done is as follows:
B = A.copy()
for i in A.index:
s = A.loc[i]
s = s[s.notnull()]
col_idx = random.sample(s.index.tolist(), 2)
B.iloc[i, col_idx] = -1
>>> B
0 1 2 3
0 -1.0 NaN -1.0 5.0
1 NaN -1.0 NaN -1.0
2 -1.0 -1.0 9.0 NaN
Is there a better way to do this natively in Pandas that avoids having to use a for loop? The pandas.DataFrame.sample
method seems to keep the number of columns that are sampled in each row constant. But if the dataframe has empty holes, the number of non-null values for each row wouldn't be constant.
How do i store a binary number in an array?
Ok, so i been working on this right here that is intended to be part of a encryption software that works synonymously like 2fa
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int RGX;
int box[32];
srand (time(NULL));
RGX = rand() % 100000000 + 9999999;
cout << "Random Generated One Time HEX #:" << endl;
cout << std::hex << RGX << endl;
while(RGX!=1 || 0)
{
int m = RGX % 2;
cout << " " << m << " ";
RGX = RGX / 2;
cout << RGX << endl;
}
return 0;
}
Here is a sample of what it outputs:
Random Generated One Time HEX #:
3ff3c70
0 1ff9e38
0 ffcf1c
0 7fe78e
0 3ff3c7
1 1ff9e3
1 ffcf1
1 7fe78
0 3ff3c
0 1ff9e
0 ffcf
1 7fe7
1 3ff3
1 1ff9
1 ffc
0 7fe
0 3ff
1 1ff
1 ff
1 7f
1 3f
1 1f
1 f
1 7
1 3
1 1
** Process exited - Return Code: 0 **
The result is different each time since it's randomized, i'm still not finished. But what i need to know is how do i store the binary value in an array, the binary value are the numbers on the left.
Using numpy default_rng with Dask?
I'd like to know how I can use a numpy default random number generator with Dask.
The documentation for e.g. dask.array.random.normal
has a note saying :
New code should use the normal method of a default_rng() instance instead
I assume that is because the documentation is copied from numpy. In numpy they introduced a default random number generator so that one can have rngs with different seeds (in contrast to the old global numpy.random.seed) but I can't figure out how to use one with the Dask random functions.
How to generate a non-intersecting polygon like an island , which is not necessarily convex? [closed]
I would like to generate a polygon, that doesn't have intersecting edges, but not necessarily convex.
I want to use it for a game. It would represent an island/continent. The more it resembles a real continent, the better. There's no need of heightmap, only the shape.
I'd store it in an array, x and y coordinates would alternate in it.
And it would be completely random, but would fit in a given area.
I'm thinking something like this:
Oracle adding randim amount if seconds to a date
I have a date that is always set to midnight i.e. '07312021 00:00:00' how can I use dbms_random.value to add (1 second, 23:59:59) to that date.
How to generate a non-intersecting polygon, which is not necessarily convex?
I would like to generate a polygon, what doesnt have intersecting edges, but not necessarily complex.
Thanks in advance.
jeudi 29 juillet 2021
SQL Server: Select random records with no duplicates
For an auditing project, need to select at random three tracking IDs per associate and cannot be dups. Wondering if it's possible with SQL?
Sample SQL Server Data:
Associate | Tracking ID |
---|---|
Smith, Mary | TRK65152 |
Smith, Mary | TRK74183 |
Smith, Mary | TRK35154 |
Smith, Mary | TRK23117 |
Smith, Mary | TRK11889 |
Jones, Walter | TRK17364 |
Jones, Walter | TRK91736 |
Jones, Walter | TRK88234 |
Jones, Walter | TRK80012 |
Jones, Walter | TRK55874 |
Williams, Tony | TRK58142 |
Williams, Tony | TRK47336 |
Williams, Tony | TRK13254 |
Williams, Tony | TRK28596 |
Williams, Tony | TRK33371 |
Regards, Manny
C# Generate Random Number on Program First Startup and Keep it the Same Every Time it is Ran Again For a File Password
I am making a log system for my app, but don't want the user to edit the log. I want the app to get a random number for this password, but I don't want it to be the same for other users of the program, to keep each log as safe as possible. But I don't know how to do this, while being able to have the password be the same every time the app is started. How should I go about this? Thanks in advanced!
Lua PRNG results repeating numbers in succession
I'm attempting to pick a number, either 1 or 2.
1 = bob wins, 2 = alice wins.
When iterating over 10000~ attempts, there appears to be a high 'streak' of repeating numbers, for example 1 being repeated 15-20 times in a row.. This doesn't seem right, is this too high?
Example code:
local bobWins = 0
local aliceWins = 0
local bobWinStreak = 0
local aliceWinStreak = 0
local bobHighestStreak = 0
local aliceHighestStreak = 0
local lastWinner = ""
for i=1,10000 do
local num = math.random(1,2)
if num == 1 then winner = "bob" else winner = "alice" end
if winner == "bob" then
bobWins = bobWins + 1
if lastWinner == "bob" then
bobWinStreak = bobWinStreak + 1
aliceWinStreak = 0
if bobWinStreak > bobHighestStreak then
bobHighestStreak = bobWinStreak
end
end
else
aliceWins = aliceWins + 1
if lastWinner == "alice" then
aliceWinStreak = aliceWinStreak + 1
bobWinStreak = 0
if aliceWinStreak > aliceHighestStreak then
aliceHighestStreak = aliceWinStreak
end
end
end
lastWinner = winner
end
print("BOB WINS: " .. bobWins,"BOB HIGHEST STREAK: " .. bobHighestStreak)
print("ALICE WINS: " .. aliceWins, "ALICE HIGHEST STREAK: ".. aliceHighestStreak)
Example output:
BOB WINS: 5036 BOB HIGHEST STREAK: 25
ALICE WINS: 4964 ALICE HIGHEST STREAK: 19
Is this normal to expect, 15-20 (25 in the given example) bob wins in succession and vice versa for alice? How can I achieve a more fair 50/50 result? The spread/distribution between the two are OK (5036:4964 is tolerable and pretty 50:50 I would say) but I personally wouldn't have expected more than say 5/6 in a row..
Furthermore, increasing the iterations does change the streak numbers (albeit slightly), but not by a huge amount.. 10,000,000 iterations returns a streak of 30-35 on average...
Pseudorandom number generator
I want to write a Python program that generates random numbers. I have already tried the following
import random
from random import randrange
a = randrange(9999)
print('Multiplier a is: ',a)
m = randrange(9999)
print('Modulus m is: ',m)
c = randrange(9999)
print('Increment c is: ',c)
x0 = randrange(9999)
print('Seed x0 is: ',x0)
i = 0
while i<1000:
x1 = (a*x0 + c) %m
x0 = x1
i+=1
print(x1)
The program works, but my problem is that i do not know how to stop the sequence if i get the same random numbers x_n=x_m. Also, is there some way to save the resulting numbers to a file?
Random number does not change for every guess the program is supposed to make and I cannot figure out how to change the min and max saved values
The game is supposed to ask the user to think of a number. Then add the minimum value and maximum value. The program is then supposed to tell the user that it will guess the number in a specific amount of guesses. This is determined by taking the square root of Maximum and subtracting the Minimum Plus 1. The program is then supposed to guess the number and ask the user if it is too high, too low, or correct. Based on the answer the Minimum or Maximum value should change and the computer should guess again until either the computer guessed the right number or the computer has exceeded its amount of guesses. If the program guesses right it should display, "I Win!" If the computer exceeds it's guesses it should display, "Cheaters Never Win!" I am extremely new to coding and my brain just cannot figure out how to fix all the issues.
The Results Display: Think of an integer value... What is the Lowest value: 5 What is the highest possible value: 30 I will guess your value in 5 guesses. My guess #1 is 9. My guess #2 is 9. My guess #3 is 9. My guess #4 is 9. My guess #5 is 9. Is that too (H)igh, too (L)ow, or (C)orrect? Cheaters Never Win!
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class guess
{
public static void main(String[] args){
Scanner input=new Scanner(System.in); //Created new scanner object
System.out.println("Think of an integer value...");
System.out.println("What is the Lowest value:");
int min=input.nextInt();
System.out.println("What is the highest possible value:");
int max=input.nextInt();
double y=Math.sqrt(max-min+1);
double DoubleValue=y;
int IntValue=(int) DoubleValue;
System.out.println("I will guess your value in " + IntValue + " guesses.");
int randomNum=ThreadLocalRandom.current().nextInt(min, max + 1);
int i=1;
for(i=1; i<y; i++)
System.out.println("My guess #" + i + " is " + randomNum + ".");
System.out.println("Is that too (H)igh, too (L)ow, or (C)orrect?");
String answer=input.nextLine(); {
if(answer.equalsIgnoreCase("H")){
max=(max-randomNum)-max;
System.out.println("My guess #" + i + " is " + randomNum + ".");
System.out.println("Is that too (H)igh, too (L)ow, or (C)orrect?");
answer=input.nextLine();
}
else if(answer.equalsIgnoreCase("L")){
min=(randomNum-min)+min;
System.out.println("My guess #" + i + " is " + randomNum + ".");
System.out.println("Is that too (H)igh, too (L)ow, or (C)orrect?");
answer=input.nextLine();
}
else if(i>y){
System.out.println("Cheaters Never Win!");
}
else{
System.out.println("I Win!");
}
}
}
}
How to implement probability / attraction for a patch in a random movement?
Situation: The agent moves according to Brownian motion. At each iteration, it can go in any direction, with the step ranging from 0 to a certain radius. Some patches have a feature that increases the likelihood of attracting the agent.
e.g. if there is a patch with the feature, the agent has a 70% chance of going to it and not to others.
Question: How do I implement this probability in the agent's movement?
Attempt: I managed to implement probability when I analyze only the agent's neighbor patches, using the move-to
. But I need to implement this probability in a ray using fd
.
How to get 50% probability from random generator, produces 0, 1 and 2 values
A random generator produces values from the list: 0, 1, 2 (with equal probabilty for all three values).
How to get only two values (50%: 0 and 50%: 1) from no more than ten uses of the generator.
Lognormal Distribution
When defining a lognormal function with a mean of 15.1466 and a standard deviation of 0.3738, the result you should get is the following:
However when I run the following code to do it with python the result I get is not the same.
mu, sigma = 15.1466, 0.3738
s = np.random.lognormal(mu, sigma, 10000)
count, bins, ignored = plt.hist(s, 30,
density=True,
color='blue')
x = np.linspace(min(bins),
max(bins), 10000)
pdf = (np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))
/ (x * sigma * np.sqrt(2 * np.pi)))
plt.plot(x, pdf, color='black')
plt.grid()
plt.show()
Is there a way to generate 60 random numbers between 0 to 1 and check if first 3 digits of any numbers is repeated [closed]
import random
for i in range 60:
print(random.random())
what should I write after this pls help
mercredi 28 juillet 2021
How to select random documents from the MongoDB collection but not the previous ones?
I have a collection of videos in MongoDB and want to select random videos documents from that collection the below code is working fine
const videos = await Video.aggregate([{ $sample: { size: Number(num) } }]);
but it also includes the previous result in the next query. I want to select random videos documents but not the previous ones.
R dataframe filling named columns with random sample data
I am trying to generate a lot of test data for other programs. Working in R Studio I import an SPSS sav file which has 73 variables and the values and labels recorded in it using Haven as a dataframe "td". This gives me all the variable names which I need to work with. Then I delete all the existing data.
td <- td[0,]
Then I generate 10,000 test data rows by loading the index IDs
td$ID <- 12340000:12349999
So far so good.
I have a constant called ThismanyRows <- 10000
I have a large list of Column header names in a variable called BinaryVariables
And a vector of valid values for it called CheckedOrNot <- c(NA, 1)
This is where the problem is:
td[,BinaryVariables] <- sample(x = CheckedOrNot, size= ThismanyRows, replace = TRUE)
does fill all the columns with data. But its all exactly the same data, which isn't what I want. I want the sample function to run against each column, but not each value in each column as in.
Even when
Fillbinary <- function () {sample(x = CheckedOrNot, size= ThismanyRows, replace = TRUE)}
and
td <- lapply(td[,BinaryVariables],Fillbinary)
generates: Error in FUN(X[[i]], ...) : unused argument (X[[i]])
So far I have not been able to work out how to deal with each column as a column and apply the sample function to it.
Any help much appreciated.
(PYTHON) Calling Class Function(s) of 2 Classes at Each Other
I made two classes that would call each other's function before releasing a result but I'm having trouble making it work, is there a reason why I could call the function of the first class above but not the function of the one below?
HERE IS THE PROGRAM:
import random
HAND = []
DECK = ['Ojama Red', 'Ojama Blue','Ojama Yellow','Ojama Green','Ojama Black', 'Ojama Pink', 'Ojama Lime']
class A:
def func1(self):
random.shuffle(DECK)
B.func3()
def func2(self):
c = DECK[0]
if c in DECK:
HAND.append(c)
DECK.remove(c)
class B:
def func3(self): # STANDBY
self.func4()
def func4(self): # DRAW
A.func2()
self.func5()
def func5(self): # MAIN PHASE 1
print('\n', HAND)
print('\n', DECK)
start_game = A()
start_game.func1()
Ho can I get these images to appear in random spots on the page?
I am creating a collage app that has an dogAPI. When the breed is selected a dog image will appear. I want the image to appear in a random spot on the page but ideally not over the text and dropdown menu. This is what I have tried and here is my codepen. This is an app so it needs to also be responsive.
//Get a random number
let getRandomNum = (num) => {
return Math.floor(Math.random() * Math.floor(num));
}
//show image in a random location
let moveImg = () => {
let dogImgs = document.querySelector('.dogPic')
let w = window.innerWidth;
let h = window.innerHeight;
dogImgs.style.top = getRandomNum(w) + "px";
dogImgs.style.left = getRandomNum(h) + "px";
};
https://codepen.io/drxl/pen/VwbQZyK
Choose random numbers from a range except numbers in a list
I have a for loop where at each turn I choose a random number from a constant range. However, I never want to get a duplicate value. This is how I am doing it now:
import random
my_range = 1000
chosen = [81, 944, 576, 618, 333, 350, 579, 774, 86, 511, 619, 552, 804, 44, 894, 408, 242]
for i in range(500):
rand_ind = random.randint(0,1000)
while rand_ind in chosen:
rand_ind = random.randint(0,my_range)
chosen.append(rand_ind)
print(chosen)
Is there any way to do this in one line or more efficiently?
Creating a random numbers for a range if dates
I have some working SQL below that generates a row for each employee_id.
I could use some SQL expertise modifying my SQL code to call the function, generate a range of dates, for each date generate N (1-10) rows for each employee_id. I want to remove the call to dbms_random.value (0, 2) + dbms_random.value (0, .75) and replace it with the value returned from the generate_dates_pipelined() FUNCTION. Once this works I intend to put this code in a procedure so I can pass it a range of dates.
Below is some sample output for a single day.
EMPLOYEE_ID CARD_NUM LOCATION_ID ACCESS_DATE
1 F123456 10 07302021 09:47:48
1 F123456 5 07282021 19:17:42
2 R33432 1 4 07282021 02:00:37
3 C765341 2 07282021 17:33:57
3 C765341 6 07282021 17:33:57
3 C765341 1 07282021 18:53:07
4 D564311 6 07282021 03:06:37
ALTER SESSION SET
NLS_DATE_FORMAT = 'MMDDYYYY HH24:MI:SS';
CREATE OR REPLACE TYPE nt_date IS TABLE OF DATE;
CREATE OR REPLACE FUNCTION generate_dates_pipelined(
p_from IN DATE,
p_to IN DATE
)
RETURN nt_date PIPELINED DETERMINISTIC
IS
v_start DATE := TRUNC(LEAST(p_from, p_to));
v_end DATE := TRUNC(GREATEST(p_from, p_to));
BEGIN
LOOP
PIPE ROW (v_start);
EXIT WHEN v_start >= v_end;
v_start := v_start + INTERVAL '1' DAY;
END LOOP;
RETURN;
END generate_dates_pipelined;
Create table employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
last_name VARCHAR2(20),
card_num VARCHAR2(10),
work_days VARCHAR2(7)
);
ALTER TABLE employees
ADD (
CONSTRAINT employees_pk PRIMARY KEY (employee_id)
);
INSERT INTO employees (
EMPLOYEE_ID,
first_name,
last_name,
card_num,
work_days
)
WITH names AS (
SELECT 1, 'Jane', 'Doe', 'F123456', 'NYYYYYN' FROM dual UNION ALL
SELECT 2, 'Madison', 'Smith', 'R33432','NYYYYYN' FROM dual UNION ALL
SELECT 3, 'Justin', 'Case', 'C765341','NYYYYYN' FROM dual UNION ALL
SELECT 4, 'Mike', 'Jones', 'D564311','NYYYYYN' FROM dual )
SELECT * FROM names;
CREATE TABLE locations AS
SELECT level AS location_id,
'Door ' || level AS location_name,
CASE round(dbms_random.value(1,3))
WHEN 1 THEN 'A'
WHEN 2 THEN 'T'
WHEN 3 THEN 'T'
END AS location_type
FROM dual
CONNECT BY level <= 10;
ALTER TABLE locations
ADD ( CONSTRAINT locations_pk
PRIMARY KEY (location_id));
SELECT
e_id AS employee_id,
card_num,
l_id AS location_id,
trunc(sysdate) + dbms_random.value (0, 2) + dbms_random.value (0, .75) AS access_date
FROM (
SELECT
employee_id AS e_id,
row_number() OVER (ORDER BY dbms_random.value) AS rn, card_num
FROM employees
) x
JOIN (SELECT
location_id AS l_id,
row_number() OVER (ORDER BY dbms_random.value) AS rn
FROM locations) y USING (rn)
ORDER by employee_id, location_id;
Best way to set up RNG for use in class? (C++)
I'm writing a class that contains an unordered_map
dispatch holding anonymous functions. The class is declared in a header file and defined in a separate .cpp file. I'm currently defining my map in the constructor's initializer list.
Chip8::Chip8()
: dispatch
{
{0x00e0, [this]() { display.fill(0); }},
...
In one of these functions, I need to obtain a random number. I presume this is an issue understanding scope as I am unsure where to seed my RNG.
What is the difference between SeedSequence.spawn and SeedSequence.generate_state
I am trying to use numpy's SeedSequence
to seed RNGs in different processes. However I am not sure whether I should use ss.generate_state
or ss.spawn
:
import concurrent.futures
import numpy as np
def worker(seed):
rng = np.random.default_rng(seed)
return rng.random(1)
num_repeats = 1000
ss = np.random.SeedSequence(243799254704924441050048792905230269161)
with concurrent.futures.ProcessPoolExecutor() as pool:
result1 = np.hstack(list(pool.map(worker, ss.generate_state(num_repeats))))
ss = np.random.SeedSequence(243799254704924441050048792905230269161)
with concurrent.futures.ProcessPoolExecutor() as pool:
result2 = np.hstack(list(pool.map(worker, ss.spawn(num_repeats))))
What are the differences between the two approaches and which should I use?
Using ss.generate_state
is ~10% faster for the basic example above, likely because we are serializing floats instead of objects.
Turning a linear time for loop into a log(n) time function?
In an interview, I was asked to describe a function that could return a random number given an object with {names:weights}
as an input. I would be allowed to use a library to generate numbers between [0,1]
but nothing else. I answered that the task need be broken in down into:
-
Ensuring that weights be cumulative
[0.25, 0.5, 0.25]
->[0.25, 0.75, 1]
, saving asc_arr
-
Produce a random number between
[0,1]
save as aval
, then iterate through myc_arr
via a for loop. Ifval
is > theith
element inc_arr
, continue, else return the name associated with theith
element.
My interviewer noted that this was acceptable, however, asked if I could articulate its performance using Big O notation. I'm not very knowledgeable here but answered that it should be in linear time. He responded that this is true; however, the pseudo could function could be improved to log(n)
time.
To my knowledge, log(n)
time would mean not iterating through each and every integer in the range [0,1,2,3,4,5,6,7,8...x]
but rather something like [1,2,4,8,...X]
. I'm not sure that this is validated. But even if it is, I'm not sure how the pseudo code function could be improved such that it didn't need to iterate through every element in c_arr
in a linear fashion.
Could someone explain?
How to Fix Rock Paper Scissors Logic Not Working when there is Tie?
I made a simple rock paper scissors game using HTML JavaScript & CSS & RandoJs For Random Picks But i am having Some Logic Issues
var rock = document.getElementById("rock"); // Getting User pickable Rock Element
var paper = document.getElementById("paper"); // Getting User Pickable Paper Element
var scissor = document.getElementById("scissor"); // Getting User Pickable Scissor Element
let robotPick = ["rock", "paper", "scissor"]; // What Robot Can Pick
// Getting Human Score Element For Changing Scores
var humanScore = document.getElementById("humanScore");
var robotScore = document.getElementById("robotScore");
var message = document.getElementById("message"); // Getting message Element
// Adding Event Listeners To Pickable Elements
window.addEventListener("load", function(e) {
rock.addEventListener("click", function(e) { checkWin("rock"); });
paper.addEventListener("click", function(e) { checkWin("paper"); });
scissor.addEventListener("click", function(e) { checkWin("scissor"); });
});
function checkWin(pick) {
let humanPick = pick;
let picks = rando(robotPick).index; // What Robot Will Pick is Generated Randomly using RandoJS
let whoWon; // This Will Contain Who Won
// Main Logic
if (humanPick === "rock" || robotPick[picks] === "rock") whoWon = "tie";
if (humanPick === "rock" || robotPick[picks] === "paper") whoWon = "robot";
if (humanPick === "rock" || robotPick[picks] === "scissor") whoWon = "human";
if (humanPick === "paper" || robotPick[picks] === "paper") whoWon = "tie";
if (humanPick === "paper" || robotPick[picks] === "scissor") whoWon = "robot";
if (humanPick === "paper" || robotPick[picks] === "rock") whoWon = "human";
if (humanPick === "scissor" || robotPick[picks] === "scissor") whoWon = "tie";
if (humanPick === "scissor" || robotPick[picks] === "rock") whoWon = "robot";
if (humanPick === "scissor" || robotPick[picks] === "paper") whoWon = "human";
// Checking Who Won!
if (whoWon === "human") {
let x = parseInt(humanScore.innerHTML);
message.innerHTML = "Robot Chose " + robotPick[picks];
x++; humanScore.innerHTML = x;
}
if (whoWon === "robot") {
let x = parseInt(robotScore.innerHTML);
message.innerHTML = "Robot Chose " + robotPick[picks];
x++; robotScore.innerHTML = x;
}
if (whoWon === "tie") {
let x = parseInt(robotScore.innerHTML);
message.innerHTML = "Robot Chose " + robotPick[picks];
x++; robotScore.innerHTML = x;
}
}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock, Paper & Scissors</title>
<style>*{transition:all 0.2s ease;-webkit-transition:all 0.2s ease}body{position:absolute;font-family:sans-serif;transform:translate(-50%, -50%);background:#252525;left:50%;top:50%;user-select:none}.body i{font-size:4em;margin:5px}.score{font-size:1.5em;text-align:center;margin-top:2em}p{margin:20px 0;padding:0;color:#ffd900;font-size:0.9em}#hands{text-align:center}#hands i{margin:10px;font-size:3em;color:#ffd900;cursor:pointer}#hands i:hover{transform:scale(1.3)}.humanScore{color:#48ff00}.robotScore{color:#00ccff}</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
<div id="hands">
<i id="rock" class="fas fa-hand-rock"></i>
<i id="paper" class="fas fa-hand-paper"></i>
<i id="scissor" class="fas fa-hand-peace"></i>
</div>
<div class="score">
<span class="humanScore"><i class="fas fa-user-alt"></i> <span id="humanScore">0</span></span>
<span class="robotScore"><i class="fas fa-robot"></i> <span id="robotScore">0</span></span>
<p id="message">Choose First</p>
</div>
<script src="https://randojs.com/2.0.0.js"></script>
When there is a Tie it is not working, and I am using RandoJs for randomly picking robot's Pick Is there any other way to do so ?
I have specified what i have done inside of the code using comments
And Also i am using Font Awesome 5 For Icons!
mardi 27 juillet 2021
How to pop duplications only once from a list by comparing to another list in Python 3
I'm trying to write a card game where the cards are assigned numerical values.
a = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
b = [1, 2]
How do I remove b
(cards you draw from a deck) from a
to get:
c = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3]
Or... How do I take a random sample away from a
to make a separate list b
?
map range of IEEE 32bit float [1:2) to some arbitrary [a:b)
Back story : uniform PRNG with arbitrary endpoints
I've got a fast uniform pseudo random number generator that creates uniform float32 numbers in range [1:2) i.e. u : 1 <= u <= 2-eps
. Unfortunately mapping the endpoints [1:2) to that of an arbitrary range [a:b) is non-trivial in floating point math. I'd like to exactly match the endpoints with a simple affine calculation.
Formally stated
I want to make an IEEE-754 32 bit floating point affine function f(x,a,b)
for 1<=x<2
and arbitrary a,b that exactly maps 1 -> a
and nextlower(2) -> nextlower(b)
where nextlower(q)
is the next lower FP representable number (e.g. in C++ std::nextafter(float(q),float(q-1))
)
What I've tried
The simple mapping f(x,a,b) = (x-1)*(b-a) + a
always achieves the f(1) condition but sometimes fails the f(2) condition due to floating point rounding.
I've tried replacing the 1
with a free design parameter to cancel FP errors in the spirit of Kahan summation. i.e. with f(x,c0,c1,c2) = (x-c0)*c1 + c2
one mathematical solution is c0=1,c1=(b-a),c2=a
(the simple mapping above), but the extra parameter lets me play around with constants c0,c1,c2
to match the endpoints. I'm not sure I understand the principles behind Kahan summation well enough to apply them to determine the parameters or even be confident a solution exists. It feels like I'm bumping around in the dark where others might've found the light already.
Aside: I'm fine assuming the following
- a < b
- both a and b are far from zero, i.e. OK to ignore subnormals
- a and b are far enough apart (measuered in representable FP values) to mitigate non-uniform quantization and avoid degenerate cases
Issues with IF repeating loops
To preface, I'm very new to coding with python and coding period. I've made a dice roller in python which allows the user to decide the number of sides, as well as the number of dice rolled. The code works as intended, but I keep getting an error message whenever I do multiple re-rolls and exit out. I've posted a screenshot of the error message and copied over the code too. I'd really appreciate any feedback, and thanks for reading this far. Error Message
## Roller v2
def Roll2():
print("""
[ - - - Welcome to Roller v2! - - - ]
""")
sides = int(input("How many sides? : "))
dice = int(input("How many dice? : "))
modifier = input("Any Modifiers (Include +/-) : ")
def roller():
import random as rand
from random import choices
d_inf = range(1, sides+1)
d_choice = choices(d_inf, k=dice)
print("""Wowee, you rolled :
""")
print(d_choice)
print(""" """)
print("Unadded Modifiers : (" + modifier + ")")
repeat = str(input("Would you like to roll the same dice again? (y/n) : "))
if repeat in ["y", "Y"]:
roller()
elif repeat in ["n", "N"]:
exit = str(input("Would you like to exit? (y/n) : "))
if exit in ["y", "Y"]:
print("Goodbye!\n")
elif exit in ["n", "N"]:
Roll2()
roller()
How to generate random big quantity in python turtle module
So, I want to create a game in Turtle python module, and I need to generate a randomly large amount of tiles as well.
Random coordinates generator
I want to generate random coordinates for spheres in a box geometry. I'm using while loop and i have 2 condition. First one is the distance of coordinates. General distance formula was used so that the coordinates do not overlap. Second one is the porosity. When porosity is less than 0.45 generating should stop. My code is working correctly but when i reduce porosity condition less than 0.80 the algorithm stucks. It cannot reach that porosity even after hours. How can I improve it to generate coordinates faster? Any suggestions are appreciated.
#dist = math.sqrt(((x2-x1)**2) + ((y2-y1)**2) + ((z2-z1)**2))
import math
import random
import numpy as np
import matplotlib.pyplot as plt
A = 0.04 # x border.
B = 0.04 # y border.
C = 0.125 # z border.
V_total = A*B*C # volume
r = 0.006 # min distance of spheres.
radius = 0.003 # radius of spheres.
wall_distance = 0.003
Porosity = 1.0
coordinates = np.array([])
while Porosity >= 0.90:
# coordinates
x = random.uniform(wall_distance, A-wall_distance)
y = random.uniform(wall_distance, B-wall_distance)
z = random.uniform(wall_distance, C-wall_distance)
coord1 = (x,y,z)
if coordinates.shape[0] == 0: # add first one without condition
coordinates = np.array([coord1])
else:
coordinates = np.vstack((coordinates, coord1))
# seperate x,y,z and convert list for control
d_x = coordinates[:,0]
x = d_x.tolist()
d_y = coordinates[:,1]
y = d_y.tolist()
d_z = coordinates[:,2]
z = d_z.tolist()
for j in range(len(y)):
for k in range(j+1, len(z)):
dist = math.sqrt(((x[j]-x[k])**2) + ((y[j]-y[k])**2) + ((z[j]-z[k])**2))
if dist <= r:
coordinates = coordinates[:-1, :] # if distance is less than r, remove last coordinate
# check porosity
V_spheres = (4/3) * (np.pi) * (radius**3) * len(coordinates)
V_void = V_total - V_spheres
Porosity = V_void / V_total
print("Porosity: {}".format(Porosity))
print("Number of spheres: {}".format(len(coordinates)))
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.set_xlim([0, A])
ax.set_ylim([0, B])
ax.set_zlim([0, C])
ax.set_title('Coordinates for spheres')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
p = ax.scatter(coordinates[:,0], coordinates[:,1], coordinates[:,2])
fig.colorbar(p)
plt.show()
Trying to generate random numbers in VBA, code returning only values that already exist in the table
I cannot get what this is doing.
For a data entry work, I need to generate a transaction number for each entry.
I have a simple function that returns a string created from a random number:
Public Function GetNewTnum() As String
Randomize 10
GetNewTnum = "SL-" & Int(Rnd * 1000000)
End Function
When I call the function in the sub, not only is it generating the same number everytime it runs, the number can already be found in the data set, which only has 577 entries at the moment!
In the sub, after generating the string, it checks to see if has already been used and another function returns true/false. A loop keeps testing until the generated string has not been found and uses this in the entry:
Public Function finddupTnum(ByRef num As String) As Boolean
Dim f As Range
Set f = inputws.Range("tblDataMaster[Tnum]").Find(num, , xlValues, xlWhole)
If f Is Nothing Then
finddupTnum = False
ElseIf Not f Is Nothing Then
finddupTnum = True
End If
End Function
Loop structure works fine. And even before the code reaches the loop, the first random number that gets generated is as described above:
Dim i As Integer
For i = 1 To 7
If Not Me.Controls("Product" & i) = "" Then
With newrow
newtnum = GetNewTnum()
MsgBox "First tnum: " & newtnum
valb = finddupTnum(newtnum)
MsgBox "Found? " & valb
Do While valb = True
newtnum = GetNewTnum()
valb = finddupTnum(newtnum)
MsgBox "New tnum: " & newtnum
MsgBox "New tnum dound? " & valb
Loop
The loop can't end because all the values generated already exist.
Thank you for your help!
Random String form array - Windows Forms c++ Visual Studio
I want, when I run the program, every button I've created (later buttons will be more) to have random String text from the array, which I've initialized. I don't know what I should do. The language is c++.
My array looks like this:
ising namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
//KPoP Idols ARRAY Initializing
KPoP_Idols = gcnew array<String^> {"Rose", "Yuna", "Momo", "Irene", "ChungHa", "Winter", "IU"};
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Label^ Timer;
private: System::Windows::Forms::Timer^ ShowButtonTextTimer;
private: System::Windows::Forms::Button^ button2;
//KPoP Idols array Declaration
array<String^>^ KPoP_Idols;
There are no arguments to 'srand' that depend on a template parameter
anybody knows why ?
template<class T, int s> void Apprentissage<T, s>::apprendre_base(int k, double learning_rate) {
int min=s-s;
int max = s-1;
srand(time(NULL));
for (int i = 0; i < k; i++) {
int rd= rand()%(max-min+1) + min;
// cout<<rd<<endl;
T in(rd);
n->apprentissage(in,learning_rate) ;
}
}
Message : [Error] there are no arguments to 'srand' that depend on a template parameter, so a declaration of 'srand' must be available [-fpermissive], [Error] there are no arguments to 'rand' that depend on a template parameter, so a declaration of 'rand' must be available [-fpermissive]
How to pick a random number every time from a list
The goal: pick a random number from a list every time a chunk is generated
Python code example to make it more clear.
I have this list:
listbytes = [87, 88, 89, 90]
And this function which splits the data:
def chunks(lst, n):
"Yield successive chunks from lst, where n is a list of possible sizes"
i = 0
while i < len(lst):
k = min(random.choice(n), len(lst) - i)
yield lst[i:i + k]
i += k
And I call it this way:
for chunk in chunks(d, listbytes):
......
Every chunk has a random size between the ints in the listbytes variable, so: 1 chunk may have the size of 87, the next one may have the size of 90, and so on..
Go code:
func split(buf []byte, lim int) [][]byte {
var chunk []byte
chunks := make([][]byte, 0, len(buf)/lim+1)
for len(buf) >= lim {
chunk, buf = buf[:lim], buf[lim:]
chunks = append(chunks, chunk)
}
if len(buf) > 0 {
chunks = append(chunks, buf[:len(buf)])
}
return chunks
}
And I call it this way:
for _, chunk := range split(buf[:n], 100) {
.......
How can I achieve the same goal but in go?
Function that returns random BigInteger between min and max [duplicate]
I need c# code that generates random BigInteger number between 2^64 and 99999999999999999999 Something like that:
BigInteger maxLimit = BigInteger.Parse("99999999999999999999");
BigInteger minLimit = BigInteger.Parse("18446744073709551617");
BigInteger bigInteger = maxLimit - minLimit;
Random randNum = new Random();
randNum.Next(minLimit, maxLimit); //cannot convert from 'System.Numerics.BigInteger' to 'int'
sklearn - sample from GaussianMixture without fitting
I would like to use a GaussianMixture for generating random data. The parameters should not be learnt from data but supplied.
GaussianMixture allows supplying inital values for weights, means, precisions, but calling "sample" is still not possible.
Example:
import numpy as np
from sklearn.mixture import GaussianMixture
d = 10
k = 2
_weights = np.random.gamma(shape=1, scale=1, size=k)
data_gmm = GaussianMixture(n_components=k,
weights_init=_weights / _weights.sum(),
means_init=np.random.random((k, d)) * 10,
precisions_init=[np.diag(np.random.random(d)) for _ in range(k)])
data_gmm.sample(100)
This throws:
NotFittedError: This GaussianMixture instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
I've tried:
- Calling
_initialize_parameters()
- this requires also supplying a data matrix, and does not initialize acovariances
variable needed for sampling. - Calling
set_params()
- this does not allow supplying values for the attributes used by sampling.
Any help would be appreciated.
Rcpp sample sugar function, how to use
I am trying to permute the order of elements in a CharacterVector. In R I would simply use:
sample(charvec)
I am trying the same thing in Rcpp using the sample
sugar function, but it keeps throwing 'error: no matching function for call to 'sample(Rcpp::CharacterVector&)'. Other sugar functions I have tried, like intersect
or sort_unique
work fine with CharacterVector, but sample refuses to work. This is the minimal example I have been experimenting with:
cppFunction('CharacterVector samplefunc() {
CharacterVector v = {"Cat", "Dog", "Fox", "Fish", "Lion"} ;
CharacterVector v2 = sample(v) ;
return v2 ;
}')
What I am doing wrong when trying to use the sample sugar function?
lundi 26 juillet 2021
Generate random numbers between -1 and 1 in java
This is what I am going to do. I want to generate random numbers between -1 and 1. Then I add that generated number to a specific number. I want to continue this until that total value reaches another specific value.
int distance = 5;
int min = -1;
int max = 1;
int randomValue;
while(distance <= 10){
randomValue = (int)(Math.random()*(max-min+1)+min);
distance = randomValue + distance;
Log.d("Output", "value is"+distance);
}
This returns values up to 11. how can I resolve this
Generating a random sequence in Python
I want to generate a sequence that contains an integer (say x) 'm' times and another integer (say y) 'n' times. How do I do this in Python?
Random assignment problem with constraints
Suppose I have C
clusters and Q
elements to be randomly distributed into the C
clusters. We have to comply with the following restrictions:
- Each cluster has capacity, i.e a number representing the number of elements that can be allocated there
- Each cluster
c_k
has associated two positive numbersa_k
andb_k
, withk = 1, 2, ..., C
. And each elementq_j
has associated aw_j
positive number withj = 1, 2, ..., Q
. The elementq_j
can be allocated inc_k
if and only ifa_k <= w_j <= b_k
, for everyk, j
. - Solutions may not be found, so we have to raise an exception
For example suppose Q = 4
and C = 2
, with W = [1,2,1,2]
representing the w_j
values, andZ = [2, 2]
are the clusters capacity (each cluster can allocate 2 elements) and WT = [(0,2), (0,2)]
is the vector of restrictions on the clusters. In this case any 2-permutation of the 4 elements is a valid solution.
I am here to search for references of a similar problem.
relaxed version of feedback vertex set (FPT)(sampling algorithm)
problem: for a given undirected graph G and k ∈ N, and the objective is to decide whether there exists a subset X ⊆ V (G) of size at most k such that every connected component in G − X is either a tree or a cycle.
we need to design a 4^k * n^O(1) running time FPT algorithm
My motivation is to use a sampling algorithm, but for that, the graph should be with a minimum degree of 3. I wrote a reduction rule for all vertex with degree 0, but I struggle to write reduction rules for degrees 1 and degrees 2 without increasing parameter k.
Is there any way to make sure 100% that sum of all probability passed to np.random.choice = 100?
I'm having 50000 samples that each has a probability, so each probability is very small. I has error probability sum isn't 1 of np.random.choice, and has tried a lot of way to fix it: convert to float64, try to assign first probability = 1- the rest, try to normalize by let all probability/ np.sum([list of all probability]), but once in a while this still happen, since i change the list of probability regularly. Anyone know how to fix this?
Attribute Error while using random module
I am trying the below program, but getting Attribute error . Can someone help me if have any idea on this issue?
import random
print(random.randrange(1, 10))
Attribute error: partially initialized module 'random' has no attribute 'randrange'(most likely due to a circular import)
Newbie learning | Why dont this random.shuffle work?
import random
##Why not working :(
lista = []
random_values = "Ko","Bil","Tv"
lista.append(random_values)
random.shuffle(lista)
print(lista)
I dont understand why this wont work...The shuffle wont shuffle the list.
Rcpp: "overloaded function with no contextual type information" for R::dbeta
I have C++ code with the Rcpp package included.
Within a function I have the following loop:
for(int i=0; i<N; i++){
double yi = y[i], xi = X_chain[i];
double numerator = R::dbeta( yi, alpha_par, beta, log=false );
double denumerator = R::dbeta( xi, alpha_par, beta, log=false );
double alpha = std::min(1.0,(numerator)/(denumerator));
(...)
}
where alpha_par and beta are doubles and they are the parameters of the beta distribution.
For both lines where I use the function R::dbeta I get the error "overloaded function with no contextual type information". I am really confused since runif and rbinom at different points in the code are working completely fine.
Which pseudo random number generator algorithm does java.util.Random in Java 8 use?
I'm trying to find out exactly how java.util.Random in java 8 generates its random numbers, more specifically the algorithm behind it. All I keep seeing is how to generate random numbers in java 8 and not the driving forces behind it.
If you could point me to any documentation regarding the PRNG that java.util.Random uses that would be perfect.
Also in case its been done already, is there a way of replicating the output of java.util.Random in python? A Quick test using a seed of 5 and int range of 0 to 100 gives different results to pythons random module
dimanche 25 juillet 2021
SwiftUI - How to get random number within a certain range
I want to bring in a random number within a certain range.
It's hard to explain, so I'll replace it with code.
func getImage(indedxLocation: Int) -> String {
let getNumber = indexLocation % 20 // value is 0 ~ 19
let getRandom = getNumber.random(in: 0 ..< 4) // I want to solve this part
return String(getRandom)
}
This code is written the way I want it and I want to know the correct logic of this code.
Thank you.
c# random value from Enum doesn't work as I would like it to
So, im using this code to find random value from my enum:
public cards chooseFromDeck()
{
var random = new Random();
return (cards)random.Next(cards.GetNames(typeof(cards)).Length);
}
and this is my Enum:
public enum cards { Ace=1,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack=10,Queen=10,King=10}
and I have 2 problems with this, 1. it somehow picks up "0" as a value, which I dont understand since I have my Ace marked as "1", and the 2nd problem is that it doesn't pick Jack,Queen and King at all, if I remove the "=10" from them all it works, but then the values are 11,12,13. What way should I use to add value "10" to Jack, Queen and King?
Is there a way to make a random number generator in java that is more likely to land on one number than another?
I want to make a random number generator in java, that generates a random number from 1-20, but I want it to be more likely to generate 1 than 20, like lower numbers are more likely to generate than higher number, is there a way to do that?
How to send random class to the new method as an argument
How to send random class to the new method as an argument?
package practice;
import java.util.Random;
public class test {
public static void main(String[] args) {
Random generator= new Random(seed);
fillMatrixRandom(generator);
public static void fillMatrixRandom(int generator) {
}
}
samedi 24 juillet 2021
PHP MySQL Picking One Random Result From Each Date
I have a db structured like this:
int, date, varchar
1, 2021-07-25, aaaa
2, 2021-07-25, aaba
3, 2021-07-25, aabb
4, 2021-07-26, bbbb
5, 2021-07-26, bbba
6, 2021-07-26, bbaa
7, 2021-07-26, babb
I need to pull one result for each date at random. So one result for 07-25 and one result from 07-26 with this example.
Sample Output:
aaaa
bbbb
Thank you
How to increment a value in a loop
I'm not sure how to properly write the question. So, the idea I have is to print the original random values I get from a list. After the user inputs a 1
inside a while loop it creates one new random number from the list. Every time the user enters 1
as the input, it keeps creating a new random number and prints the previous random numbers together.
import random
numbers = [1, 2, 3, 4, 5]
random_number = [random.choice(numbers) for _ in range(2)]
print(random_number)
while True:
choice = int(input("Press [1] to continue [2] to exit: "))
if choice == 2:
break
elif choice == 1:
extra_number = [random.choice(numbers) for _ in range(1)]
for i in extra_number:
print("\nFirst Numbers:", random_number, "Extra Numbers:", i)
This loop will return a random number from the list. However, every time the user enters 1
it replaces the old one with a new one. I want to still return those old values and also print a new one every time the user enters 1
. So, I thought that maybe increment will work, but I don't know how to make it work. I also tried enumerate
and range(len())
and found it a bit confusing to understand. I would appreciate it if someone could help me or if there is an easier way of doing this.
Widen radius of SVG curves with JavaScript
The snippet below draws random connected curves over the document a certain number of times:
function createPath() {
const
dimensions = getWindowDimensions(), svg = document.querySelector( `svg` ),
path = document.createElementNS( `http://www.w3.org/2000/svg`, `path` );
dimensions[0] = dimensions[0]; dimensions[1] = dimensions[1];
svg.appendChild( path );
path.setAttribute(
`d`,
`M ` +
`${getRandomNumber(dimensions[0])} ` + `${getRandomNumber(dimensions[1])} ` +
`C ` +
`${getRandomNumber(dimensions[0])} `+`${getRandomNumber( dimensions[1])}, ` +
`${getRandomNumber(dimensions[0] )} `+`${getRandomNumber( dimensions[1])}, ` +
`${getRandomNumber(dimensions[0])} ` + `${getRandomNumber( dimensions[ 1 ])} `
)
for( let i = 0; i < 100; i++ ) {
path.setAttribute(
`d`,
path.getAttribute( `d` ) +
`S`+`${getRandomNumber(dimensions[0])} `+`${getRandomNumber(dimensions[1])}, `+
`${getRandomNumber(dimensions[0])} ` + `${getRandomNumber(dimensions[1])} `
)
}
}
setInterval( setSVGDimensions, 10 ); setInterval( positionPath, 10 );
createPath();
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
display: flex; justify-content: center; align-items: center;
}
svg {
border-radius: 1rem; background-color: rgba( 95%,95%,95%,0.5 );
filter: blur( 1rem );
animation-name: blur; animation-duration: 1s;
animation-timing-function: ease-in-out; animation-fill-mode: forwards;
stroke-linecap: round; stroke-linejoin: round;
stroke-width: 0.25rem; fill: none;
}
@keyframes blur {
100% { filter: blur( 0rem ); }
}
path {
animation-name: grow;
animation-duration: 2500s;
animation-timing-function: cubic-bezier( 0.75,0.25,0.25,1 );
stroke-dasharray: 1000000;
stroke-dashoffset: 1000000;
stroke: rgba( 0%,100%,75%,0.75 );
}
@keyframes grow {
100% { stroke-dashoffset: 0; }
}
<svg></svg>
<script>
function getRandomNumber( max ) { return Math.floor( Math.random() * max ); }
function getWindowDimensions() {
const
dimensions = [],
windowWidth = document.documentElement.clientWidth,
windowHeight = document.documentElement.clientHeight;
dimensions.push( windowWidth, windowHeight );
return dimensions;
}
function setSVGDimensions() {
const
dimensions = getWindowDimensions(), svg = document.querySelector( `svg` );
svg.style.width = dimensions[ 0 ] - 10; svg.style.height = dimensions[ 1 ] - 10;
}
function positionPath() {
const
dimensions = getWindowDimensions(), path = document.querySelector( `path` );
path.setAttribute(
`transform`,
`
scale( 0.5 ) translate( ${ dimensions[ 0 ] / 2 },${ dimensions[ 1 ] / 3 } )
`
)
}
</script>
This is the desired behavior except for the sharpness of some curves. The radius is too small, the angle is too acute. We want wider smoother curves. For example in this screenshot the problem areas are circled.
In the picture below notice the red circles have very sharp curves whereas the green circled are wider smoother curves:
Is there a way we could use JavaScript to prevent the creation of the sharp curves ( circled in red ) and have the algorithm only create wider curves ( circled in green )?
Dirichlet distribution and correlation
I have the following variables that follow a beta distribution:
Alpha1 Alpha2 Beta(Alpha1,Alpha2)
Variable 1 3.18 2.81 0.53
Variable 2 2.33 3.666 0.38
Variable 3 1.44 4.55 0.24
Variable 4 1.8 4.2 0.3
Variable 5 2.61 3.38 0.436
From the distribution I have generated random values in order to obtain the pearson correlation matrix. The problem is, in general, random numbers of univariate variables, the correlation is very low. My question is this:
From the beta functions that I show above how you could generate a multivariable Dirichlet function in python and how you could obtain its correlation matrix.
solve: 'int' object has no attribute 'self'
newPos = self.ConvertToScreen(self.X, self.Z, self.xMin. self.xMax, self.zMin, self.zMax, width, height)
The above is the line where i am getting error. I tried asking people for help but most of them were not familiar with pygame.
What is the best way to use a secrets package, if previously I used a random package to generate unique_code in python?
i have this code for generate unique_code
using Random Package
import random
FullChar = 'CDHKPMQRVXY123456789'
total = 20
count = 7
for i in range(total):
select = random.sample(FullChar, count)
random.shuffle(select)
unique_code = ''.join(select)
print(entries)
I Tried Using Secrets Package
import random
FullChar = 'CDHKPMQRVXY123456789'
total = 20
count = 7
for i in range(total):
select = random.sample(FullChar, count)
select = secrets.SystemRandom.sample(FullChar, count)
secrets.SystemRandom.shuffle(select)
unique_code = ''.join(select)
Here I use random package to generate unique_code(import random), but I think this is the old way to generate unique_code with this package, I want to use secrets package to generate unique_code(import secrets). What is the best way to use a secret package(import secrets), if previously I used a random package to generate unique_code like the code I wrote earlier?
When I used Random Package it's Clear, but when i changes it to secret package it's showing error
select = secrets.SystemRandom.sample(FullChar, count)
TypeError: sample() missing 1 required positional argument: 'k'
Thanks
vendredi 23 juillet 2021
Positive random number generation with given mean and standard deviation
I am working on a simulation project. Need help on random number generation. I need two sets of random numbers.
Properties:
- Primary set (var_a) > Normally distributed, greater than 0, with given mean and std.
- Secondary set (var_b) -> Same as a primary set, with an addition, that second set cannot be greater than primary set. The reason being the output of a deterministic function will be in percentage between 0-1 only. For example:
How to add the sum of a dictionary if condition is true
I'm working on something similar to blackjack. There are only a few of them just for testing. I randomize two different key's from the dictionary. The problem I'm having is that I don't know how to add the total sum of the values based on the condition. I do understand that sum() doesn't work in this case, but I want something similar to get the returns from the for loop item
, which returns two elements and add them together. Thank you in advance!
import random
numbers = {'9': 9, '10': 10, 'J': 10}
numbers_list = list(numbers.keys())
pick_one = random.choice(numbers_list)
pick_two = random.choice(numbers_list)
print(pick_one, pick_two)
for items in numbers:
if pick_one in numbers_list and pick_two in numbers_list:
if pick_one == items and pick_two == items:
total = sum(numbers[items])
print(total)
Can I set manually the seed of Randomization in Visual Basic Application
I need to get the same sequence of the randomization by setting the seed. Can I do this in Visual Basic?
Code, I used:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Dim rand As New Random
MsgBox(rand.Next(1, 10))
End Sub
Thanks and have a nice day!
Dynamic Eigen Matrix Random Initialization
I have a vector<MatrixXf*> called weights. In the loop, a new MatrixXf is allocated, pointer pushed to the vector, and meant to be initialized to random values. However, I want to avoid setRandom() in favor of my He distribution.
The uncommented code below works as-is, but it feels very clunky to create a 'local' matrix that may be in the stack (or heap, but the class doc is vague) and copy it into my destination matrix. The commented lines are things I've tried before that had no effect (matrix values remained 0).
What would be the better solution?
/* context */
typedef Eigen::MatrixXf Matrix;
vector<Matrix*> weights;
random_device rd;
mt19937 rgen(rd());
vector<uint> topology;
...
// Initialize weights (using He)
if (i > 0) {
normal_distribution<float> dist(0.0, sqrt(2.0/topology[i-1]));
auto he = [&](){return dist(rgen);};
if (i != topology.size() - 1) {
Matrix m = Eigen::MatrixXf::NullaryExpr(topology[i-1] + 1, topology[i] + 1, he);
weights.push_back(new Matrix(topology[i-1] + 1, topology[i] + 1));
(*weights.back()) = m;
//weights.back()->NullaryExpr(weights.back()->rows(), weights.back()->cols(), he);
//weights.back()->NullaryExpr([&](){return dist(rgen);});
weights.back()->col(topology[i]).setZero();
weights.back()->coeffRef(topology[i-1], topology[i]) = 1.0;
} else {
Matrix m = Eigen::MatrixXf::NullaryExpr(topology[i-1] + 1, topology[i], he);
weights.push_back(new Matrix(topology[i-1] + 1, topology[i]));
(*weights.back()) = m;
//weights.back()->NullaryExpr(weights.back()->rows(), weights.back()->cols(), he);
//weights.back()->NullaryExpr([&](){return dist(rgen);});
}
cout << "Topology Loop: i=" << i << " and nodes=" << topology[i] << endl;
cout << *weights.back() << endl;
}
Fitting or representation of a stochastic field
How can I make the get_random_string Django module to return only numerical values?
What should I do to my simple code below, so that it only returns numerical values?
>>> from django.utils.crypto import get_random_string
>>> get_random_string(10)
>>> 'PhaWT9X02U'
Something like: 1067603657
And if it is possible, can you recommend an id field generated in this manner?
Maze Generation results [closed]
I'm trying to write an algorithm to create mazes. The algorithm looks like this:
- Start at a random cell.
- Mark the current cell as visited, get a list of the neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.
But the algorithm produces mazes like this:
I don't know why the algorithm creates full lanes instead of creating dead ends as well to make it look more like a maze instead of a one way road.
I can't narrow down the problem with the algorithm. I though of bad random selection or that the algorithm marks each cell as visited in the recursive step resulting in no dead ends as it can't go back to a cell. I could provide code as well but I think my idea for the algorithm is somehow messed up. I would be grateful for any ideas.
Randomly sleeting rows based on all groups in two columns
I have a large dataset with about 167k rows. I would like to take a sample of 2000 rows of it while making sure I am taking rows from all groups in two columns (id & quality)
in the data. This is a snapshot of the data
df <- data.frame(id=c(1,2,3,4,5,1,2),
quality=c("a","b","c","d","z","g","t"))
df %>% glimpse()
Rows: 7
Columns: 2
$ id <dbl> 1, 2, 3, 4, 5, 1, 2
$ quality <chr> "a", "b", "c", "d", "z", "g", "t"
So, I need to ensure that the sampled data has rows from all combinations of these two group columns. I hope someone can help out.
Thanks!
jeudi 22 juillet 2021
Random subsampling of a data.frame and summarize mean and standard deviation
In R, I have some ecological data in this form:
sample = seq(1, 20, by=1)
group = c("A","A","A","B","B","C","D","E","E","E","E","E","E",
"E","E","E","E","F","F","F")
df = data.frame(sample, group)
Where sample
is the sample number and group
is a different taxonomic group associated with each sample
In total, I have 20 samples (in reality more) and I can get the relative frequency of a certain group with:
data.frame(table(group)/length(group))
group Freq
1 A 0.15
2 B 0.10
3 C 0.05
4 D 0.05
5 E 0.50
6 F 0.15
Now I would like to subsample (10 samples) my data frame for 100 times and get the mean relative frequency of each group together with the standard deviation.
How can I do that?
Subset a table such that the samples are normally distributed around a value in a column
I have the following table called original_table
:
name height age
personA 180 21
personB 190 37
personC 168 27
personD 182 56
...
My goal is to create two random samples of size 100 from the original_table
such that the mean of age is normally distributed around 25, and height average is close to 175. Basically, a person with age 25 and height 175 has the highest chance of being in the tables, but not guaranteed.
Why Do I get this error when trying to do simple math? [duplicate]
Here this the code.
a = input (": ")
b = input(": ")
ab = (a-b)
print (ab)
I get this error.
typerror: unsupported operand type(s) for -: 'str' and 'str'
Get random vectors between the 3 vector plane
I would like to know how to get random vectors inside a triangle, but it seemed more difficult than I expected.
The plane would have coordinates like [a, b], [x, y], [u, v] (three points):
But I also wanted the chosen points not to be too close to each other:
Thanks for any help.
picking a truly random number from a vector in cpp [duplicate]
I have this current code
std::string randomMove = possibleMoves[rand() % possibleMoves.size()];
int randomMoveInt = std::stoi(randomMove);
board[randomMoveInt-1] = "StackOverflow";
But everytime I restart the program the pattern is the same and does not change no matter how many times I run it. Is there a way to avoid this/any ideas? Thanks
Generating all possible combinations & randomizing their distribution in a matrix
I want to generate all possible combinations & randomize their distribution in a matrix.
Example:
Data Set: {A,B, C, D} String Length=4 (4^4=256 combinations)
So a 16 x 16 matrix would be generated & scrambled.
So AAAA AAAB AAAC... etc. would be randomly distributed within the matrix without AAAA or any other combination being repeated.
Ideas and links are greatly appreciated! Thanks!
How to generate all possible combinations and randomize [closed]
I want to generate a matrix with all possible non-repeating combinations & then randomize their distribution.
Example: Data Set: {A,B, C, D} String Length=4 (4^4=256 combinations)
So a 16 x 16 matrix would be generated & scrambled.
AAAA AAAB AAAC... etc. would be randomly distributed within the matrix without AAAA or any other combination being repeated.
Any ideas are greatly appreciated! Thanks!
My Guessing game isn't able to print out the dialogue
beginner here! My question is, why doesn't the terminal say the prints?
import random
print(" Guess number between 1-5")
def Guessinggame(Number = int(random.randint(1, 5))):
if input == Number:
return "YOU'RE AWESOME!"
else:
return "Not correct"
while():
Guessinggame()
It's a guessing game where you have to guess between the number 1 and 5.
How to override Python's random with own generator?
In the docs for Python's random
, it states that one can "use a basic generator of your own" by overriding the random()
method. Suppose I have a custom generator that outputs a random float uniformly in the semi-open range [0.0, 1.0), i.e. just like random()
.
- How would I go about replacing Python's with my own?
Further, suppose the replacement is a true random generator built off of a natural source of entropy.
- Does this mean I can use the other parts of the class like
random.choice()
on a given array and make claims that the chosen element is truly random?
How can I select a random subsequence of length 'l' in Haskell?
I have a list of vertices [1..n] and I need to select a random subsequence of the vertices of length 'l'.
Eg : generateS 3 [5,6,7,8,9,10,11,12,13]
Answer = [5,11,13]
Is there any better way than:
sort (take 5 $ randomRs (70,100) (mkStdGen 3) :: [Int] )
Bin Packing problem with constrains in R for genomic data
I'm trying to solve a different version of the bin packing problem in R. Any insights or resources will be appreciated. I'm trying to randomize finite amount of bins (windows) in all the knapsacks (chromosomes), but there regions in each chromosome that can not be used.
Example for the data I have:
Chromosomes length:
Chr1:1 - 200000
chr2:1 - 100000
.
.
.
Constrains:
chr1: 100-200
chr1: 5000-5087
chr2: 1098-2067
.
.
.
The bins size I need to pack / random all over the chromosomes:
3876
2000
10000
.
.
.
I need to use as many bins as possible, in random locations.
Thank you!
Shuffling a list using random-fu shuffle, doing an operation on a list and displaying result in Haskell
My goal is to get a list of N random items taken from an input list and see the result in GHCI. I decided to shuffle the input list, then take the first N elements from it (i.e. slice first elements). I am using shuffle
function from random-fu module Data.Random.List.
Here's the code I currently have and at least it can be compiled
import Data.Random
import Data.Random.List
rndSelect :: [a] -> Int -> RVar [a]
rndSelect l n
= do
l' <- shuffle l;
return $ take n l'
But when I run rndSelect "abcdefg"
in GHCI prompt, I get the following error:
<interactive>:1:1: error:
• No instance for (Show (Int -> RVar [Char]))
arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In a stmt of an interactive GHCi command: print it
I think I know what it means. RVar
doesn't derive Show
. I guess I should modify my function so that it gets shuffled RVar[a]
and then somehow take a list of the first N elements and convert it to IO action.
Here's one of my failed attempts:
rndSelect :: [a] -> Int -> IO ()
rndSelect l n
= do
l' <- shuffle l;
l'' <- take n l'
s <- runRVar l'' StdRandom
putStrLn s
I know, that it is messed up and raises errors on top of errors. I am beginner in Monads, "do" blocks and things like that in Haskell
I would be glad if someone help me to fix my approach, but if you know alternative way to achieve my goal, I will be happy to see it as well. Thank you very much!
mercredi 21 juillet 2021
How to detect whether a number sequence is generated by human random action or pseudo-random generator?
I have a user button touch sequence, which record ticks between user press this button and lift up. Such as 0.111,0.23,0.45,0.12
records user touch button 4 times, and first touch lasts for 0.111 s.
Some user is real human-being, and other is bots. Bots touch button by pseudo-random generator, maybe implemented like web.button.touch(random.uniform(0, 1))
So, How to detect whether a number sequence is generated by human random action or pseudo-random generator?
How to reset a randomly generated number again after a click using JavaScript?
So, basically, I am trying to generate a password when I click a button. The program generating the password once but when I click it again due to the fact that a new Randomized number isn't generated the program doesn't give a new password. Here is the CODE:
let password = ["NyiNE7!38vs","SyiMA4*78dt","SuoSO6]40db","LeaDU9'11ln","QooGU9!09nk","SeuXI1_63sp","SieKY6)07zk","GaaDI9'30gn","BoyLY4|74ct","BuaZI0+69vl"]
function Random() {
let i = Math.floor(Math.random() * 9)
}
i = Math.floor(Math.random() * 9)
const div = document.getElementById('password')
const button = document.getElementById('generate')
button.addEventListener('click' , generatePassword , Random)
function generatePassword(){
div.innerHTML = password[i]
}
How to randomly select colors in plotly python graph
I have the following data lists:
date = ['2019-01-01', '2019-01-18', '2019-02-03']
value1 = [6798.0, 436.0, 348.0]
value2 = [500.0, 455.0, 348.0]
From these lists I generate a line graph using the plotly library, this way:
trace_1 = go.Scatter(x = date,
y = value1,
mode = 'markers+lines',
marker_color='rgb(152, 0, .8)',
name = '1')
trace_2 = go.Scatter(x = date,
y = value2,
mode = 'markers+lines',
marker_color='rgb(0, 0, .8)',
name = '2')
data_total = [trace_1, trace_2]
fig = go.Figure(data=data_total, layout=layout)
py.iplot(fig)
The graphic is working perfectly and the lines are in different colors. However, I would like the line colors, instead of manual as I did, to be automatically generated randomly.
Following this tutorial: https://www.kite.com/python/answers/how-to-generate-random-colors-in-matplotlib-in-python
I tried to do:
colors = np.random.rand(1,3)
trace_1 = go.Scatter(x = date,
y = value1,
mode = 'markers+lines',
marker_color = colors,
name = '1')
trace_2 = go.Scatter(x = date,
y = value2,
mode = 'markers+lines',
marker_color = colors,
name = '2')
data_total = [trace_1, trace_2]
fig = go.Figure(data=data_total, layout=layout)
py.iplot(fig)
But this code doesn't work.
How do I stop my random enemy spawner from spawning an enemy where there is one enemy already?
I made a script that spawns random enemies, randomly across a set of different predestined positions in the game. These positions are empty game objects. Also the spawner has a limit, so if doesn´t spawn more of that I want, and if the number of current enemies goes back to being less than the maximum, it starts to spawn more enemies until the limit is reached
All of this works nice and i have no problem, but the thing that is missing and I want to add to this spawner, is that enemies don´t spawn randomly in the same position, making an overlap, if in one of the possible spawn positions there is already an enemy. I want the spawner to take another position that is free of enemies, for the next one.
Random values from a PERT distribution in pythoon
I'd like to generate in python 10,000 random values from a PERT distribution that has the following parameters low=6898.5, peak= 7338.93, high=7705.87
How would you make a function that adds random numbers from a list to reach a certain value?
the question title might be a little bit confusing so let me see if I can explain it a little better here. I want to create a function that will generate a sequence of numbers (in any order or combination) that are in a pre-defined list to add to a certain value.
IE.
var x = [6, 4, 3]; //pre-defined values
var n = 24; //the number I want to add too
function myFunc(values, goal) {
//code for algorithm
//return a sequence of numbers from the list that add to 24
}
myFunc(x, n)
Example Outputs from myFunc:
- 4, 4, 4, 6, 3, 3 --> 24
- 6, 4, 3, 3, 4, 4 --> 24
- 3, 4, 4, 6, 3, 4 --> 24
- etc.
The algorithm would be able to return one of the many permutations that exist but I just came up with a couple for the sake of the question.
Responses don't have to be language-specific I just need a general idea/insight on how to create and structure this algorithm.
Thanks!
Why does "random.choices" return always the same element when passing a list "cum_weights" of decreasing values?
I don't understand the cum_weights
parameter of random.choices
.
I read that it is:
Weight of previous element + own weight [10, 5, 1] → [10, 15, 16]
So as I understand it, the probability of "cherry"
is 16 and it is the highest. So why is "apple"
more repetitive as a result?
import random
mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, cum_weights=[10, 5, 1], k=9))
outputs:
['apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple']
Generate random numbers in PERT distribution
I'd like to generate in python 10,000 radom values from a PERT distribution that has the following parameters low=6898.5, peak= 7338.93, high=7705.87
Trying to check if a name is in a list then continue
This is a sample of code that I am using to distribute holiday shifts randomly between employees.
I would like to be able to enter the previous years holiday for each employee. Then if the holiday chosen randomly matches a previous holiday it skips that employee and moves to the next.
import random
import sys
from itertools import cycle, product
print ('start','\n')
nyd = ['zia', 'bettina']
holiday_list = ['NYD','MLK','PRD','MEM','IND','LAB','THD','XMS']
shift_list = ['Night', 'Noon']
emp_list = ['Donna', 'Gessica', 'Bettina', 'Irina', 'Zia', 'Marsha',]
assigments = []
holiday_shifts = product(holiday_list, shift_list) # combine all the holidays and shifts via product()
random.shuffle(emp_list) # randomize our employees
for emp in cycle(emp_list):
try:
assigment = list(next(holiday_shifts)) + [emp]
assigments.append(assigment)
except StopIteration:
# we've assigned all the holiday_shifts
break
def schedule():
for a in assigments:
print(", ".join(a))
schedule()
# y = input("enter no whose table you want: ")
# for x in range(sys.maxsize**10):
# schedule()
print ('\n','next','\n')
print (" end ")
Getting the same random numbers, possible wrong use of srand() or a coding error?
I bumped into this problem today while i was running my code. My code is supposed to run 10k times and at the end collecting some datas and averages.
Everytime a new run starts, srand generate a radom seed doing
srand(time(NULL))
The code itself is very short and it runs several times during 1 second. I've read that time(NULL) returns the number of seconds since a precise date, so is it possible that for the runs in the same "second" i'm getting the same "random" number? Because i'm getting something like 1000 same numbers and then it changes in another number, repeating itself for other 1000 times approx.
It could be also a coding error but the code looks fine to me.
Is there a way to generate number in a different way if this is the problem? Otherwise i will give a deeper check to my code.
Thank you guys!
How Exactly Works the Random Class in C#? [duplicate]
I want to understand why when I create a Random Number Generator in this example, instead of generating random number that eventually are the same (i.e. generate the number '3' two times), it always generate different ones without me coding anything. What I mean by that, is that when I Generate the password, it is always with the same size: 10 digits. What it means that when generating the "random" position of the password in wich we will insert the random digit, it magically never is the same, it never overwrites an already generate digit. Could you folks elucidate that for me? Thank in advance.
private const string CapitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string SmallLetters = "abcdefghijklmnopqrstuvwxyz";
private const string Digits = "0123456789";
private static Random rng = new Random();
private static StringBuilder password = new StringBuilder();
static void Main(string[] args)
{
for (int i = 0; i < 2; i++)
{
char capitalLetter = GenerateChar(CapitalLetters);
InsertAtRandomPosition(password, capitalLetter);
}
for (int i = 0; i < 6; i++)
{
char smallLetter = GenerateChar(SmallLetters);
InsertAtRandomPosition(password, smallLetter);
}
for (int i = 0; i < 2; i++)
{
char number = GenerateChar(Digits);
InsertAtRandomPosition(password, number);
}
Console.WriteLine(password);
}
private static char GenerateChar(string availableChars)
{
int randomIndex = rng.Next(availableChars.Length);
return availableChars[randomIndex];
}
private static void InsertAtRandomPosition(StringBuilder password, char character)
{
int index = rng.Next(password.Length+1);
password.Insert(index, character);
}``
While loop crashes inconsistently when generating random numbers with constraint
-
Start with a vector, vector0
-
Initialize a while loop that generates another random vector, vector1
-
Use the dot product to calculate the angle between them
-
If the angle theta between vector0 and vector1 is too large, keep re-making vector1 until it's small enough
It looks something like this:
# initialize the angle
theta = 0
# the first vector:
vector0 = [x0, y0, z0]
# initialize while loop:
while theta <= 0 or theta > np.pi/8:
# create the second vector using random numbers
x1 = random.uniform(-maxlen, maxlen)
y1 = random.uniform(-maxlen, maxlen)
z1 = random.uniform(-maxlen, maxlen)
vector1 = [x1, y1, z1]
# find the angle between the two vectors. The loop will start again if it is too large.
theta = np.arccos(np.dot(vector0, vector1) / np.linalg.norm(vector0)*np.linalg.norm(vector1)
This process is nested within two other loops - not especially large ones, only 5 step & 100 step. A simple enough process, I thought.
Here is my problem: this while loop crashes about 70% of the time. Just gives up. But some of the time, it works perfectly!
It's easy to kill it and re-initialize but sometimes I'm doing this ten times over to get the code to run through successfully, which is becoming unbearable.
Am I doing something daft that is causing this? Perhaps there's a bug that sometimes triggers in my code, or I've made a mathematical error? Maybe there is a more memory/CPU-efficient way to achieve this outcome? Or do I just need to use a more powerful machine?
how to make int random number
hey there im trying to make a random tree spawner script and was wondering how i could make the "number" int random i tried to o it like i did with the x and z int any help would be much appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class randomspawn : MonoBehaviour
{
public GameObject tree;
public int number;
public int yaxis;
void Start()
{
PlaceTree();
}
void PlaceTree()
{
for (int i = 0; i < number; i++)
{
Instantiate(tree, GeneratedPosition(), Quaternion.identity);
}
}
Vector3 GeneratedPosition()
{
int x, y, z;
x = Random.Range(-1000, 1000);
y = UnityEngine.Random.Range(-yaxis, yaxis);
z = Random.Range(-1000, 1000);
return new Vector3(x, y, z);
}
}
How to introduce pre-specified random variation into a continuous variable in R?
I've been asked to "simulate" random variations into a set of continuous biomarkers, to see which of them are more robust to possible analytical variations.
Let's say we have the initial values of biomk
:
df = structure(list(biomk = c(4.97673374242057, 4.9600435079802, 4.73707525686803,
4.6737629774537, 5.12038615805537, 5.16421438202456, 5.94437293957413,
5.33464929579543, 5.12871458216186, 4.50424426739813)), row.names = c(NA,
-10L), class = "data.frame")
> df
biomk
1 4.976734
2 4.960044
3 4.737075
4 4.673763
5 5.120386
6 5.164214
7 5.944373
8 5.334649
9 5.128715
10 4.504244
Let's say we want 15% of variation in biomk_15
. The person doing this before me had coded:
set.seed(20)
seq_15 <- seq(from=-15, to=15, by=.01)
df$factor15<-sample(seq_15, size=10, replace=TRUE)
df$biomk15 <- df$biomk+((df$factor15*df$biomk)/100)
> df
biomk factor15 biomk15
1 4.976734 -13.35 4.312340
2 4.960044 -2.86 4.818186
3 4.737075 3.98 4.925611
4 4.673763 4.11 4.865855
5 5.120386 1.65 5.204873
6 5.164214 13.08 5.839694
7 5.944373 3.89 6.175609
8 5.334649 -9.60 4.822523
9 5.128715 -5.11 4.866637
10 4.504244 3.36 4.655587
This is a simple approach to simulate some random variations.
But this comes from an idea to simulate some sort of "inter-assay" coefficient of variance (CV), calculated as mean/sd. But the issue with this approach is how it is limited to a (-15,+15) range and ignores the initial "intra-assay" CV:
# Original biomk CV
> (mean(df$biomk)/sd(df$biomk))
[1] 12.56766
# New biomk CV
> (mean(df$biomk15)/sd(df$biomk15))
[1] 9.047034
Of course, ideally this CV simulations should not be done in silico but with inter-lab data etc etc, but I have to do this.
QUESTION: Do you see a way that this could be done better? Or to introduce this random variation leaving the "intra-assay" CV unchanged? So that new values would still have cv = 12.56766?
I'm not sure if it makes sense, but thanks anyway.
What is the time complexity of random.nextInt() in Java?
I'm wondering what the time complexity of random.nextInt()
is in Java.
I will attach a snippet of code down below:
Random rand = new Random();
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
int[] randomNums = new int[list.size()];
int i = 0;
while(i < randomNums.length) {
int index = rand.nextInt(list.size());
randomNums[i++] = list.get(index);
list.remove(index);
}
return randomNums;
mardi 20 juillet 2021
Javascript Password Generator Invalid return statement
We are using Camunda to produce a password using some code we found here on StackOverflow.
This code was working but all of the sudden we started getting and error;
Invalid return statement return
Can someone help me out?
Thanks
function generatePassword(length, rules) {
if (!length || length == undefined) {
length = 10;
}
if (!rules || rules == undefined) {
rules = [
{chars: "abcdefghijklmnopqrstuvwxyz", min: 3}, // As least 3 lowercase letters
{chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 3}, // At least 2 uppercase letters
{chars: "0123456789", min: 2}, // At least 2 digits
{chars: "!@#$&*?|%+-_./:;=()[]{}", min: 2} // At least 1 special char
];
}
var allChars = "", allMin = 0;
rules.forEach(function(rule) {
allChars += rule.chars;
allMin += rule.min;
});
if (length < allMin) {
length = allMin;
}
rules.push({chars: allChars, min: length - allMin});
var pswd = "";
rules.forEach(function(rule) {
if (rule.min > 0) {
pswd += shuffleString(rule.chars, rule.min);
}
});
return shuffleString(pswd);
}
function shuffleString(str, maxlength) {
var shuffledString = str.split('').sort(function(){return 0.5-Math.random()}).join('');
if (maxlength > 0) {
shuffledString = shuffledString.substr(0, maxlength);
}
return shuffledString;
}
var pswd = generatePassword(15, [
{chars: "abcdefghijklmnopqrstuvwxyz", min: 4}, // As least 4 lowercase letters
{chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 1}, // At least 1 uppercase letters
{chars: "0123456789", min: 3}, // At least 3 digits
{chars: "!@#$&*?|%+-_./:;=()[]{}", min: 2} // At least 2 special chars
]);
return generatePassword();
Random pick cycle from an array in VBA
I'm new in VBA. I want to make a random pick cycle like that:
Let's say I have seven elements in an array(1,2,3,4,5,6,7), each time when I pick one element from the array, the total number of elements will decrease by 1. After picking every element, the array will be reset to what I initially defined (1,2,3,4,5,6,7) and do the random pick cycle again. The result of every cycle should be different.
Is it possible to do that in VBA?
Gaussian Random Number Generator using ran2.c and boxmuller algorithm
I am trying to generate normally distributed random numbers using the 'ran2.c' and Box-Muller Method. I have written the code and saved as 'gau_rit.c' . It is showing this warning message,
In file included from gau_rit.c:5:
ran2.c:16:19: note: expected ‘long int *’ but argument is of type ‘long int’
Also for the output,
Segmentation fault (core dumped)
I am new in C language, so I need help in this regard. I understand that something is happening with the variable declaration. But failed to figure out.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define PI 3.14159265 // The value of pi
#include "ran2.c"
double norm(double mean, double sd); // Returns a normal random variable
//double ran2(int seed);
int main()
{
int i=45;//counter
float x,s;
double mean = 0.0, sd = 1.0;
static long seed1=123456789;
static long seed2=987654321;
double norm(double mean, double sd){
double u, r, theta;
u = 0.0;
while(u==0.0)
u=ran2(seed1);
r = sqrt(-2.0 * log(u));
theta = 0.0;
while(theta==0.0)
theta = 2.0 * PI * ran2(seed2);
x = r * cos(theta); //for arbitrary mean and sd, we need to change this x
return(x);
}
for(i=1;i<=45;i++)
{
s=norm(mean,sd);
printf("%f\n",s);
}
}
And the ran2.c is here
#define IM1 2147483563
#define IM2 2147483399
#define AM (1.0/IM1)
#define IMM1 (IM1-1)
#define IA1 40014
#define IA2 40692
#define IQ1 53668
#define IQ2 52774
#define IR1 12211
#define IR2 3791
#define NTAB 32
#define NDIV (1+IMM1/NTAB)
#define EPS 1.2e-7
#define RNMX (1.0-EPS)
double ran2(long *idum)
{
int j;
long k;
static long idum2=123456789;
static long iy=0;
static long iv[NTAB];
double temp;
if (*idum <= 0) {
if (-(*idum) < 1) *idum=1;
else *idum = -(*idum);
idum2=(*idum);
for (j=NTAB+7;j>=0;j--) {
k=(*idum)/IQ1;
*idum=IA1*(*idum-k*IQ1)-k*IR1;
if (*idum < 0) *idum += IM1;
if (j < NTAB) iv[j] = *idum;
}
iy=iv[0];
}
k=(*idum)/IQ1;
*idum=IA1*(*idum-k*IQ1)-k*IR1;
if (*idum < 0) *idum += IM1;
k=idum2/IQ2;
idum2=IA2*(idum2-k*IQ2)-k*IR2;
if (idum2 < 0) idum2 += IM2;
j=iy/NDIV;
iy=iv[j]-idum2;
iv[j] = *idum;
if (iy < 1) iy += IMM1;
if ((temp=AM*iy) > RNMX) return RNMX;
else return temp;
}
#undef IM1
#undef IM2
#undef AM
#undef IMM1
#undef IA1
#undef IA2
#undef IQ1
#undef IQ2
#undef IR1
#undef IR2
#undef NTAB
#undef NDIV
#undef EPS
#undef RNMX
/* (C) Copr. 1986-92 Numerical Recipes Software #.3.