lundi 30 novembre 2020

How to use srand() in a class function and yield different results [duplicate]

I am trying to create a class in c++ where the class functions calculate a chance of something happening. But when I try to implement the functions using srand(time(0)) it just produces the same outcome every time. mooseChance is a private variable of the class Hunting. How do implement srand(time(0)) to get random odds in the function call?

    void Hunting::calcMooseChance()
    {
        srand(time(0));
        bool mooseAppear = false;
        mooseAppear = (rand() % 100) < 50;
        mooseChance = mooseAppear;
    }



Fantasy Name Generator using Machine Learning

I am in the process of writing a fantasy novel but I've never been the best at making "natural" sounding names, so the other day I looked up how to program a random name generator using coding. I happened upon one on YouTube where the guy was using machine learning through examples of names in a CSV file (he was using Excel; I'm poor right now and using LibreOffice Calc).

I copied his code and listened to him explain it to better learn, as I'm new to programming, and I keep getting an "IndexError: list index out of range", even though I copied his code exactly the way he had it. I even downloaded the file he had placed on the YouTube videos and I couldn't even get his to work. Basically I want to use a list of names for the machine to figure out the probability of certain letter combinations in order to make a more "natural" sounding name.

I am using Sublime Text 3 as the editor and using the Build feature on that for Python 3. The error comes at the line "prob[num1][num2] += 1" (which is line 95 on Sublime Text 3). This is a link to the machine learning part of the series: https://www.youtube.com/watch?v=Zy6-ixrY3gs&list=LL&index=6 . The code as I copied it is as follows:

import csv
global letter_count
letter_count = 0

race_name = "human male"

class letter():
    # Each letter has a lowercase character, and uppercase character, and
    # identifiers as vowel or consonant.
    def __init__(self, lowerchar, upperchar, is_vowel, is_consonant):
        global letter_count
        self.upperchar = upperchar
        self.lowerchar = lowerchar
        self.is_vowel = is_vowel
        self.is_consonant = is_consonant
        self.num = letter_count
        letter_count += 1

def normalize(prob):
    # Normalize the probability matrix so that the sum of each row is 1.
    global alphabet
    new_prob = prob
    for i in range(0,len(alphabet)):
        total = 0
        for j in range(0,len(alphabet)):
            total += prob[i][j]
        if (total > 0):
            for j in range(0,len(alphabet)):
                new_prob[i][j] = prob[i][j]/total
        else:
            for j in range(0,len(alphabet)):
                new_prob[i][j] = len(alphabet)**(-1)
    return new_prob

# Define the alphabet
global alphabet
alphabet = [letter('a','A',True,False),
            letter('b','B',False,True),
            letter('c','C',False,True),
            letter('d','D',False,True),
            letter('e','E',True,False),
            letter('f','F',False,True),
            letter('g','G',False,True),
            letter('h','H',False,True),
            letter('i','I',True,False),
            letter('j','J',False,True),
            letter('k','K',False,True),
            letter('l','L',False,True),
            letter('m','M',False,True),
            letter('n','N',False,True),
            letter('o','O',True,False),
            letter('p','P',False,True),
            letter('q','Q',False,True),
            letter('r','R',False,True),
            letter('s','S',False,True),
            letter('t','T',False,True),
            letter('u','U',True,False),
            letter('v','V',False,True),
            letter('w','W',False,True),
            letter('x','X',False,True),
            letter('y','Y',True,True),
            letter('z','Z',False,True)
            ]

# Initialize probability matrix.
# prob[i][j] = probability that letter j comes after letter i
global prob
file_name = 'default prob.csv' # Should initialize to all 0s.
prob = []
with open(file_name, newline='') as csvfile:
    prob_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in prob_reader:
        prob.append([])
        for num in row:
            prob[len(prob)-1].append(float(num))

# Read list of pre-generated names. Names should be stored one per line in file.
file_name = race_name + ' names.csv' # Change to name of file with names you wish to use as seeds.
with open(file_name, newline='') as csvfile:
    name_reader = csv.reader(csvfile, delimiter=',', quotechar='|') # Record file contents.
    for names in name_reader: # Loop over names in list.
        name = names[0]
        # Loop over letters in the current name.
        for i in range(0,len(name)-1):
            letter1 = name[i]
            letter2 = name[i+1]
            num1 = 0
            num2 = 0
            for i in range(0,len(alphabet)):
                if (letter1 == alphabet[i].lowerchar or letter1 == alphabet[i].upperchar):
                    num1 = alphabet[i].num
                if (letter2 == alphabet[i].lowerchar or letter2 == alphabet[i].upperchar):
                    num2 = alphabet[i].num
            # Add one to the number of times letter i is followed by letter number i
            prob[num1][num2] += 1

# Normalize the probability matrix.
prob = normalize(prob)

# Write probability matrix to file. This file will be read by the name generator.
file_name = race_name + '.csv'
with open(file_name, 'w', newline='') as csvfile:
    prob_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for i in range(0,len(alphabet)):
        prob_writer.writerow(prob[i])



Why is this not returning a string, and instead returning NaN [closed]

I am trying to learn js by writing a program, and I came across this problem with my code. I am trying to use js to generate a random hex code, but my program is not returning a string, and instead, saying that it is undefined.

var hex = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
var colorone = "#" + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length];
var colortwo = "#" + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length];
var colorthree = "#" + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length];
var colorfour = "#" + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length];
var colorfive = "#" + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length] + hex[Math.floor(Math.random) * hex.length];

Here is my code. I set it to console.log colorone - colorfive, but the result is #undefinedundefinedundefinedundefinedundefinedundefined. Does anybody know why this happens and ohw I can fix this?




How can I get a random sample from a list of objects with a desired systematic bias of some object attribute?

The case I have is that I have a population of objects and I would like to renew the population by discarding a certain percentage and add some new ones. The discarded objects should on average belong to a lower percentile of the population, i.e. they would in general have slightly lower "value" than the average of the whole population.

I am working with a list of objects that has some attributes. Among these an ID and, say, "value". I would like to get a random sample of unique objects from this list so that the mean of the "value" of the objects in the sample has a certain bias compared to the mean of the "value" for the whole population.

Below is a minimal example

from random import seed
from random import random
from scipy import stats
seed(243)

class Object:
    def __init__(self,ID,Value):
        self.ID = ID
        self.Value = Value

population = []
for i in range(0,50):
        value = random()
        population.append(Object(i,value))

population_list = [x.Value for x in population]
mu = np.mean(population_list)
print(mu)

The approach I am trying is to assign a weight to each Object ID and then use np.random.choice to sample the IDs. This seems to make sense, since if I use a uniform distribution for the weights I get the same mean for the sample:

Ids = [x.ID for x in population]
Weights = np.ones(len(Ids))/len(Ids)

test_means = []
while i<1000:
    Sample = np.random.choice(Ids,p=Weights,size=25,replace=False)
    Sample_list = [x.Value for x in population if x.ID in Sample]
    
    test_means.append(np.mean(Sample_list))
    i+=1
print(np.mean(test_means))

However, I can't seem to figure out how to construct the weights so that my sample will be systematically biased? Ideally, I would like to be able to control the bias, so that the mean of the sample would statistically approach, say, 0.80 x the population mean.

Would appreciate some good ideas or an alternative approach.




Python random.seed produces similar random.randint numbers in python given different range sizes

When using random in python, there are certain seeds that produce similar random numbers.

For example in python 3.8.5:

>>> import random
>>> random.seed(100)
>>> print(random.randint(1,100))
19
>>> random.seed(335)
>>> print(random.randint(1,100))
19
>>> random.seed(100)
>>> print(random.randint(1,500))
75
>>> random.seed(335)
>>> print(random.randint(1,500))
75
>>> random.seed(100)
>>> print(random.randint(1,1000))
150
>>> random.seed(335)
>>> print(random.randint(1,1000))
149

It would appear that this pattern holds for many combinations of seeds where making random.randint produce similar results for different seeds.

For another example:

>>> import random
>>> random.seed(101)
>>> print(random.randint(1,100))
75
>>> random.seed(155)
>>> print(random.randint(1,100))
75
>>> random.seed(101)
>>> print(random.randint(1,500))
298
>>> random.seed(155)
>>> print(random.randint(1,500))
298
>>> random.seed(101)
>>> print(random.randint(1,1000))
596
>>> random.seed(155)
>>> print(random.randint(1,1000))
595

Is there any reasonably simple way to solve this such that these numbers produce substantially different results given different range sizes?




How to call a random function of a class in c++?

I am trying to create a command-line game in C++. I am new to it and just started learning. My game consists of a player class and a dragon class. The classes are declared in separate header files. What I would like to know is, if there is a way to call a random function of a class after declaration.
Like

// ignore the includes
class foo{
    public:
        string name = "foo";
        foo(string name){
            this->name = name;
        }

        void func1(){
            //some code
        }

        void func2(){
            //some code
        }

        void func3(){
            //some code
        }
}


/////
//main.cpp
#include <iostream>
#include "foo.h"

int main(){
    foo bar("hello");
    //call a random function like func1, func2, func3;
    return 0;
}



laravel get specific random model

I use laravel 8. get random 3 users:

Users::inRandomOrder()->limit(3)->get();

but I want to add a specific user to the random output.

example :

Users::find(1);

output:

// [1, 5, 7, 9]

Thanks for helps




How to print random numbers from a selected sequence?

I want the program to print randomly one of these numbers:

{1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10}

Instead it prints randomly nonsense numbers

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

int main()
{
  srand( time(NULL) );
  int card;
  int deck[40] = {1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10};
  card = rand()% deck[40];
  printf("%d", card);
  return 0;
}

What can I do? thanks




dimanche 29 novembre 2020

Random walk in python using matplotlib, random and numpy

import random

N = 30

x = 0
y = 0
z = 0

for _ in range(N):

    n = random.random()

    if n < 1/6:
        x += 1
    elif 1/6 <= n < 2/6:
        y += 1
    elif 2/6 <= n < 3/6:
        z += 1
    elif 3/6 <= n < 4/6:
        x -= 1
    elif 4/6 <= n < 5/6:
        y -= 1
    elif n >= 5/6:
        z -= 1

    print(f"({x},{y},{z})")  # python 3.6ism

print("squared distance = {}".format(x*x + y*y + z*z))

This is my code for simulating a random walk. I would like to make this random walk biased towards going up. How can I do that?




Generating a 6 digit unique random number

I want to create a 6 digit unique random number and check with existing numbers in the file and if its same, i need to generate another number until its unique.

While debugging I was able to find out that this is almost successful and if the number is same, it generates the new unique number but after the competition of the else if statement and when it returns back to the if statement to check if the new created number is equal to the first line read in the file, the program crashes and goes to the try catch statement.

Please note in "Customer.Txt" the unique number will be in the following order. First unique number will be in row 1, second one will be 9 and third will be 17 and hence forth.

Can anyone help me in figuring out what is the issue here?

Random MemeberShipId = new Random()
StreamReader InputFile
InputFile=File.OpenText("Customer Info.txt");
while(!InputFile.EndOfStream)
{
  X = int.Parse(MemeberShipId.Next(0, 999999).ToString("000000"));
  Y = int.Parse(InputFile.ReadLine());
  if(X!=Y)
{
for(int J=1;J<8;J++)
{
Temp=InputFile.ReadLine();
}
}
else if(Y==X)
{
MessageBox.Show("Same Unique Number Found, Creating another Unique number");
X=int.Parse(MemebershipId.Next(0,999999).ToString("000000);
}
}



Does np.random.randint size can be unlimited?

X1 = np.random.randint(low=PRD.iloc[0], high=PRD.iloc[1], size=(100000000))

Does the size possible to make it unlimited?

because i want them to keep generating.




Performance of Random number generators of pyroot and random

I was looking to optimize a simple given code that generates a random number ([0,1,2]) that is not in a given list. The random number generator is TRandom3 from ROOT.

def getNumber(noList, randomgen):
    #Fügen Sie hier Ihren Code ein!: 💩
    i = randomgen.Integer(3)
    while i in noList:
        i = randomgen.Integer(3)
    return i

It is very basic and just generates new numbers until an allowed one is reached.

My own optimized code looked like this:

def bessereAuswahl(noList):
    return random.choice([elem for elem in [0,1,2] if elem not in noList])

I just remove all not allowed numbers from my list [0,1,2] and use random.choice to pick one element.

Running on windows 10 I had a performance increase, running the same code on linux I had a performance decrease.

Why is that the case?

Is there a hidden performance penalty for random on linux or is it a performance boost in pyroot?




How can I make a random generator in Javascript for a discord bot?

I'm a beginner in coding and I'm trying to learn to code a discord bot that messages a random generated things, like lets say I'm doing an advice command, what I want it to do is to pick 1 out of 10 advice tips randomly. Hopefully anyone understands, thank you.




Select a random alphabetical string without import random

I would like to know how to select a random alphabetical string from a list WITHOUT importing "random"

the list looks like the following example

words = ["aberrant","abhorrent","abiding","abject"]




Why do we XOR with 4101842887655102017 while implementing Ranq1 in Numerical Recipes (c++)?

Good afternoon everyone. I am reading through the Numerical Recipes book (Edition 3) by William H. Press, Saul A. Teukolsky, William T. Vetterling.

On the page 351 the example of the composed random number generator is given. I can understand all code line by line, yet I hardly can comprehend why there is XOR operation between v^j. Could anyone explain why do we do the XOR between the seed and v?

struct Ranq1 {
Ullong v; //the long long 64-bit variable (typedef)
Ranq1(Ullong j): v(4101842887655102017LL) {
    v^=j; 
    v = int64();
}
//Xorshift algorithm to generate uniform random numbers with 
inline Ullong int64() {
    v ^= v >> 21;
    v ^= v <<35;
    v ^= v >> 4; 
    return v * 2685821657736338717LL; //d1

}
};

Will be grateful for any ideas and help!




How can I generate an array of random numbers that fluctuate by 1 in javascript?

I want to be able to generate the following array (or something like it) in javascript:

[
  52, // random number 0-100
  53, // random +1 or -1
  54, // random +1 or -1
  53, // random +1 or -1
  52, // random +1 or -1
  53, // random +1 or -1
  52, // random +1 or -1
  51, // random +1 or -1
  50, // random +1 or -1
  51, // random +1 or -1
  // etc., etc., etc.
]

How can I do that?

I've tried this, but I always get a random number followed by 1's and -1's only:

Array(50).fill(0).map((v, i, a) => i !== 0 ? (Math.round(Math.random()) ? a[i-1] + 1 : a[i-1] - 1) : Math.floor(Math.random() * 101))



Adding random values in column depending on other columns with pandas

I have a dataframe with the Columns "OfferID", "SiteID" and "CatgeoryID" which should represent an online ad on a website. I then want to add a new Column called "NPS" for the net promoter score. The values should be given randomly between 1 and 10 but where the OfferID, the SideID and the CatgeoryID are the same, they need to have the same value for the NPS. I thought of using a dictionary where the NPS is the key and the pairs of different IDs are the values but I haven't found a good way to do this.

Are there any recommendations?

Thanks in advance. Alina




samedi 28 novembre 2020

Not able to display random words in python

import random
from words import voc_list
import time
from plyer import notification

def get_word():
    word = random.choice(voc_list)
    return word.upper()

if __name__ == "__main__":
    while True:
    
        notification.notify(
        title = "Here is another vocablary word :-"
        The_word = random.choice(voc_list)
        Timeout = 8
        )
    
    
    
    

I am trying to make a vocabulary reminder that tells you a new word in every 2 hours. I made a list of words along with their meaning and trying to display any one randomly for which I have used from words import voc_list but why it is showing as invalid syntax here The_word = random.choice(voc_list)




C ++Output to file is incorrect?

This program is to generate numbers between 0 - 2^32, and I am trying to copy this randomly generated sample into a file, but it gives output as a string of multiple "equal signs(=)'. I don't understand where the error can be from. I also attached an image of the output

#include<iostream>
#include<conio.h>
#include <ctime>
#include<fstream>
#include <cstdlib>
#include <iomanip>
#include <math.h>
#include <vector>
#include <random>
#include <string>

using namespace std;

int main(){

    int ya;
    vector<unsigned long long> instance;
    fstream inFile;
    inFile.open("outputFile.txt");

    if (!inFile) {

        cout << "The file can't be opened" << endl;
    }

    std::mt19937_64 generator;
    generator.seed(std::time(0));
    uniform_int_distribution<unsigned long long>randomNumber(0, 4294967295);

   
    for (int index = 0; index < 10; index++) {
      cout << randomNumber(generator) << endl;
       inFile << randomNumber(generator)<<"\n";
       //instance.push_back(randomNumber(generator));
    }


   
   
    if (inFile.is_open()) {

        cout << inFile.rdbuf();
    }

   
    return 0;
}



Trying to make randomly generated collages in Processing

I’m really new to Processing 3 and I’m really enjoying it but also about to rip my hair out! I am wanting to to create random collages that are built from .png assets. The code works fine at the moment and does (half) of what I want it to do.

I was wondering if anyone could help me with the following please?

  1. Applying a random positioning property to the images so they appear randomly across the canvas so they are not just in a line
  2. The same as above but a variable size
  3. Adding a code that stops the same image from duplicating in one collage

Thanks so much in advance, here is my code so far:

PImage[] images = new PImage[67];
int[] counters = new int[5];
int DISPLAY_TIME = 4000; 
int lastTime; 
int number = 0;
 
 
 
void setup() 
{ 
  size(600, 600); 
  for (int i = 0; i < images.length; i++) 
  { 
    images[i] = loadImage("Collage_" + nf(i+1, 2) + ".png"); 
    images[i].resize(100,100);
    
 
  } 




  lastTime = millis(); 
 
}   
 
void draw() 
{ 
  background(250); 
  fill(250);   
  if (millis() - lastTime >= DISPLAY_TIME)
  { 
  for( int i = 0; i < counters.length; i++){
  counters[i] = int(random(0,images.length));
}
lastTime = millis();  
  } 
for( int i = 0; i < counters.length; i++){
  image (images[counters[i]], 40 + 30 * i, 50);}
}
 
 
void keyPressed(){
  if(key == 's'){
    println("Saving...");
    String s = "screen" + nf(number,4) +".jpg";
    save(s);
    number++;
    println("Done saving.");
  }
}



What's the best random number generator for android?

There are many generators out there, but none completely suits me. First of all, we need a simple one, with a good design, convenient and with wide functionality.




Generate stock like data time series?

Is there a quick way to generate random stock like data series ?

What I mean is data sequence which looks like a stock or a temperature or seasonal graph i.e. not jagged ups and downs, but more like a time based curve.




I'm creating terrain that overlaps while it isn't supposed to

I'm creating a simple platformer in MonoGame with procedurally generated islands as terrain. I have 4 important classes: AllIslands, Islands, Ground, and GroundBlocks. AllIslands is a class that manages the islands and causes them to procedurally generate. Islands is the class that makes the island with random length and position. Ground is the class that manages and creates rows of GroundBlocks.

I'm trying to generate the islands with room in between them, to do this I use the variable RightXOfLastIsland, this variable contains the rightmost X value of an island. I look at the RightXOfLastIsland and then add a random amount to it for the position of the new island. My problem is that the islands overlap and I have no idea why.

class AllIslands
{
    public List<Island> ListOfIslands = new List<Island>(0);
    public int RightXOfLastIsland = 0;

    public AllIslands()
    {

    }

    public void CreateIsland(Ground ground)
    {
        if (ListOfIslands.Count > 0)
        {
            Island previousIsland = ListOfIslands[ListOfIslands.Count - 1];
            RightXOfLastIsland = previousIsland.RightXOfLastIsland;
        }
        Island island = new Island(ground, RightXOfLastIsland);
        ListOfIslands.Add(island);
    }
    public void ProcedurallySpawnIslands(Player player, Ground ground)
    {
        if (player.Position.X > RightXOfLastIsland - 200)
        {
            CreateIsland(ground);
        }
    }
}

class Island
{
    public int RightXOfLastIsland;

    public Island(Ground ground, int rightXOfLastIsland)
    {
        RightXOfLastIsland = rightXOfLastIsland;

        Random random = new Random();

        int tempRightX = RightXOfLastIsland / 100;

        int locationX = random.Next(tempRightX + 5, tempRightX + 10);
        int locationY = random.Next(5, 9);
        int lengthRowOfBlocks = random.Next(5, 10);

        Vector2 location = new Vector2(locationX * 100, locationY * 100);

        ground.CreateGroundBlocks(location, lengthRowOfBlocks);

        RightXOfLastIsland = RightXOfLastIsland + (lengthRowOfBlocks * 100);
    }
}



Predict SHA-256 RNG (random number generator) based on previous SHA-256

There is a system that make random SHA-256 and put in the formula to make a coefficient(somehow like casino). and before coefficient close they put MD-5 of SHA-256 that made by RNG and as you we cant decrypt MD-5.

Predicting SHA-256 is the only way to get coefficient. Can I predicting random SHA-256 based on previous SHA-256?




I need to get prolog to guess random element in a lost in x amount of tries

Write a predicate to interactively guess an element from a list in at most k tries, where k is also an input (integer) value. this is the exact question. I'm not sure if that means If i also have to get the list from the user. How do i get a random element and how do i make it run x number of times? up until now all i know is doing something until the list is empty method([],[]). <=like that. currently my code looks something like this.

'''guess_number:- write("Please insert a list"), read(L), write("Please insert amount of tries"), read(T).'''




Skewed t-distribution in python

Python has scipy.stats.t which can generate random numbers (rvs) and fit the parameters (fit) that follow the t-distribution, but is there something similar in python for fitting and generating a skewed-t distribution?

If not, can scipy.stats.t be modified somehow to be the skewed t?




vendredi 27 novembre 2020

Python - How does argument 'function' affect a list when using shuffle

When you use shuffle(x, random), you have two parameters: the list and the function. By default, the function is random(), which returns a random value between 0 and 1.

Now, what I would like to know is, how does this affect the list? If, for example, I assign a function to return a specific value in such way like the following:

import random

def myfunction():
  return 0.1

mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist, myfunction)

print(mylist) #Prints: ['banana', 'cherry', 'apple']

What will happen? From what I've seen, the way the list is organized changes. So, If I, once again, determine the value the function returns, will It be organized differently?

import random

def myfunction():
  return 0.9

mylist = ["apple", "banana", "cherry"]
random.shuffle(mylist, myfunction)

print(mylist) #Prints: ['apple', 'banana', 'cherry']

Whereas If return a value such as 0.89, the way the list is organized does not change. This leads to my doubt.

I probably made some vague assumptions, but It's the best explanation I have.




Weighted random sample of array items *without replacement*

I want to generate a random sample from an array of objects using an array of weighted values for each object. The weighted list may, or may not, be integer values. It could be floats like [0.2, 0.1, 0.7, 0.3], or it could be integers like [20, 10, 70, 30]. The weights do not have to add up to a value that represents 100%.

Peter below gave me a good reference on the general algorithm that I'll have to take a closer look at. It's not specific to JS, but this was what he linked: https://stackoverflow.com/a/62459274/7915759

I didn't see a ready-made accumulate() that I could use, so put this together:

function accumulate(numbers) {
    let accum = [];
    let total = 0;
    for (let n of numbers) {
        total += n;
        accum.push(total);
    }
    return accum;
}

To choose a single object from the population:

function wchoice(pop, wts) {
    let acm = accumulate(wts);
    let tot = acm[acm.length - 1]; // sum of all weights.
    let rnd = Math.random() * tot;

    // a *native* bisect_left() would be more efficient here:
    let idx = acm.findIndex((elm) => rnd <= elm); 

    return [idx, pop[idx]];
}

(Error handling logic is removed from these examples to keep them simple.)

Array.findIndex() is alright for the purposes I need this for, but it would be more efficient if there were a native bisect_left() function to locate the index of the chosen member.

Generating a sample with replacement is just a matter of calling wchoice() k number of times. But, to choose k members from the population without replacement is more involved:

function wsample(population, weights, k) {
    weights     = [...weights];
    let sample  = [];
    let indices = [];
    let index   = 0;
    let choice  = null;

    for (let i=0; i < k; i++) {
        [index, choice] = wchoice(population, weights);
        weights[index]  = 0; // Eliminates the item from subsequent picks.
        sample.push(choice);
        indices.push(index);
    }
    return [indices, sample];
}

k must be <= the number of non-zero items in weights.

So that's what I have so far. I have somewhat of a solution, but I'm not certain this is the best way. Any tips are appreciated.




Why is random.shuffle so much slower than using sorted function?

When using pythons random.shuffle function, I noticed it went significantly faster to use sorted(l, key=lambda _: random.random()) than random.shuffle(l). As far as I understand, both ways produce completely random lists, so why does shuffle take so much longer?

Below are the times using timeit module.

from timeit import timeit
setup = 'import random\nl = list(range(1000))'

# 5.542 seconds
print(timeit('random.shuffle(l)', setup=setup, number=10000))

# 1.878 seconds
print(timeit('sorted(l, key=lambda _: random.random())', setup=setup, number=10000))



Random dates without duplicates based on the value of other columns

I have a temp table called #RandomDates that looks like this in SQL Server:

╔════╦═════════════╦══════════╦══════════════════╦════════════════════════════════╦═══════════════════════╗
║ ID ║ Description ║ RaceType ║ RaceStartTime    ║ AverageCompletionTimeInMinutes ║ PredictCompletionTime ║
╠════╬═════════════╬══════════╬══════════════════╬════════════════════════════════╬═══════════════════════╣
║ 1  ║ Player1     ║ RaceA    ║ 2025-05-10 10:00 ║ 120                            ║ NULL                  ║
╠════╬═════════════╬══════════╬══════════════════╬════════════════════════════════╬═══════════════════════╣
║ 2  ║ Player2     ║ RaceA    ║ 2025-05-12 17:00 ║ 120                            ║ NULL                  ║
╠════╬═════════════╬══════════╬══════════════════╬════════════════════════════════╬═══════════════════════╣
║ 3  ║ Player3     ║ RaceC    ║ 2025-08-12 08:15 ║ 60                             ║ NULL                  ║
╠════╬═════════════╬══════════╬══════════════════╬════════════════════════════════╬═══════════════════════╣
║ 5  ║ Player4     ║ RaceY    ║ 2025-08-29 16:00 ║ 10                             ║ NULL                  ║
╠════╬═════════════╬══════════╬══════════════════╬════════════════════════════════╬═══════════════════════╣
║ 6  ║ Player4     ║ RaceY    ║ 2025-08-30 21:00 ║ 10                             ║ NULL                  ║
╚════╩═════════════╩══════════╩══════════════════╩════════════════════════════════╩═══════════════════════╝

I want to update the column "PredictCompletionTime" with random dates however I need them to be based on the values of columns "RaceStartTime" and "AverageCompletionTimeInMinutes".

Example for ID = 1

  • RaceA takes place on 2025-05-10 10:00
  • RaceA takes an average of 120 minutes to complete
  • I want my randomized "PredictCompletionTime" column to be somewhere between:

RaceStartTime + AverageCompletionTimeInMinutes + RANDOMLY add OR deduct a small amount of MINUTES and SECONDS ( lets say between 5 to 10 minutes )

So valid dates for this example could be:

2025-05-10 12:07:20

2025-05-10 11:59:40

I have tried doing this with RAND()* but for some reason my "PredictCompletonTime" column keeps getting updated with duplicated values for each RaceType.

Thanks in advance,




How do i create random weights within a range that add up to 1 in python

How do i create an array of random numbers that a) add up to 1 and b) are subject to upper and lower bounds? For example, assume the upper and lower bounds are 0.1 and 0.5 and i want to create an array of three random floats x1, x2 and x3 that add up to 1. thx in advance!




Function in MATLAB to draw samples from Uniform Distribution

I want to draw randomly from a Uniform Distribution defined as below by code in MATLAB :-

pd1 = makedist('Uniform','lower',-0.0319,'upper',0.0319); % X1

In MATLAB the usual command is random() but the help file tells me its only for Guassian mixture distributions. So can it also be extended for use in Uniform Distribution or is there any other function to explicitly draw randomly for Monte Carlo Simulations.




Random rows from db with each having equal probability

I have a database where I have a table with 100 rows, and I want to select 5 rows at random from that table such that each row has an equal chance to be selected.

Edit:

Basically, those rows are Ads and I want each Ad to get equal screen time. That is why any algorithm that just selects 5 rows randomly but also makes sure that each row gets selected equally in a day.




Fill an array[][] with either X or 'c'

i have an array the size 200200 filled all with the letter 'c'. Now I have to fill randomly in the middle of the array with the size of 1010 either the letter 'c' (which is already inside) or the letter 'x'.

So my guess was to solve it with a for-loop starting for both brackets [] at 94 to 104 and then use a random method to insert the value 'x'. But what random method is there, for something like this. I can not use Math.random for this right?




Flutter : how to show next index after complete a specific logic in Swiper, where GridView also set in Swiper?

i set a GridView in Swiper (Swiper took by importing, import 'package:flutter_swiper/flutter_swiper.dart';). and i want to show next index of Swiper after completing a logic in GridView. suppose, i have a long string list(array) and took four value string from this list(array) by random, this four values string set in GridView index.

Again i make a new string list(array) by this four value string and took a value from this new string list(array) by random, this single string set in Swiper. finally if user can select the Swiper index value to the GridView four index value correctly, then user can see next screen in Swiper. but output is not working properly. problem is - at first i set white color in GridView index, if it is correct answer should be green color in GridView index and incorrect will be red color in GridView index. here is my logic made it messy.

I'm trying to make a word game. First of all, the index will be white. if user Click the correct answer then index will be to green color and go to next screen, also index will be white in next screen.. again if user click incorrect answer then index will be to red color and don't let go to the next page until user put correct answer...

import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:math';

class GameWordRoute extends StatefulWidget {
@override
 _GameWordRouteState createState() => _GameWordRouteState(); }

class _GameWordRouteState extends State<GameWordRoute> {

SwiperController _controller = SwiperController();
SwiperControl _control = SwiperControl(color: Colors.white);

double get _width => MediaQuery.of(context).size.width;
double get _height => MediaQuery.of(context).size.height;

bool inLastPage = true;
bool _answer = false;

List<Color> colorList = <Color>[Colors.white, Colors.white, Colors.white, Colors.white,];
List<String> gameButtonList = <String>[];

FlutterTts flutterTts = FlutterTts();

@override
Widget build(BuildContext context) {

var sizeDevice = MediaQuery.of(context).size;
final orientation = MediaQuery.of(context).orientation;

final double itemHeight = sizeDevice.width / 6;
final double itemWidth = sizeDevice.width / 2;

return Scaffold(
  backgroundColor: Colors.purple, // white
  body: SafeArea(
    child: Column(
      children: <Widget>[
        Expanded(
            flex: 1,
            child: Container(
              color: Colors.lightBlueAccent,
            )),
        Expanded(
          flex: 8,
          child: Container(
            color: Colors.cyan,
            child: Swiper(
              controller: _controller,
              loop: false,
              scrollDirection: Axis.horizontal,
              itemCount: word_data.drink.length,
              onIndexChanged: (value) {
                if (value == word_data.drink.length - 1)
                  setState(() {
                    inLastPage = true;
                  });
                else {
                  setState(() {
                    inLastPage = true;  // false
                  });
                }
              },
              itemBuilder: (BuildContext context, int index) {
                gameButtonList.clear();
                var fourValueRandom = new Random();

                for (var i = 0; i < 4; i++) {
                  final fourGameBtnRandom = word_data.drink[fourValueRandom.nextInt(word_data.drink.length)];
                  gameButtonList.add(fourGameBtnRandom);
                }

                var oneValueRandom = new Random();
                var oneValueRandomGet = gameButtonList[oneValueRandom.nextInt(gameButtonList.length)];
                var wordDataReplace = oneValueRandomGet.replaceAll(" ", "_").toLowerCase();
                return Container(
                  child: Column(
                    children: <Widget>[
                      Expanded(
                          flex: 8,
                          child: Container(
                            color: Colors.purple,
                            width: _width,
                            alignment: Alignment.center,
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: Image.asset("asset/drink_images/" + wordDataReplace + ".png",
                                fit: BoxFit.contain,
                              ),
                            ),
                          )),
                      Expanded(
                          flex: 1,
                          child: Container(
                            color: Colors.yellow,
                            width: _width,
                            alignment: Alignment.center,
                            // "${categoryTitleArray[index]}"
                            child: Text("What is this?"),
                          )),
                      Expanded(
                          flex: 4,
                          child: Container(
                            color: Colors.yellow[200],
                            width: _width,
                            alignment: Alignment.center,
                            child: GridView.builder(
                                padding: EdgeInsets.all(8),
                                itemCount: 4,
                                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: (orientation == Orientation.portrait) ? 2 : 4,
                                  crossAxisSpacing: 5,
                                  mainAxisSpacing: 5,
                                  childAspectRatio: (itemWidth / itemHeight),
                                ),
                                itemBuilder: (BuildContext context, int index) {
                                  return GestureDetector(
                                    onTap: () {
                                      if (index == 0) {
                                        if (gameButtonList[0] == oneValueRandomGet){
                                          _answer = true;
                                          inLastPage = false;
                                          colorList[0] = Colors.green;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);

                                        }else{
                                          colorList[0] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }

                                      } else if (index == 1) {

                                        if (gameButtonList[1] == oneValueRandomGet){
                                          _answer = true;
                                          colorList[1] = Colors.green;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
                                          inLastPage = false;
                                        }else{
                                          colorList[1] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }

                                      } else if (index == 2) {
                                        if (gameButtonList[2] == oneValueRandomGet){
                                          _answer = true;
                                          colorList[2] = Colors.green;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
                                          inLastPage = false;
                                        }else{
                                          colorList[2] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }
                                      } else if (index == 3) {

                                        if (gameButtonList[3] == oneValueRandomGet){
                                          _answer = true;
                                          colorList[3] = Colors.green;
                                          inLastPage = false;
                                          setState((){});
                                            _showCorrectAndIncorrectDialog("Congratulation", "asset/icon_images/ok_emoji.png", "Correct answer", Colors.green);
                                        }else{
                                          colorList[3] = Colors.red;
                                          inLastPage = true;
                                          setState((){});
                                        }
                                      }
                                    },
                                    child: Container(
                                      child: new Card(
                                        elevation: 0,
                                        color: colorList[index], //Colors.transparent,
                                        child: Center(
                                          child: Text(
                                            "${gameButtonList[index]}",
                                            textAlign: TextAlign.center,
                                            style: TextStyle(color: Colors.black),
                                          ),
                                        ),
                                      ),
                                    ),
                                  );
                                }),
                          )),
                    ],
                  ),
                );
              },
            ),
          ),
        ),
        Expanded(
            flex: 1,
            child: Container(
              color: Colors.lightBlueAccent,
            )),
      ],
    ),
  ),
);
}

void _showCorrectAndIncorrectDialog(String _title, String _image, String _subTitle, Color _color){

showDialog(
    context: context,
    builder: (BuildContext context){
      Future.delayed(Duration(milliseconds: 500), () {
        Navigator.of(context).pop(true);
      });
      return AlertDialog(
        title: Text(_title, textAlign: TextAlign.center, style: TextStyle(color: _color),),
        content: Container(
          height: _width/1.1,
          child: Column(
            children: <Widget>[
              Expanded(
                flex: 4,
                child: Container(
                  // color: Colors.cyan[100],
                  child: Image.asset(_image,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(height: 8),
              Expanded(
                flex: 1,
                child: Container(
                  color: Colors.cyan,
                  child: Center(
                    child: Text(
                      _subTitle,
                      style: TextStyle(
                        // fontSize: 24,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }
);
}
}

preview the screen of this source code




jeudi 26 novembre 2020

C#: Random.NextDouble method stalling out application

I'm receiving some inconsistent behavior from the Random.NextDouble().

Regularly, the console would freeze and the cpu usage would increase dramatically until I closed it down. I ran the debugger and found that the cause of the freezing was Random.NextDouble(). I added some lines for debugging purposes, but the code is as follows:

        double generateCatenationRate()
        {
            double catenation = 999.999; //random value to see if it pops up down there
            double uniformValue;
            double int_covalence = covalence.original;
            double dist = int_covalence - 4;


            int counter = 0;
            while (true)
            {
                counter++;
                uniformValue = utils.getRandomDouble(); //goes bad here!
                if (uniformValue <= 0.15)
                {
                    catenation = Math.Abs(utils.normalize(dist, 0, 4)) + uniformValue;

                    if (catenation < 0 || catenation > 1)
                    {
                        if (counter > 10000)
                        {
                            Console.WriteLine("Went nuclear!");
                            break; //break so console doesn't stall out
                        }
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }

            }
            Console.WriteLine("Took "+counter+" iterations.");
                return 1 - catenation;
        }

And:

        public static double getRandomDouble()
        {
            Init();
            return random.NextDouble();
        }

Lastly:

        private static void Init()
        {
            if (random == null) random = new Random();
        }

It typically does not stall out, but running it several times successively produces output such as:

Took 4 iterations.
Took 3 iterations
Took 3 iterations.
Took 23 iterations.
Took 12 iterations.
Took 4 iterations.
Went nuclear!
Took 10007 iterations.

Can anyone explain why Random.NextDouble() occasionally seems to create an infinite loop? Looking around, I suspect it has something to do with how the values are seeded, but any insight would be appreciated; would love to fix this issue.

Thank you!




Getting Smoothly Animated GAN Output

I am working on a TensorFlow GAN that generates abstract art, and I'm hoping to pass in a set of inputs to produce a smooth output animation. I started with the following code to do so:

import tensorflow as tf

# Create a noise vector by sampling a normal distribution
noise_vec = tf.random.normal([100,1])

for i in range(frames):
     tf.concat([noise_vec, [noise_vec[-1]] + 0.1*tf.random.normal([100,1])], 0)

generated_frames = Generator(noise_vec)

As expected, making slight variations to the generator's input produces slight variations in its output, so the frames start out with smooth changes. However, since variance is additive between random variables, the values in the noise vector become more and more extreme for later frames. Since the network was only trained on a single tf.random.normal sampling, it ends up producing ugly results. Is there any way to randomly "step" the noise vector through an animation while keeping values within the range that the generator expects?




How can I deterministically create a lazy random Numpy array?

Essentially, what I want to do is have some random stream that looks like:

x = np.random.standard_normal(N)

where N is an enormously large number. So, x can't fully exist in memory because it is too large. So, I want to be able to create an object that behaves like a lazily executed Numpy array, but can be deterministically and consistently sliced to return actual Numpy arrays: x[a:b]

Essentially, is there a way to "jump" to a different position in Numpy's RNG?


It seems there is some mention of jumping ahead in the numpy.random documentation but this does not seem like what I am looking for and it only has a very specific large jump size.




bash shell pull all values from array in random order. Pull each value only once

I need to pull the values from an array in a random order. It shouldn't pull the same value twice.

R=$(($RANDOM%5))
mixarray=("I" "like" "to" "play" "games")
echo ${mixarray[$R]}

I'm not sure what to do after the code above. I thought of putting the first pulled value into another array, and then nesting it all in a loop that checks that second array so it doesn't pull the same value twice from the first array. After many attempts, I just can't get the syntax right.

The output should be something like: to like I play games

Thanks,




Simulate an election

import random

def trial_election(win_chance):
  if random.random() < win_chance:
    return 'win'
  else:
    return 'lose'

region_1 = trial_election(0.87)
region_2 = trial_election(0.65)
region_3 = trial_election(0.17)
  
tally = 0
for trial in range(10_000):
  if region_1 == 'win':
    if region_2 == 'win':
      tally+=1
    elif region_3 == 'win':
      tally+=1
  elif region_2 == 'win':
    if region_1 == 'win':
      tally+=1
    elif region_3 == 'win':
      tally+=1
  elif region_3 == 'win':
    if region_1 == 'win':
      tally+=1
    elif region_2 == 'win':
      tally+=1
print(f'The winning percentage is {tally/10_000}')

The request for this code is as such: Suppose two candidates,CandidateA and CandidateB,are running for mayor in a city with three voting regions.The most recent polls show that CandidateA has the following chances for winning in each region: •Region1:87percentchanceofwinning •Region2:65percentchanceofwinning •Region3:17percentchanceofwinning Write a program that simulates the election ten thousand times and prints the percentage of times in which Candidate Awins. I only get 1.0 or 0 from running above code, I had expected to get more varieties between 0 and 1, can anyone tell me what is wrong please?




Problem producing a new random number at the end of HiLo guessing game

I'm creating a HiLo guessing game in Java. Everything I have so far works as intended except at the end when I prompt a user to play again, the random number remains the same from the previous game. How do I make it so the code produces a new random number when the user chooses to play a new game?

    int answer  = (int)(Math.random() * 100 + 1);
    int guess = 0;
    int guessCount = 0;
    boolean playGame = true;
    String restart;
    Scanner scan = new Scanner(System.in);
    
while(playGame == true)
{
    while (playGame == true) 
    {
        System.out.println("Enter a number between 1 and 100: ");
        guess = scan.nextInt();
        guessCount ++;
        
        System.out.println(answer);
        
        if (guess < 1 || guess > 100) 
        {
            System.out.println("You have entered an invalid number.");
            guessCount --;
        } else if (guess == answer) 
        {
            System.out.println("Correct! Great guess! It took you " + guessCount + " tries!");
            break;
        } else if (guess > answer) 
        {
            System.out.println("You've guessed too high! Guess again: ");
        } else if (guess < answer)
        {
            System.out.println("You've guessed too low! Guess again: ");
        }
    }
    
    System.out.println("Would you like to play again? Y/N");
    restart = scan.next();
    
    if (restart.equalsIgnoreCase("Y")) 
    {
        playGame = true;
    } else if(restart.equalsIgnoreCase("N"))
    {
        System.out.println("Thank you for playing!");
        break;
    }
}



How to make a random password generator with at least one capital letter, lowercase letter, special character and number everytime in php

I am trying to do what the title says and this is all that I can figure out how to do in php.

<?php 
    $random = substr(md5(mt_rand()), 0, 8
    echo $random;
?>



Deceitful but innocent-looking random number generator seed

What would be the the best RNG seed controllable by sinister developer / software user, which - when discovered - could be explained as silly and innocent developer mistake?

Example: some kind of setSeed(CURRENT_MILLISECOND) with usage of macro, but somewhere else make that macro multiply current second by 1000, making output predictable.




python print out same random number

Generate three random integers between 1 and 20, and check if exactly two of them are the same. If exactly two are the same, tell the user “Exactly two numbers are the same”. In any case, print out all three randomly generated numbers as well. (without using count() and function()




Как совместить input с range ? Python [closed]

как спросить если expNum = любое число от 1 до 100? Не понимаю как использовать функцию range там

import random 
expNum = int(input("In what range ? "))

if expNum == range(1, 100):

Спасибо




unable to shuffle array correctly in react

I am trying to shuffle an array in react . I fetch the data from the api and then I want to mount the data pictures as a shuffled array in my screen and not in the order I fetched them .

This is my code :

useFetch.js

import {React , useState , useEffect} from 'react';

export default function useFetch() {
  
  const [ pokemon,setPokemon] = useState([]);
  const [shuffled,setShuffled]= useState([]);
  useEffect(()=>{
    const fetchPokemon = async () =>{  //here I fetch my pokemon 
      const promises = [];
      for (let i=1;i<=10;i++){
        let  url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        let response = await fetch(url);
        let result = await response.json();
        promises.push(result);
      }

      const data = await Promise.all(promises);
      setPokemon(...pokemon,data); //successfully sets the pokemon data 
    }


    const shufflePokemon = ()=>{ //here I try to shuffle the pokemon array and return a random on mount 
      fetchPokemon(); 
      let randomArray= pokemon.map((poke,index)=>{ //this is what I am trying to do to shuffle the array  but it is not correct 
         let  j = Math.floor(Math.random() * (index + 1)); 
         let temp = poke[index];
         poke[index] = poke[j];
         poke[j] = temp;
      })
      setShuffled(...shuffled,randomArray);

    }

    shufflePokemon(); //call shuffle on mount 
  },[])
 
   return {shuffled} //returns shuffled array of objects 

}

In my code above in the shufflePokemon function I try to give an idea of what needs to be done but the code is obviously not correct . I would appreciate your help




Am I overlooking something in the statistics of my Secret Santa draw?

We are doing the typical Secret Santa draw in my Company for Christmas. We are 12 people divided into 2 companies, the first company is "Bit" and the second is "MP".

I will describe here how the draw works, programmed in C#:

We have a list with 12 people:

  • 6 people are from Bit
  • 6 people are from MP

First we shuffle the list so the first person who begins choosing is fully random and therefore the order of the list does not matter anymore.

Then we start the draw with the first person of the shuffled list, let's say Person 6.

Person 6 pulls one person from the whole 12 people pool. If this person 6 has pulled himself, then it does not count and he pulls another one (the person 6 would be again available in the pool), until it is different from Person 6.

So let's say Person 6 (MP) -> Person 1 (Bit)

When person 6 obtains someone assigned, this assigned person (in this case Person 1) can't be assigned anymore and we continue with the draw with the other remaining 11 people.

We also catch the case, which the last person can not pull anyone but himself. For instance (example with 4 people):

  • Person 1 -> Person 3
  • Person 2 -> Person 1
  • Person 3 -> Person 2
  • Person 4 -> ?????

In this case, all people and their assignee are reset and the draw begins again.


With the draw explained, we just programmed some statistics to test that the draw random enough is.

After some simulations ~ 10.000 iterations (draws) we got these results:

  • Bit -> Bit: 29881 (this means it has happened 29881 times that someone from the Company Bit got assigned someone from the company Bit)
  • Bit -> MP: 30119
  • MP -> Bit: 30119
  • MP -> MP: 29881

And the question is: WHY no matter how many times we do the simulation and how many iterations/simulation are configured, the number of Bit -> MP = MP -> Bit and Bit -> Bit = MP -> MP?




How to write python random string generator with alternating vowels and consonants and custom string length?

I have no idea how to do this and I don't know if it is ok to ask this here without giving anything I have already done. Because I didn't do anything. Expected results are:

xapoti bahepami mucif avelo vinel aligator erihemi labiwon

etc.




Generate terms which add up to x

I am trying to take y number of terms and make them added together to equal a predefined x.

I can't seem to think of an answer to this, and havent exactly tried anything other than for loops to generate some numbers.

If anyone could show some examples or try to explain, that would be very much appreciated.

EDIT: Examples of terms: "3g", "-5o", "4"




Ask questions with attributes and functions

This is my code:

class People:

    def __repr__(self):
        return f"A('{self.name}', {self.age})"

    def __init__(self, name, age):
        self.name = name
        self.age = age

def sortlist():
    people = []
    file = open('people.txt', 'r').readlines()

    for k in file:
        k = k.split()
        people.append(People(k[0], float(k[1])))
    people.sort(key=lambda c: (c.age, c.name))
    g = 0
    for g in range(len(people)):
        people[g].height = g + 1
return people

def question_height():
    for i in sortlist():
            print(random(i[0]))

def question_name():
    for i in sortlist():
        for i in range(0,104):
            print(random.choice(i.name))

The last part of the code (after return people) does not work the way I want it to. I want the question_height function to pick out a random number from the height attribute and the question_name function to pick out a random name from the name attribute.

Does anyone have an idea on what I could do to make it work?




what needs doing if including cstdlib doesn't let me use rand()?

So, I'm trying to replicate a simple dice roll using cstdlib and rand(), but visual studio code seems to have a problem with rand, claiming it's not defined, despite me having included cstdlib, any thoughts?

i'll paste the code, as bare bones as it is atm, perhaps someone could figure it out? FYI, I'm using Visual Studio Code on PopOS 20.10 (not sure if it's relevant)

#include <iostream>
#include <cstdlib>
#include <random>

class player
    {
        public:

            std::string name;
            int health;
            int strength = 1 + (std::rand() % 12);
            int defense;
            int initiative;
            int luck;

            void levelup();

            void win();

            void lose();

        private:   

    };

The error it throws up is: namespace "std" has no member "rand" C/C++(135)




mercredi 25 novembre 2020

How do you decipher and solve this?

I saw this code on one of the competitions sites, I try to google it and solve it but I failed hope to help me guys to answer this.

S[[; R D YJOTF UP=GPIMFRT




Seaborn data visualization misunderstanding of densities?

I was playing around with the seaborn library for data visualization and trying to display a standard normal distribution. The basics in this case look something like:

import numpy as np
import seaborn as sns

n=1000
N= np.random.randn(n)
fig=sns.displot(N,kind="kde")

Which behaves as expected. My problem starts when I try to plot multiple distributions at the same time. I tried the brute N_2= np.random.randn(n/2) and fig=sns.displot((N,N2),kind="kde"), which returns two distributions (as wanted), but the one with smaller sample size is significantly different (and flatter). Regardless of the sample size, a proper density plot (or histogram) should have the area below the graph equal to one, but this is clearly not the case.

Knowing that seaborn works with pandas Dataframes, I've tried with the more elaborate (and generally bad and inefficient, but I hope clear) code below to attempt again multiple distributions on the same graph:

import numpy as np
import seaborn as sns
import pandas as pd
n=10000

N_1= np.reshape(np.random.randn(n),(n,1))
N_2= np.reshape(np.random.randn(int(n/2)),(int(n/2),1))
N_3= np.reshape(np.random.randn(int(n/4)),(int(n/4),1))

A_1 = np.reshape(np.array(['n1' for _ in range(n)]),(n,1))
A_2 = np.reshape(np.array(['n2' for _ in range(int(n/2))]),(int(n/2),1))
A_3 = np.reshape(np.array(['n3' for _ in range(int(n/4))]),(int(n/4),1))

F_1=np.concatenate((N_1,A_1),1)
F_2=np.concatenate((N_2,A_2),1)
F_3=np.concatenate((N_3,A_3),1)

F= pd.DataFrame(data=np.concatenate((F_1,F_2,F_3),0),columns=["datar","cat"])
F["datar"]=F.datar.astype('float')
fig=sns.displot(F,x="datar",hue="cat",kind="kde")

Which shows again very different (almost scaled) distributions, confirming that the result in this case is not consistent with what I was expecting (namely, roughly overlapping distributions). Am I not understanding how this graph works? There is a completely different approach to draw multiple distributions on the same graph that I am missing?




Why isn't my java dice program matching actual probability distributions?

I made a really simple dice rolling method and figured there wouldn't be any issues, but when I test it the probability doesn't match real distributions. Is there something wrong in my test or the math.random function that causes this?

public class Dice {
    public static void main(String arg[]) {
        int[] guy = {0,0,0,0,0,0, 0,0,0,0,0,0,0,0};
        for(int i = 0; i< 1000000; i++) {
            guy[rolldice()] = guy[rolldice()] + 1;
            
        }
        for(int j = 0; j< guy.length; j++) {
            System.out.println(j + "Number times is " + guy[j]);
        }
        
    }
    
    public static int rolldice() {
        int die1 = (int)(Math.random()*6) + 1;
        int die2 = (int)(Math.random()*6) + 1;
        //System.out.println("The first die comes up " + die1);
        //System.out.println("The second die comes up " + die2);
        //System.out.println("Your total roll is " + (die1 + die2));

        return die1 + die2;
    }

}

The output is the following:

0Number times is 0
1Number times is 0
2Number times is 91530
3Number times is 91522
4Number times is 91528
5Number times is 91521
6Number times is 91523
7Number times is 91525
8Number times is 91529
9Number times is 91526
10Number times is 91527
11Number times is 91525
12Number times is 91521
13Number times is 0



For which stdlib implementations is std::rand thread safe?

According to cppreference,

It is implementation-defined whether rand() is thread-safe.

Which, if any, major implementations of std::rand are thread safe?




Randomly selecting a value (from a subset of values) at even distribution within a group in excel

I have an excel document with the the following values (only those that are relevant here are provided).

For the value column, I want to select from the values 200, 400, 600, and apply them randomly to each row. Beyond this, I need to have an even distribution within each ID (therefore each ID would have 200 twice, 400 twice, 600 twice).

currently, I have been using this excel formula =CHOOSE(RANDBETWEEN(1,3),200,400,600) in the value column, which randomly selects from the three values, but obviously does not provide an even distribution within each ID group (although it may in certain instances by chance).

ID  value
1   x
1   x
1   x
1   x
1   x
1   x
1   x
2   x
2   x
2   x
2   x
2   x
2   x
3   x
3   x
3   x
3   x
3   x
3   x

Does anyone have a solution for this, either in Excel or Python?




Computer Player for a Gomoku Game in C++ [closed]

A few time ago I made a game similar to Gomoku in C++ that is taking between two players.

Now I want to make it Player vs Computer. I tried to do it in simplest way, by making a function of computer to pick a random cell but I still haven't succeeded. I understood that in order of getting a random number I can use rand() and for a letter something like this:

char letters[] = "abcdefghijklmnopqrstuvwxyz";
char x = letters[rand() % 26];

Can someone help me and describe how to implement a computer player? This is my implementation so far:

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

void print_table(int x[][15]) {
    system("cls");
    for (int i = 0; i < 15; i++) {//the loop that use to print out the english character row
        if (i == 0)
            cout << setw(4) << "A";
        else if (i == 1)
            cout << " B";
        else if (i == 2)
            cout << " C";
        else if (i == 3)
            cout << " D";
        else if (i == 4)
            cout << " E";
        else if (i == 5)
            cout << " F";
        else if (i == 6)
            cout << " G";
        else if (i == 7)
            cout << " H";
        else if (i == 8)
            cout << " I";
        else if (i == 9)
            cout << " J";
        else if (i == 10)
            cout << " K";
        else if (i == 11)
            cout << " L";
        else if (i == 12)
            cout << " M";
        else if (i == 13)
            cout << " N";
        else if (i == 14)
            cout << " O";
        else if (i == 15)
            cout << " P";
    }
    cout << endl;
    for (int i = 0; i < 15; i++) {
        cout << setw(2) << i;//print out the row number
        for (int j = 0; j < 15; j++) {//print out the board game.
            if (x[i][j] == 0) {//the inital value is 0, so when the block is 0 then print out the '.'
                cout << " .";
            }
            else if (x[i][j] == 1) {//when the player O input the block then the value will adding one then if check the block is one then output the 'o'
                cout << " O";
            }
            else if (x[i][j] == 2) {//when the player X input the block then the value will adding two then if check the block is two then output the 'x'
                cout << " X";
            }
        }
        cout << endl;
    }
}
int check_player(int p) {
    if (p == 1) {//change the player everytime before the next loop compile
        p++;
    }
    else {
        p--;
    }
    return p;
}
void input_value(int &t, int &n, int p, int x[][15]) {
    char eng;
    int number;
    do {//the loop that ask for the user input the location.
        cout << "player ";
        if (p == 1) {
            cout << "O";
        }
        else {
            cout << "X";
        }
        cout << ", make a move: ";
        cin >> eng;//input the location
        cin >> number;
        if (eng == 'A')//change the character to different number
            t = 0;
        else if (eng == 'B')
            t = 1;
        else if (eng == 'C')
            t = 2;
        else if (eng == 'D')
            t = 3;
        else if (eng == 'E')
            t = 4;
        else if (eng == 'F')
            t = 5;
        else if (eng == 'G')
            t = 6;
        else if (eng == 'H')
            t = 7;
        else if (eng == 'I')
            t = 8;
        else if (eng == 'J')
            t = 9;
        else if (eng == 'K')
            t = 10;
        else if (eng == 'L')
            t = 11;
        else if (eng == 'M')
            t = 12;
        else if (eng == 'N')
            t = 13;
        else if (eng == 'O')
            t = 14;
        if (!(eng >= 'A'&&eng <= 'M') || !(number >= 0 && number <= 14) || x[number][t] != 0) {//when the input wrong, output the statement to ask anouther input and loop again.
            cout << "Invaid input, Try again!" << endl;
            continue;
        }
        else {//if no problem then this input loop is break and jump to the next statement
            break;
        }
    } while (1);//Because it will break as well so the do-while loop is no any requirement
    n = number;
}
int main() {
    const int num = 15;//the number for constant the array row and column value
    char check_e;//for the user input the column
    int R[num][num] = { 0 }, check_n, player = 1, buger = 0, transfer, playerO_win = 0, playerX_win = 0, draw = 0, check_draw;//the variable that for user input or checking the game statment
    do {//launch the loop for the user input again and again
        check_draw = 0;//reset the checking of draw
        print_table(R);
        input_value(transfer, check_n, player, R);
        R[check_n][transfer] += player;//change the value according the player's input and the player name.
        for (int i = 0; i < num; i++) {
            for (int j = 0; j < num; j++) {
                if (i <= 8 && R[j][i] != 0 && (R[j][i] == R[j][i + 1] && R[j][i] == R[j][i + +2] && R[j][i] == R[j][i + 3] && R[j][i] == R[j][i + 4])) {//the checking for the row bingo
                    if (R[j][i] == 1) {
                        playerO_win++;
                        break;
                    }
                    else {
                        playerX_win++;
                        break;
                    }
                }
                else if (j <= 8 && R[j][i] != 0 && (R[j][i] == R[j + 1][i] && R[j][i] == R[j + 2][i] && R[j][i] == R[j + 3][i] && R[j][i] == R[j + 4][i])) {//the checking for the column bingo
                    if (R[j][i] == 1) {
                        playerO_win++;
                        break;
                    }
                    else {
                        playerX_win++;
                        break;
                    }
                }
                else if (j <= 8 && i <= 8 && R[j][i] != 0 && (R[j][i] == R[j + 1][i + 1] && R[j][i] == R[j + 2][i + 2] && R[j][i] == R[j + 3][i + 3] && R[j][i] == R[j + 4][i + 4])) {//the checking for the \ situation.
                    if (R[j][i] == 1) {
                        playerO_win++;
                        break;
                    }
                    else {
                        playerX_win++;
                        break;
                    }
                }
                else if ((j >= 4 || i >= 4 || i <= 8) && R[j][i] != 0 && (R[j][i] == R[j - 1][i + 1] && R[j][i] == R[j - 2][i + 2] && R[j][i] == R[j - 3][i + 3] && R[j][i] == R[j - 4][i + 4])) {//the checking for the / situation
                    if (R[j][i] == 1) {
                        playerO_win++;
                        break;
                    }
                    else {
                        playerX_win++;
                        break;
                    }
                }
                for (int i = 0; i < num; i++) {//the loop for checking the draw
                    for (int j = 0; j < num; j++) {//this loop will check for every time compilation.
                        if (R[j][i] == 0)//when there are any empty block then the check_draw will adding, the draw situation is the check_draw be 0
                            check_draw++;
                    }
                }
                if (check_draw == 0) {//when the check_draw equal to 0 which mean the situation is no empty block
                    draw++;
                    break;
                }

            }
            if (playerO_win != 0 || playerX_win != 0 || draw == 1)//break the second loop
                break;
        }
        if (playerO_win == 1 && playerX_win == 0) {// when the player win print the block game again and print out the win statement
            print_table(R);
            cout << "player O wins!" << endl;
            break;
        }
        else if (playerX_win == 1 && playerO_win == 0) {//the other player win the game
            print_table(R);
            cout << "player X wins!" << endl;
            break;
        }
        else if (draw == 1) {//the draw block game print
            print_table(R);
            cout << "Draw game!" << endl;
            break;
        }
        player = check_player(player);

    } while (1);//in fact it is no need for the loop statement, because most of the situation will have a break statement for out of the loop
    return 0;
}



Process terminated with status -1073741819 in C++

My code works properly around 90% of the time, but randomly it'll crash with the following error. I've no idea what my issue is considering it works mostly. The goal is to create a square with randomly created dimensions from 0-9 in both width and height; each 'block' of the square contains another randomly generated number. Thanks for the help!

Following section of code:

 srand(time(NULL));
  int arrayX = rand() % 9;
  int arrayY = rand() % 9;
  int arrayShape[arrayX][arrayY];
  cout << "Shape Length: "   << arrayX << endl << "Shape Height: " <<  arrayY << endl;

  int i;
  int j;
  for (i = 0; i < arrayY; i++)
  {
    for (j = 0; j < arrayX; j++)
    {
      arrayShape[i][j] = rand() % 9;
      cout <<  arrayShape[i][j];

      if (j == arrayX - 1) {
        cout << endl;
      }


    }
  }



How to use Counters to generate a random number ranging 2 to 12 using VHDL

I was going through Digital Systems Design Using VHDL (Second Edition) by Charles H. Roth, Jr. and Lizy Kurian John where I came across Section 5.2.2 A Dice Game. In order to understand it better I tried implementing the codes given.

I was able to successfully implement the first part of the problem wherein the Dice Sum have been hardcoded like this:

type arr is array(0 to 11) of integer;
constant Sumarray:arr := (4, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12);

Here is the complete implementation:

design.vhd

--Behavioral Model for Dice Game
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL;

entity DiceGame is
port(Rb, Reset, CLK: in bit;
     Sum: in integer range 2 to 12;
     Roll, Win, Lose: out bit);
end DiceGame;

architecture DiceBehave of DiceGame is

signal State, Nextstate: integer range 0 to 5;
signal Point: integer range 2 to 12;
signal Sp: bit;

begin
process(Rb, Reset, Sum, State)
begin
    Sp <= '0'; Roll <= '0'; Win <= '0'; Lose <= '0';
    case State is
    when 0 => if Rb = '1' then Nextstate <= 1; end if;
    when 1 =>
        if Rb = '1' then Roll <= '1';
        elsif Sum = 7 or Sum = 11 then Nextstate <= 2;
        elsif Sum = 2 or Sum = 3 or Sum = 12 then Nextstate <= 3;
        else Sp <= '1'; Nextstate <= 4;
        end if;
    when 2 => Win <= '1';
        if Reset = '1' then Nextstate <= 0; end if;
    when 3 => Lose <= '1';
        if Reset = '1' then Nextstate <= 0; end if;
    when 4 => if Rb = '1' then Nextstate <= 5; end if;
    when 5 =>
        if Rb = '1' then Roll <= '1';
        elsif Sum = Point then Nextstate <= 2;
        elsif Sum = 7 then Nextstate <= 3;
        else Nextstate <= 4;
        end if;
    end case;
end process;

process(CLK)
begin
    if CLK'event and CLK = '1' then
        State <= Nextstate;
    if Sp = '1' then Point <= Sum; end if;
    end if;
end process;

end DiceBehave;

--Test Module

entity GameTest is
port(Rb, Reset: out bit;
     Sum: out integer range 2 to 12;
     CLK: inout bit;
     Roll, Win, Lose: in bit);
end GameTest;

architecture dicetest of GameTest is

signal Tstate, Tnext: integer range 0 to 3;
signal Trig1: bit;
type arr is array(0 to 11) of integer;
constant Sumarray:arr := (4, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12);

begin

CLK <= not CLK after 20 ns;

    process(Roll, Win, Lose, Tstate)
    variable i: natural; -- i is initialized to 0
    begin
        case Tstate is
            when 0 => Rb <= '1'; -- wait for Roll
                Reset <= '0';
                if i >= 12 then Tnext <= 3;
                elsif Roll = '1' then
                Sum <= Sumarray(i);
                i := i + 1;
                Tnext <= 1;
                end if;
            when 1 => Rb <= '0'; Tnext <= 2;
            when 2 => Tnext <= 0;
                Trig1 <= not Trig1; -- toggle Trig1
                if (Win or Lose) = '1' then
                    Reset <= '1';
                end if;
            when 3 => null; -- Stop state
        end case;
    end process;

    process(CLK)
    begin
        if CLK = '1' and CLK'event then
            Tstate <= Tnext;
        end if;
    end process;

end dicetest;

testbench.vhd

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL;

entity tester is
end tester;

architecture test of tester is

component GameTest
port(Rb, Reset: out bit;
     Sum: out integer range 2 to 12;
     CLK: inout bit;
     Roll, Win, Lose: in bit);
end component;

component DiceGame
port(Rb, Reset, CLK: in bit;
     Sum: in integer range 2 to 12;
     Roll, Win, Lose: out bit);
end component;

signal rb1, reset1, clk1, roll1, win1, lose1: bit;
signal sum1: integer range 2 to 12;

begin

Dice: Dicegame port map (rb1, reset1, clk1, sum1, roll1, win1, lose1);
Dicetest: GameTest port map (rb1, reset1, sum1, clk1, roll1, win1, lose1);

end test;

The second part of the problem requires generating the Dice Sum using Counters. Here is the code snippet provided in the book.

Code - 1

entity Counter is
port(Clk, Roll: in bit;
     Sum: out integer range 2 to 12);
end Counter;

architecture Count of Counter is

signal Cnt1, Cnt2: integer range 1 to 6:= 1;

begin
process(Clk)
begin
    if Clk = '1' then
        if Roll = '1' then
            if Cnt1 = 6 then Cnt1 <= 1; else Cnt1 <= Cnt1 + 1; end if;
            if Cnt1 = 6 then
                if Cnt2 = 6 then Cnt2 <= 1; else Cnt2 <= Cnt2 + 1; end if;
            end if;
        end if;
     end if;
end process;

Sum <= Cnt1 + Cnt2;

end Count;

Code - 2

entity Game is
port(Rb, Reset, Clk: in bit;
     Win, Lose: out bit);
end Game;

architecture Play1 of Game is
component Counter
port(Clk, Roll: in bit;
    Sum: out integer range 2 to 12);
end component;

component DiceGame
port(Rb, Reset, CLK: in bit;
     Sum: in integer range 2 to 12;
     Roll, Win, Lose: out bit);
end component;

signal roll1: bit;
signal sum1: integer range 2 to 12;

begin
Dice: Dicegame port map (Rb, Reset, Clk, sum1, roll1, Win, Lose);
Count: Counter port map (Clk, roll1, sum1);
end Play1;

I understand that Code-1 describes the working of Counter. But I am unable to figure out how to incorporate Code-2 in design.vhd and what necessary changes need to be made in test module of design.vhd

If anyone can guide me it would be really helpful. Thanks in advance.




What am I doing wrong? Password generator in Python using Tkinter and random

I started making a simple password generator in Python 3.8.1 using Tkinter and random, but I have a problem. I want to add checkboxes (in Tkinter: checkbuttons) but something is wrong. In the checkboxes, it would be possible to select the elements from which the password is generated. It is done in such a way that when you select a checkbox, a given pool of characters, e.g. letters or numbers, are added to the list of characters from which the password is generated. The problem is that when you uncheck the checkbox, the items are not removed from the character list and the password is still generated using the previous parameters.

import random
from tkinter import *
from tkinter import messagebox
import clipboard

# Define window
app = Tk()
app.geometry("305x155")
app.title("Password Generator")
# Items used to generate password
uppercase_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase_letters = "abcdefghijklmnopqrstuvwxyz"
digits = "0123456789"
# From which items you want to generate password
upper = BooleanVar()
lower = BooleanVar()
nums = BooleanVar()

everything = ""

def check_1():
    global upper, lower, nums
    global everything
    # Add items what you want to everything variable
    if upper.get() == True:
        everything += uppercase_letters
    if upper.get() == False:
        everything.replace("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "")
def check_2():
    global upper, lower, nums
    global everything
    if lower.get() == True:
        everything += lowercase_letters
    if lower.get() == False:
        everything.replace("abcdefghijklmnopqrstuvwxyz", "")
def check_3():
    global upper, lower, nums
    global everything
    if nums.get() == True:
        everything += digits
    if nums.get() == False:
        everything.replace("0123456789", "")

CheckboxLabel_1 = Label(app, text="Big Letters")
CheckboxLabel_1.grid(row=2, column=5)

CheckboxLabel_2 = Label(app, text="Low Letters")
CheckboxLabel_2.grid(row=3, column=5)

CheckboxLabel_3 = Label(app, text="Numbers")
CheckboxLabel_3.grid(row=4, column=5)

Checkbox_1 = Checkbutton(app, text="", variable=upper, onvalue = True, offvalue= False, command=check_1)
Checkbox_1.grid(row=2, column=6)

Checkbox_2 = Checkbutton(app, text="", variable=lower, onvalue = True, offvalue= False, command=check_2)
Checkbox_2.grid(row=3, column=6)

Checkbox_3 = Checkbutton(app, text="", variable=nums, onvalue = True, offvalue= False, command=check_3)
Checkbox_3.grid(row=4, column=6)

LengthText = Label(app, text="Length: ")
LengthText.grid(row=0, column=5)

Space = Label(app, text="")
Space.grid(row=0, column=4)

length = Entry(app, width=4) # Length of your password
length.insert(0, "20") # Default length (max. 62)
length.grid(row=0, column=6)

AmountText = Label(app, text="Amount: ")
AmountText.grid(row=1, column=5)

amount = Entry(app, width=4) # Amount of generated passwords
amount.insert(0, "1") # Default amount
amount.grid(row=1, column=6)

Generated = Label(app, text="Generated password:") 
Generated.grid(row=0, column=1)

Space_1 = Label(app, text="")
Space_1.grid(row=1, column=0)

PasswordText = Entry(app, width=25) # Text box
PasswordText.grid(row=1, column=1)

# Generating password function
def generate_password():
    PasswordText.delete(0, END) # Clear text box before writing a new password
    for x in range(int(amount.get())):
        password = "".join(random.sample(everything, int(length.get())))
        PasswordText.insert(0, password) # Past password into text box
    Completed = Label(app, text="Password generated.", fg="green") # Show info
    Completed.grid(row=3, column=1)

Submit = Button(app, text="Generate", command=generate_password) # Generating button
Submit.grid(row=2, column=1)

# Copying password to clipboard
def copytoclipboard():
    clipboard.copy(PasswordText.get())
    messagebox.showinfo(title="Info", message="Password copied to clipboard.")
    
Copy = Button(app, text="Copy", command=copytoclipboard) # Copying button
Copy.grid(row=1, column=3)

app.mainloop()

I used replace() to delete elements from everything variable because it's impossible to subtract strings.

Numbers and Big Letters checkboxes are unchecked, but the program still uses them to generate passwords (photo)




Fail to understand the output of numpy.random.RandomState()

When I do the following in Python:

>>> import numpy
>>> numpy.random.RandomState()

it returns RandomState(MT19937) at 0x2BABD069FBA0. I understand the first part of the output, but I fail to understand the meaning of the hexadecimal part. It doesn't seem to be the random seed as well. I tried to check online but couldn't find any information on this. Please may I ask if anyone understands the meaning of the hexadecimal number? Many thanks!




Probability of random draw from non-standard normal (Python)

I have a vector of random draws that I obtained with np.random.normal(0,std_vector) where std_vector is a vector of length N with different standard deviations in each entry. I need to find the "probability of each random draw". This is a very unclear expression unfortunately, but I thought it means I need to back out the probability of drawing a specific value from the probability density function (pdf) with parameters loc=0 and std=std_vector. How can I obtain such infomation with Python? Also, what do you think is meant for "probability of each random draw"? That probability should become the weights in the calculation of a probability-weighted average, hence they should be between zero and 1. I am a bit confused about that, hence any suggestion is welcomed.




New in r and struggling with the question below

question 1) Suppose X is a continuous r.v. with pdf: f(x)=4x^2, −6<x<1.

  1. Plot the pdf of X and verify that f(x) is a pdf

2 Find Pr(X<-15 | X>−21)




How to generate same random arrays while using np.random.normal()

X_p=np.random.normal(0,0.05,size=(100,2))
X_n=np.random.normal(0.13,0.02,size=(50,2))
plt.scatter(X_p[:,0],X_p[:,1])
plt.scatter(X_n[:,0],X_n[:,1],color='red')
plt.show()

this code generates different plot everytime we run it. Can someone tell me is there a way to generate same data always with given std and mean

enter image description here




Fill an array with random numbers in correct way with sum of every four equals or higher than two

I need some help or hint. There is a code:

public class RandomInArray {
    public static void main(String[] args) {
        Random random = new Random();
        int[] array = random.ints(8, 0, 2).toArray();
        System.out.println(Arrays.toString(array));
    }
}

example: [1,0,1,0,0,1,0,1]

The Sum of every 4 numbers in an array has to be a minimum of 2. example: [1,0,1,0,0,1,0,1] From first 1+0+1+0 is correct, the sum is >=2. than: 0,1,0,0, the sum is 1. Incorrect. 1,0,0,1, the sum is 2. Correct. 0,1,0,1, the sum is 2. Correct. How to extend method to print out every time correct random mix of elements in array? There are correct examples with 8 elements. If ex. 20 elements, less or more, the result should be the same. Correct examples:

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



mardi 24 novembre 2020

How to generate a number that hasn't been generated yet? [duplicate]

So I'm writing a code in C++ that reads a certain amount of lines from a text file and randomly gives me the contents of five random ones. However there's times where the same line is repeated in the same sequence. Is there a way to not repeat the same line within a sequence?




How to generate a random numpy array, but with a certain criterion, for example that each element is greater than the previous one?

I was wondering if there's a neat way to generate a random array in Python (naturally, using numpy) with a certain given structure, for instance an array of random ints where each element in the array is greater than the previous one: For instance, a and b would satisfy the criterion, but c wouldn't:

a = [1, 2, 3, 4, 5, 6, 7, 8]
b = [10, 22, 57, 154]
c = [5, 12, 75, 44, 66]

Similarly, is there a systematic way to set any similar sort of criteria, for instance to have a random array where the elements first increase and then, after a certain point, they start to decrease. Or would these situations require different approach every time?

Thanks!




Fastest way to generate long strings in JavaScript (performance)

There are lot of random string questions on stack exchange, but they do not help me with my problem. I need to generate a lot of random (no need to be true random) long strings (256 chars) in JavaScript as fastest as possible. It doesn't need to be one-line function, performance is the only thing that matters. Can someone help me with this?




How to use O(log n) mutually independent random bits to generate n pairwise independent random bits

We motivated this problem by “saving space”, yet then, we went ahead and stored n pairwise independent random bits ξi . That pretty much defeats the purpose. Show how to use O(log n) mutually independent random bits to generate n pairwise independent random bits. (Thus, all you really need to store are those O(log n) bits.)




Randomly assing to condition on equal proportions R

I have the following database (as an example)

participants <- c(1:60)
codes <- c(1:60)
database <-cbind(participants, codes)

The second variable codes contains emails linked to each participant ID, although for example proposes I just filled it with numbers. I have 60 participants each one with a participant ID and an email tied to this ID (a number from 1 to 60). As such in the example row 1 is 1 ,1 and so on. I need to divide the list on 3 groups of identical proportion, eg 20 participants per group. The way I am doing it now is

#generating list of participants
participants <- c(1:60)
codes <- c(1:60)
database <-cbind(participants, codes)

#randomizing the order of the list
randomized_list <- sample(participants)

#Extracting the three groups 

group1 <- randomized_list[c(1:20)]
group2 <- randomized_list[c(21:40)]
group3 <- randomized_list[c(41:60)]

Leaving me to do the work of getting the email addresses and dividing the lists more or less by hand (compare group 1, 2 and 3 with database and making the link).

Is there a more elegant and compact solution for achieving the results I seek?




Dynamically allocate and initialize new object with 30% probability

I'm writing a program that will simulate a randomized race between runners who are climbing up a mountain where dwarf orcs (dorcs) are coming down the mountain to attack the runners. It begins with two runners named harold and timmy at the bottom of the mountain. The runners make their way up the mountain in randomized moves where they may make progress forward up the mountain, or they may slide back down the mountain. Dorcs are randomly generated, and they inflict damage on a runner if they collide. The simulation ends when one of the runners reaches the top of the mountain, or when both runners are dead.

I'm struggling with a part where I have to implement the actual race loop. Once the race is initialized, the race loop will iterate until the race is over. This happens when either a winner has been declared, or when all runners are dead.

Every iteration of the race loop will do the following:

with 30% probability, dynamically allocate a new dorc as an EntityType structure, and initialize it as follows:

(a) a dorc’s avatar is always “d”

(b) each dorc begins the race at the top of the mountain, which is at row 2

(c) with equal probability, the dorc may be placed either in the same column as timmy, or in the same column as the harold, or in the column exactly half-way between the two

(d) add the new dorc to the race’s array of dorcs

(e) using the pthread_create() function, create a thread for the new dorc, and save the thread pointer in the dorc’s entity structure; the function that each dorc thread will execute is the void* goDorc(void*) function that you will implement in a later step; the parameter to the goDorc() function will be the EntityType pointer that corresponds to that dorc

I guess I'm confused with the logic of how to approach this. I decided to make a function called isOver() to indicate if the race is over, and then a separate function called addDorc() to initialize the Dorc elements and do all the requirements above.

In isOver(), I attempt to add a dorc object to the dorcs array by doing addDorc(race); with every iteration of the race loop/if the race hasn't ended or no one died. But I keep getting the error:

control.c:82:3: error: too few arguments to function ‘addDorc’
   addDorc(race);

The problem is I don't think I can manually declare all the parameters in addDorc() because some elements like the "path" argument are based on probability. As mentioned above, with equal probability, the dorc may be placed either in the same column as timmy, or in the same column as the harold, or in the column exactly half-way between the two. The issue is I don't know how to factor this random value when calling addDorc() and would appreciate some help. I also don't know if I'm doing the "with 30% probability, dynamically allocate a new dorc as an EntityType structure" correctly and would be grateful for some input on that as well.

defs.h

typedef struct {
  pthread_t thr;
  char avatar[MAX_STR];
  int  currPos; 
  int  path; 
} EntityType;

typedef struct {
  EntityType ent;
  char name[MAX_STR];
  int  health;
  int  dead; 
} RunnerType;

typedef struct {
  int numRunners;
  RunnerType *runners[MAX_RUNNERS];  
  int numDorcs;
  EntityType *dorcs[MAX_DORCS]; 
  char winner[MAX_STR]; 
  int  statusRow; 
  sem_t mutex;
} RaceInfoType;

void launch();
int addDorc(RaceInfoType*, char*, int, int);
int isOver(RaceInfoType*);
void initRunners(RaceInfoType*);
int addRunner(RaceInfoType*, char*, char*, int, int, int, int);

int  randm(int);

void *goRunner(void*);
void *goDorc(void*);

RaceInfoType *race;

control.c

void launch(){

    race = malloc(sizeof(RaceInfoType));
    race->numRunners = 0;
    
    initRunners(race);
    
    if (sem_init(&race->mutex, 0, 1) < 0) {
        printf("semaphore initialization error\n");
        exit(1);
    }
    
    strcpy(race->winner, " ");
    
    
    srand((unsigned)time(NULL));
    
    int i;
    for(i = 0; i < race->numRunners; ++i){
        pthread_create(&(race->runners[i]->ent.thr), NULL, goRunner, " ");
    }
    
    race->numDorcs = 0;
}



int addDorc(RaceInfoType* race, char *avatar, int path, int currPos){ 
    if(race->numDorcs == MAX_DORCS){ 
        printf("Error: Maximum dorcs already reached. \n");
        return 0;
    }       
    race->dorcs[race->numDorcs] = malloc(sizeof(EntityType));
    
    int timmysColumn = race->dorcs[race->numDorcs]->currPos;
    int haroldsColumn = race->dorcs[race->numDorcs]->currPos;
    int halfwayColumn = (timmysColumn+haroldsColumn)/2;
    
    int r = rand()%100;
    
    pthread_t dorc;
    
    if(r <= 30){
        strcpy(race->dorcs[race->numDorcs]->avatar, "d");
        race->dorcs[race->numDorcs]->currPos = 2;
        if(r <= 33){
            race->dorcs[race->numDorcs]->path = timmysColumn;
        }else if(r <= 66){
            race->dorcs[race->numDorcs]->path = haroldsColumn;
        }else{
            race->dorcs[race->numDorcs]->path = halfwayColumn;
        }
        pthread_create(&dorc, NULL, goDorc, " ");
    }
    race->numRunners++;
}

int isOver(RaceInfoType* race){ 
    int i;
    for(i = 0; i < race->numRunners; ++i){
        if((race->winner != " ") || (race->runners[race->numRunners]->dead = 1)){
            return 1;
        }
        addDorc(race);
        return 0;
    }
}
void initRunners(RaceInfoType* r){
    addRunner(r, "Timmy", "T", 10, 35, 50, 0); 
    addRunner(r, "Harold", "H", 14, 35, 50, 0); 
}


int addRunner(RaceInfoType* race, char *name, char *avatar, int path, int currPos, int health, int dead){
    if(race->numRunners == MAX_RUNNERS){ 
        printf("Error: Maximum runners already reached. \n");
        return 0;
    }       
    race->runners[race->numRunners] = malloc(sizeof(RunnerType));
    strcpy(race->runners[race->numRunners]->name, name);
    strcpy(race->runners[race->numRunners]->ent.avatar, avatar);
    race->runners[race->numRunners]->ent.path = path;
    race->runners[race->numRunners]->ent.currPos = currPos;
    race->runners[race->numRunners]->health = health;
    race->runners[race->numRunners]->dead = dead;
    race->numRunners++;
    return 1;
}



Change message with a random system (Discord.js)

I'm making a bot for discord (using discord.js), and I tried to make a system that says "It's me Mario" when you say "; its-me", and a small chance to send only "It's me" and with a photo of "Golden Freddy" (FNAF), I wanted to make the message "bug" and as I said earlier the photo of Golden Freddy appears. It worked at first, but it didn't bug the text. How do I solve this? Sorry if I wrote something wrong I am using google translator

Code:

const Discord = require('discord.js')

module.exports = { name: "its-me", description: "Mario meme",

async run (client, message, args) {

    var list = [
       //? 
    ]

    var rand = list[Math.floor(Math.random() * list.length)];

    const mario = new Discord.MessageEmbed()
    .setTitle(`It's me!`)
    .setImage('https://vignette.wikia.nocookie.net/mario-bros/images/7/75/Mario.png/revision/latest/scale-to-width-down/340?cb=20131012013704&path-prefix=pt-br')
    .setColor("RED");

    const golden = new Discord.MessageEmbed()
    .setTitle(`ıɬ'ʂm̸̩̙̖̝̣̻̈́̈̃̀͑̂̾͝e̸̼̪͂̈́̀̇̈́̕  !`)
    .setImage(`https://i.pinimg.com/originals/43/e2/7a/43e27a96c3d58e32907ded73134c2faf.png`)
    .setColor('#B8860B')

    message.channel.send(rand)
}

}