dimanche 31 mai 2020

How can a mersenne_twister_engine be serialized using Boost?

I have a class that implements std::mt19937 and I would like to be able to save and load the state of the random number generator for consistency. I'm aware that the << and >> operators can be used to save/load the engine's state and that I can separate the save and load functions when I archive the file if necessary. My guess at how to do this would be to use the << and >> operators to store the state into/extract the state from an object that can be serialized. My questions are

  1. What object can be used to store the state of the mersenne_twister_engine that can also be serialized using Boost?
  2. Is my approach safe and generally considered to be good practice?
  3. Is there an approach to this that is generally considered to be better?



Generate different object with same attributes

I am building a project. One of the requirements is to generate the object with the same attributes but randomly different values. I tried to use deep-copy, but not sure if it is conceptually correct.

  1. So, for example, I have a Person class, inherited from the abstract class Character.
  2. And there is a ScenarioGenerator, which I'll put the getRandomPerson method to create the instances of the Person class.

Any help of advice is highly appreciated.

Here is part of my Person class:

public class Person extends Character {
private Random random;

private boolean pregnant;
private boolean isYou;

Person(int age, Profession profession ,Gender gender, BodyType bodyType, boolean isPregnant) {
    super(age, gender, bodyType);//pass the attributes to the super class called Character
}

Person (Person otherPerson) { //copy constructor

    this.age = otherPerson.getAge();
    this.gender = otherPerson.getGender();
    this.bodyType = otherPerson.getBodyType();
}
public Profession getProfession () { // One of the getters which generate random enum value
    //only adults have profession
    if (getAge()<=16 || getAge()>68) {
        return Profession.NONE;
    } else {
        return Profession.values()[new Random().nextInt(Profession.values().length)];
    }
}
// setters and getters
}

And the method of my ScernarioGenerator class:

public class ScenarioGenerator {
    public Person getRandomPerson() {
    //need age, gender, bodyType, profession, pregnancy
    Person people = new Person(person.getAge(), person.getProfession(), person.getGender(), person.getBodyType(), person.isPregnant());
    Person clone = new Person(people);
    return clone;
}



Python choices; Having a variable value for number of times the choice can be carried out

I'm attempting to keep getting random choices until the condition in the if block is met(i.e when three consecutive choices return the same result). The challenge is that I don't know how to set the choice to continue until the condition is met because it seems k must be specified. Thus, I cannot have a variable value for k which is determined by when the condition is met.


#import random module
import random

# initiate x which would contain predictions
x = 0

#define prediction; which would continue until 3 consecutive predictions get same outcome
while True:
   x = (random.choices(['H','T'], k = 10 ))
   print(x)
   if x[-3:] == ['H','H','H'] or x[-3:] == ['T','T','T']:
      break




What is the behavior of calling np.random.multinomial many times?

When called, np.random.multinomial and other sampling functions give a certain number of independent samples from the chosen probability distribution. For instance,

np.random.multinomial(20, [1/6.]*6, size=2)

represents throwing a die 20 times, and then 20 times again.

However, what happens if you call np.random.multinomial(1, [1/6.]*6, size=1) a thousand times in succession? Will I get a thousand independent die rolls, i.e. does np.random.multinomial guarantee independent samples and correct distributions between successive calls? Empirically, it looks like there is some significant correlation between calls. Is it better to reset np.random.RandomState before every call? This seems wrong somehow.




Randomised Queue implementation - ideas for randomness

I am taking the Algorithms course in coursera. One of the assignments is the following:

Randomized queue. A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random among items in the data structure.

I am trying to find a way to implement dequeue (randomly removing an item) in a constant amount of time. I have thought of an idea to do this recquiring a deque (which supports removing and adding an item from the front and back in constant time). My idea is as follows:

  • Use a deque as an underlying data structure inside the randomized queue
  • Enqueue - use a library function to generate an integer between 0 and 1 inclusive. If the integer is 0, add the item to the front of the deque. Otherwise, add it to the back.
  • Dequeue - any direction would be fine.

The reason why the randomness happens in enqueue rather than in dequeue is because I find it to be not exactly random (E.G. n calls to enqueue will have dequeue only return either the first or nth item). So to be sure the items are being removed randomly, I decided to enqueue them randomly.

This idea seems good to me because I cannot find holes in it, but the problem is I cannot prove that my idea would really work. I don't know much about randomness. In fact, this is only the 5th time I am working with random data structures.

Is my idea correct? Will it generate a data structure that removes items at random?




Octave: Filling specific values in random cells inside a table

I am trying to fill some values in a table (1 row n columns). 1 and 0 must be inside the table but in random positions and the remaining cells have to be random values between 0 and 1.

e.g for n=4 P should look something like this

P = 0.0000 0.58177 1.00000 0.86008

What I have done is: filling the first two positions inside the table with 1 and 0 and the rest of n (if n>2) is filled with randomized values [0,1]. Any ideas how to fix my code are welcome.

function P=pairwise_matrix(n)

P=zeros(1,n);

 a = 0; b = 1;
 x = a + (b-a) .* rand(1,1);



  P(1,1)=1

  if (n==1)
    printf("not applicable")
  endif

  if (n==2)
    P(1,1)=0
    P(1,2)=1
  endif


  for (i=3:n)
        P(1,i)=rand(x);
  endfor




endfunction



What is the difference between random.choice() and random.choices()?

What is the difference between random.choice() and random.choices() in python?




C# problem with Random number in several lists [duplicate]

I was "fighting" with Random generator through some time in multi thread app on forms and I realize that Random isn't "thread safe".

Either way I need to use it in my app while I create an object of "Seller". Each Seller got his own stock with the same phones, but different price and amount.

Firstly I was trying to generate random amounts in stock when I started job of thread, but it returns me the same values in all stocks(I use Json to store data).

Then I decided to parse json data in Seller constructor and generate Random stock while creating an instance of this object. When I decided to create for example 5 objects, only in 1st stock values was different - in the rest 4 was the same.

Is any chance to solve it?

This is my Seller class:

 class Seller
    {
        private int ID;

        public List<Phone> Stock;
        private Phone phone;
        public int SellerCounter = 0;

        public Seller(int ID)
        {
            this.ID = ID;
            this.Stock = new List<Phone>();
            LoadJson();
            randomStock(this.Stock);
            string phonesJson = JsonConvert.SerializeObject(this.Stock);
            createStockFile(phonesJson);
            this.SellerCounter++;
        }

        public int getID()
        {
            return this.ID;
        }

        public void setID(int ID)
        {
            this.ID = ID;
        }

        public void LoadJson()
        {
            using (StreamReader r = new StreamReader("telefony.json"))
            {
                string json = r.ReadToEnd();
                this.Stock = JsonConvert.DeserializeObject<List<Phone>>(json);
            }
        }

        public void createStockFile(string phonesJson)
        {
            string fileName = "sellerStock" + this.getID()+".json";

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            File.WriteAllText(fileName, phonesJson);

        }

        public void randomStock(List<Phone> Stock)
        {

            double price = 0;

            double percent = 0;

            int amount = 0;

            Random random = new Random();

            foreach (Phone phone in Stock)
            {
                amount = random.Next(0, 15);

                price = phone.Get_OriginalPrice();

                percent = price * 0.1;

               if (random.Next(0, 2) == 0)
               {
                    price -= percent*0.1;
                    phone.Set_OriginalPrice(price);
               }
                else
                {
                    price += percent*0.1;
                    phone.Set_OriginalPrice(price);
                }
                phone.Set_SoldAmount(amount);
            }
        }

        public void setStock(List<Phone> phones)
        {
            foreach (Phone phone in phones)
            {
                this.Stock.Add(phone);
            }
        }

I know that I shouldn't do that in a constructor, but I need to find a solution...




Randomizer picks a number from the vector and delete it

So, program picks this number from the vector, it's actually a sequence {1...n} and I want to print out and delete random number from it. However, everytime program prints out {n...1} sequence. Example: Vector(1,2,3,4,5) => program picks random number 4 => Vector(1,2,3,5) => random number 1 => Vector(2,3,5) and until Vector(). So, program will print (4,1,...). In case of this program, it always prints out (5,4,3,2,1) for Vector(1,2,3,4,5).

int main()
{
    srand(time(NULL));
    rand();
    int toReturn;
    std::cout << "Enter the number of tickets: ";
    std::cin >> toReturn;
    std::cout << std::endl;
    std::vector<int> nums;


    for (int i = 1; i <= toReturn; ++i)
    {
        nums.push_back(i);
    }

    int choice=0;
    bool checked=0;
    while (nums.size() > 0)
    {
        bool inVector=0;
        choice = rand() % toReturn + 1;

        while(inVector == 0)
        {
            choice = rand() % toReturn + 1;

            for (int i = 0; i < nums.size(); ++i)
            {
                if (choice == nums[i])
                {
                    inVector = 1;
                }
                else
                {
                     inVector = 0;
                }
            }
        }
        std::cout << "Why not check the ticket " << choice << std::endl;
        std::cout << "Did u do it right?" << std::endl;
        std::cin >> checked;
        if (checked)
        {
            nums.erase(std::remove(nums.begin(), nums.end(), choice), nums.end());
        } 

        else
        {
             continue;
        }
    }
    if (nums.size() == 0)
    {
        std::cout << "You checked all tickets!!!";
    }
    return 0;
}

I would be glad if you leave any suggestion to code refactoring




Generating numbers from given mean, median, SD, maximum and minimum values using R

I have a list of temperature data which shows mean, median, SD, maximum , minimum and IQR of temperatures for different months. I wanted to generate a set of numbers using the above given values. is it possible in R ?

The smaple data :

a <- tribble( ~"Month",~"year", ~"mean", ~"SD", ~"Min", ~"Q1", ~"Med", ~"Q3", ~"Max", "July", 2018, 1.13, 0.07, 0.98, 1.09, 1.13, 1.18, 1.27, "August", 2018, 1.16, 0.08, 1.04, 1.10, 1.16, 1.22 ,1.39, "September", 2018, 1.08, 0.08, 0.97, 1.00, 1.08, 1.12, 1.29, "October", 2018, 1.16, 0.11, 0.94, 1.07, 1.16, 1.23, 1.42, "November", 2018, 1.48, 0.25, 1.02, 1.34, 1.48, 1.60, 1.93, "December", 2018, 1.82, 0.17,1.52, 1.69, 1.82, 1.92, 2.20, "January", 2019, 1.91, 0.19, 1.56, 1.76, 1.89, 2.02, 2.26, "February", 2019, 1.59, 0.17, 1.33, 1.44, 1.59, 1.77, 1.90, "March", 2019, 1.35, 0.18, 1.10, 1.20, 1.33, 1.45, 1.67, "April", 2019, 1.34, 0.10, 1.16, 1.27, 1.34, 1.41, 1.47, "May", 2019 ,1.31, 0.07, 1.14, 1.24, 1.31, 1.35, 1.43, "June", 2019, 1.31, 0.06, 1.19, 1.26, 1.31, 1.35,1.43 )

what i actually want is some boxplot like this as an output from it : -fg




Apply one of five colours randomly to series of links [duplicate]

I have a large number of links with the class folioLink i'm trying to use JS to pick one of five pre-determined colours and randomly apply across all the links. i.e. so each link with this class will have one of these colours randomly assigned.

So far I have:

  var colors = ['skyblue', 'mediumseagreen', 'orange', 'lightcoral', 'lightcoral','red'];
$('.folioLink').css('color', function(index) {
  return colors[index % colors.length];
});

Which is assigning the colours - but only in this sequence which then repeats. What can I add here to apply the colours at random? Thanks!




Generating numbers from given mean, median, SD, maximum and minimum values using R

I have a list of temperature data which shows mean, median, SD, maximum , minimum and IQR of temperatures for different months. I wanted to generate a set of numbers using the above given values. is it possible in R ?




samedi 30 mai 2020

pick a random image from unsplash API reactjs

I am developing a reactjs application which uses unsplash API to update background images of the application. The result from the API is as below:

{total: 2330, total_pages: 78, results: Array(30)}

As the API gives back 30 images only per page, I have implemented the following logic to retrieve any random image from the list of 30 images:

        if (typeof response.data !== "undefined") {
          const num = Math.floor(Math.random() * 30) + 1;
          const url = response.data.results[num].urls.regular;
          updateBackground(url);
        }

But the above logic is limited to picking up a random image from the first page only. How do I pick a random image from the total of 2330 images ? Is there a way to exclude total_pages from the result ?

Thanks




Can't figure out why this conditional statement is only executing once. Perhaps rand()?

Can't figure this out. To begin, I'm calling srand(time(NULL)); in main. Working on implementing the game snake and I'm having trouble getting the apple to randomly appear in another part of the game map. When the snakehead equals the apple (using x, y coordinates), the statement that I've indicated below should execute. It works the first time, but (through testing with various print statements) seems to only be executed once. The initial apple position is hardcoded and thus not set by the (rand() % 18) + 1. It seems to not work when the new coordinates for the apple are set by rand(). Can't figure out why.

void SnakeGame::main_loop()
{
     while (keyboard_input != 113) // q to quit 
    {
        usleep(0.2 * 1000000);
        keyboard_input = wgetch(snake_window);
        this->input_handler();

        if (snake_direction == UP)          { yPos--; }
        else if (snake_direction == DOWN)   { yPos++; } 
        else if (snake_direction == LEFT)   { xPos--; } 
        else if (snake_direction == RIGHT)  { xPos++; } 
        this->snake->move(xPos, yPos);

        if (xPos == xApple && yPos == yApple) // <--- THIS STATEMENT
        {   
            this->getNextApple();
            this->incrementScore();
        }
        draw_field();
    }
}

void SnakeGame::getNextApple()
{
    int xNew;
    int yNew;
    while (1)
    {
        xNew = (rand() % 18) + 1;
        yNew = (rand() % 18) + 1;
        if ( (xNew != this->xPos && yNew != this->yPos) && (this->snake->is_snake(xNew, yNew) == false) )
        {
            break;
        }
    }
    this->xApple = xNew;
    this->yApple = yNew;
}

Been trying to figure this out all day. Any thoughts would be welcome.




TypeError: can only concatenate str (not "int") to str: What does it mean?

from tkinter import*
import random
from tkinter import messagebox
window=Tk()
window.title("Random Tools")
window.configure(background="light green")
textvaria = IntVar()
textvaria2 = IntVar()

label0 = Label(window, text = "Min", bg ="light green")
label0.grid(row=1, column=0)

spinboxmin = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria)
spinboxmin.grid(row=2, column=0)
a = spinboxmin.get()

label1 = Label(window, text="Max", bg="light green")
label1.grid(row=3, column=0)

spinboxmax = Spinbox(window, from_=1, to=9999, increment=1, textvariable=textvaria2)
spinboxmax.grid(row = 4, column =0)
b = spinboxmax.get()

def submit2():
    if a <= b:
        answertext.delete('1.0', END)
    else:
        messagebox.showerror("Error", "Max must be greater than min!")

submit = Button(text="Submit", command=submit2)
submit.grid(row=4, column=2)

n = random.randint(a, b+1)

answertext = Text(text=n)
answertext.grid(row=5, column=0)


window.mainloop()

I'm doing a GUI for randoming numbers. But when I run this in Python Module, it said: "TypeError: can only concatenate str (not "int") to str" Can someone help me with this? Thank a lot.




Use R to Randomly Assign of Participants to Treatments on a Daily Basis

The Problem:

I am attempting to use R to generate a random study design where half of the participants are randomly assigned to "Treatement 1" and the other half are assigned to "Treatment 2". However, because half of the subjects are male and half are female and I also want to ensure that an equal number of males and females are exposed to each treatment, half of the males and females should be assigned to "Treatment 1" and the remaining half should be assigned to "Treatment 2".

There are two complications to this design: (1) This is a yearlong study and the assignment of participants to treatment must occur on a daily basis; and (2) Each participant must be exposed to "Treatment 1" a minimum 10 times in a 28 day period.

Is this even possible to automate this in the R interface? I assume so, but I think my beginner status as an R programmer prohibits me from finding the solution on my own. I have been struggling for days to figure out how to actualize this, and have looked through many similar-sounding posts on this site that were not able to be successfully applied here. I am hoping someone out there knows some tricks that could help me get unstuck in solving this problem, any advice would be greatly appreciated!

What I Have Tried:

Specific Information

# There are 16 participants
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

# Half are male and half are female
g <- c(rep("M", 8), rep("F", 8))

# I make a dataframe but this may not be necessary
df <- cbind.data.frame(p,g)

# There are 365 days in one year
d <- seq(1,365,1)

...unfortunately, I am not sure how to proceed from here.

Ideal Outcome:

I am envisioning something approximate to this table as the outcome: I do not have enough reputation points to embed images yet so here is the link, sorry!

Basically there is a column for each participant and a row for each day. Associated with each day is an assignment to either Treatment 1 (T1) or Treatment 2 (T2), with 4 of the 8 males and 4 of the 8 females being assigned to T1 and the remainder to T2. These treatments are reassigned every day for 1 year. Not depicted in this chart is the need for each participant to be exposed to T1 at least 10 times in a 28-day period. The table does not have to look like that if something else makes more sense!




Optimize shuffled array - do I need to go through the whole array?

I will try to explain my issue. I'm trying to create a chessengine in PHP (just for fun :-)) The integers in the code simply returns valid moves (for simplicity - in real code it's objects and movement pattern depending on which piece it's about)


I'm looking for a way to effectively search through an array. By effectively I mean as fast as possible. Look at my comment in code below "IS it possible to break out of loop without going through all 1000 values?" I hope the comments would try to explain what I want to achieve. I'm just looking for ideas to optimize below code, not full code :-)


//This is for demonstrating
//1000 values to go through
$moves_maybe_valid = [];
foreach(range(1,1000) as $nr) {
    $moves_maybe_valid[] = $nr;
}
shuffle($moves_maybe_valid);


//Go through possible values
$move_checked = [];
$nr=0;
foreach($moves_maybe_valid as $mmv) {
    $move_is_valid = check_move($mmv);

    //Check if not in checked array
    if ($move_is_valid === false && !in_array($mmv, $move_checked)) {

        //Add to checked move array
        $move_checked[] = $mmv;
    }

    //IS it possible to break out of loop without 
    //going through all 1000 values?

}


//for demonstration purpose only
//numbers (5,6) that returns true are unknown until an
//an actual check is done in this function
function check_move($nr) {
    if ($nr == 5 || $nr == 6) {
        return true;
    }
    return false;
}



Solving problem to generate custom number from inserted values with GUI in Python

Hello im having python learning project. I want to insert in GUI two numbers, which are defining range for program to generate random number from.

I am really having problems with calling function with press of the button. And constantly getting error ValueError: invalid literal for int() with base 10: '', when trying to convert string from entry in GUI to int and then inserting them into random.randint.

Thx for Help!

from tkinter import *
import random

root = Tk()
root.title("Generator custom random number")

#function that gets number from entry converts string to int and defines target number in stevilo
def function():
    string_answer1 = prvo_stevilo.get()
    int1 = int(string_answer1)
    string_answer2 = drugo_stevilo.get()
    int2 = int(string_answer2)
    stevilo = random.randint(int1, int2)


#Defining GUI
navodilo = Label(root, text="Choose custom lower and upper number to chose random number from", width=60)
navodilo2 = Label(root, text="From", width=20, borderwidth=3)
navodilo3 = Label(root, text="To", width=20, borderwidth=3)
prvo_stevilo = Entry(root, width=20, borderwidth=3)
drugo_stevilo = Entry(root, width=20, borderwidth=3)
gumb = Button(root, text="Generate number", width=17, height=2, command=function)
praznavrstica = Label(root, text="")
izpis = Label(root, text="Random number is: ", width=20)
izpis_stevila = Label(root, text="" + stevilo)

#Showcase of gui
navodilo.grid(row=0, column=0, columnspan=1)
navodilo2.grid(row=1, column=0, columnspan=1)
navodilo3.grid(row=3, column=0, columnspan=1)
prvo_stevilo.grid(row=2, column=0, columnspan=1)
drugo_stevilo.grid(row=4, column=0, columnspan=1)
praznavrstica.grid(row=5, column=0, columnspan=1)
gumb.grid(row=6, column=0, columnspan=1)
praznavrstica.grid(row=7, column=0, columnspan=1)
izpis.grid(row=8, column=0, columnspan=1)
izpis_stevila.grid(row=9, column=0, columnspan=1)


#Loop
root.mainloop()



Bruteforcing a 32-bit seed in PHP

I am trying to crack this code to see if i can predict the next random password that is generates:

function generateRandomPassword($sequence)
{
   // $sequence is abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 
   $string = "";
   do
   {
     $string .= substr(str_shuffle($sequence),0,1);
   }while(strlen($string) < 8);

   return $string;
}

I am trying to bruteforce the seed, here is my PHP script:

<?php

$time_start = microtime(true); 

for($i = 0;$i < 4294967296;++$i)
{
    mt_srand($i);
    $string = "";
    do {

        $string .= substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, 1);

    } while (\strlen($string) < 8);

    if($string == 'AXtPvOsX')
    {
        echo '<b>Seed Found: </b>' . $i;
        break;
    }
}

$time_end = microtime(true);

$execution_time = ($time_end - $time_start);
echo '<br><b>Total Execution Time:</b> '. number_format($execution_time,2). ' seconds';

Now, the thing is, i know PHP is not efficient when it comes to bruteforcing but it has been running now for 3 days and it's still going. I tried to replicate the str_shuffle() in C++ to make bruteforcing faster but I couldn't port the code to C++.

Can anybody tell me why does it take so long to go through all 2^32 possible values?




Generate number repeating python

Code:

import random
number1=random.randint(0,62)
print(number1)

I tried and the numbers repeated each other.

One condition: The numbers will be different.




java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20

Im doing a thing for a thing and I have to "Multiply each element in list2 by its element index number and place the value in array list1." and so my code is

public static void main(String[] args) {        
        int List1 []= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,};
        int List2 []= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; 
        int L1= 0;
        int L2= 0;

        for( L2=0 ;L2<List2.length;L2++) {
            List2[L2]= (int) (100*Math.random());
            System.out.print(" "+List2[L2]);
        }//end of list2 for loop

System.out.println("");

        for( L1 = 0;L1<List1.length;L1++)
        {
            List1[L1]= List2[L2]*L2;
            System.out.print(" "+List1[L1]);
        }//end of list1 for loop
)

and it throws this error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 20 out of bounds for length 20"




C# Generic method for random number generation

I see that there is a similar question for C++. Does anyone know why this method works when the method is non-generic, but as soon as I make it generic, the random number portion of code fails? Error: Cannot implicitly convert type int to 'T'. If I can't use generics, I will have to rewrite the same function over and over for each different length of array.

public void fillGenericArray<T>(T[] inputArray) where T : IComparable
        {
            var randomNumb1 = new Random();


            for (int i = 0; i < inputArray.Length - 1; i++)
            {
                Console.WriteLine($"{inputArray[i] = randomNumb1.Next(1, 501)},");
                Console.WriteLine($"{inputArray[i] = randomNumb1.Next(1, 501)},");
                // oneHundredArray.Size++;
                Console.WriteLine($"{Size}");
            }
        }



Dice rolling program with counter

I'm new to programming and I have a task that I can't figure out on my own.

The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input. After every roll the number of the die will show and the total so far. If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.

here is my code:

import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break



Python Key Generator with String dont work

import random


mod1 = "BOT"
mod2 = (random.randrange(1,9999))
mod3 = (random.randrange(1,9999))
mod4 = (random.randrange(1,9999))


key = mod1 + "-" + mod2 + "-" + mod3 + "-" + mod4
print(key)

When i run this i become the error: TypeError: can only concatenate str (not "int") to str

Can anyone Help me




Mongoose-random Doenst Show Properly

I am using mongoose-random: 'https://github.com/matomesc/mongoose-random' I want to show my articles in a random sequence. But findRandom() is not working.

My app.js

app.get('/', function (req, res) {
  var perPage = 5
  var page = req.query.query;
  Metin
  .findRandom()
  .skip((perPage * page) - perPage)
  .limit(perPage)
  .exec(function(err, metins) {
      Metin.count().exec(function(err, count) {
          if (err) return next(err)
          res.render('index', {
              current: page,
              pages: Math.ceil(count / perPage),
              metins: metins,
          })
      })
  })
});

Also in my model.js, I have implemented:

 var random = require('mongoose-random');
    .
    .
    .
    metinSchema.plugin(random);

I couldnt understand why it is not working. The problem is: It doesnt gives any error but at the same time it doesnt show my articles(metin).Just shows the page without my articles. When just use find({}) my articles are shown. I couldnt understand why it is not working?

Can you please help to me?




How to create random numbers a specific number of times?

How can i create a random number a specific numbers of time?

public class Feld  {
    public static void main(String[] args) {
        double k = (int)(Math.random()*1000001);
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0;i<n;i++){
            arr[i] = i;
        }
        boolean found = false;
        i=0;
        while (i < arr.length) {
            if (arr[i] == k) {
                found = true;
                break;
            }
            i++;
        }
        if (found) {
            i++;
            System.out.println(i);
        } 
        else {
            System.out.println((arr.length + 1));
        }
    }
}

My problem is, that if i put k into a loop to create it more than one time i'll get an error at:

if (arr[i] == k)



vendredi 29 mai 2020

Can I use a randomly generated number as a parameter to a method in Java?

So I'm very new to Java so this question might have a pretty simple answer. I'm trying to create a Magic8 ball program and I want the fortune to depend on the randomly generated number, but it's treated as a method and I'm not sure that a method can have another method as a parameter.

public int generator(){
    int num = rnd.nextInt(2) + 1;
return num;
}

That's my method to generate the random number, is there a way to use the product of this in another method?




How do I store an output of a function into an array in Kotlin

So for an assignment, I have to maker a program that generates 200 random numbers and then gets stored into the array and then called upon later. so I thought about storing the function in an array like this

    fun main() {
    var randomValues = arrayOf( List(200) { Random.nextInt(0, 100) })
    println(randomValues)
}

and that didn't work I get this output [Ljava.util.List;@533ddba. I'm not too accustomed to arrays so I'm not sure what to do. Sorry if this has been asked before.




How to formulate a random event and build a Machine Learning algorithm?

I am working on a problem and wanted to ask your ideas/suggestions. Let' suppose you have a vendor who over- supplies materials to you on and off. What I mean is that sometimes they provide enough materials sometimes they over-provide. It does not happen on a continuous basis and it is sporadic. And of course, you are being charged for this over-supply. You have enough data to work with over a 2 years time frame. Now I want to build ML model that is able to forecast this over-supply when a new order comes onsite. I have a dataset ready for this. You know that this is not a continuous variable where you could use linear/non-linear relationships to predict. Since I know the tolerance for each order I can assign labels Yes/No to my data. Do you think a classification algorithm would be enough?




How do i make something random in a function?

i have a function with some images in it here

function rain() {
    ctx.drawImage (image1, x, y, 100, 50);
    ctx.drawImage (image2, x, y, 100, 50);
    ctx.drawImage (image3, x, y, 100, 50);
    ctx.drawImage (image4, x, y, 100, 50);
}

How do i make this function randomly choose one of these images when i call it?




Im making a quiz using windows forms and C# but it keeps displaying the same question

It reads in questions/answers/topics etc from a .txt file and stores it in an array called ‘questionArray’ which is split by commas into another array called ‘splitDetails’. The if statement selects questions of a particular difficulty level and topic from the list and creates a new question ‘newQ’ of type MultipleChoice which has properties like QuestionText, Choice1, Choice2 etc. and its added to a list called ‘allQuestions’. populateTextboxes() picks a random question from the ‘allQuestions’ list and sets it to the object ‘currentQ’ which is of type MultipleChoice, then deletes it from the list so it isn’t shown again.

{
if (File.Exists("MultipleChoice questions.txt")) //checking file exists
{
   string[] questionArray = File.ReadAllLines("MultipleChoice questions.txt"); //create array of all questions 

   foreach (string Q in questionArray)
   {
        string[] splitDetails = Q.Split(',');  //create new array split by commas
if (splitDetails[6] == Quiz.DifficultyLevel && splitDetails[7] == Quiz.CurrentTopic)
       {
            newQ.QuestionText = splitDetails[0]; 
              newQ.Choice1 = splitDetails[1];
              newQ.Choice2 = splitDetails[2];
              newQ.Choice3 = splitDetails[3];
              newQ.Choice4 = splitDetails[4];
              newQ.Answer = splitDetails[5];
              newQ.Difficulty = splitDetails[6];
              newQ.Topic = splitDetails[7];
              newQ.QuestionType = splitDetails[8]; 

              allQuestions.Add(newQ); 

         }
      }
   }
   Else MessageBox.Show("No question file found", "File not found");
}

//add text to blank question form
public MultipleChoice populateTextboxes() 
{
  Random myNum = new Random();

  if (allQuestions.Count > 0)
  {
    questionCount += 1;

       //select random question from all questions
       int randomNumber = myNum.Next(0, allQuestions.Count);
       currentQ = allQuestions[randomNumber];
       allQuestions.Remove(currentQ);//remove used uestion so it isnt used again
  }

  //when the round is over (3 questions asked)
  if (questionCount == 4) 
  {
    //open keyboardQuestion
    this.Close();
    KeyboardInput k = new KeyboardInput();
    k.Show();

   }

   lblQuestion.Text = currentQ.QuestionText; 
   btnChoice1.Text = currentQ.Choice1;
   btnChoice2.Text = currentQ.Choice2;
   btnChoice3.Text = currentQ.Choice3;
   btnChoice4.Text = currentQ.Choice4;

   return currentQ;
}




Random Sampling for Isotropic Angle

When sampling angles in 3-d space to get angles isotropically, I've been read from a few textbooks that the proper way to sample is this is with phi=2*pi*r1 and theta=arccos(1-2*r2) where r1 and r2 are values from 0 to 1. However, I'm a little confused about this. It seems to me like for the distribution to be isotropic, we would need to sample theta=pi*r2.




How good is Python secrets.SystemRandom in Windows 10?

I want to use Python for basic cryptographic applications with Windows 10.

I see that secrets uses secrets.SystemRandom which in turn uses os.urandom() for random number generation.

How good is os.urandom in Windows 10?

From the Python documentation I see that os.urandom() in Windows uses CryptGenRandom() which is deprecated by Microsoft and has some security flaws as per Wikipedia.




How do I rerun a static integer array?

here's the array I want to rerun:

public static int[] rollDice(int dice[]) {
    // generate 5 random numbers / update dice array
    for (int i = 0; i < dice.length; i++) {
        dice[i] = (int)(Math.random() * 6 + 1);
    }

    return dice;
}

If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.




Randomised partition vs Lomuto Partition in Quick Select

How does Randomised partition improve the performance of the Quick Select Algorithm, even though the worst-case time complexity of both the algorithms (using Lomuto and randomized partition) is O(n^2)?




Fast method to access random image pixels and just once

I'm learning OpenCV (C++) and as a simple practice, I designed a simple effect which makes some of image pixels black or white. I want each pixel to be edited only once; so I added address of all pixels to a vector. But it made my code very slow; specially for large images or high amounts of effect. Here is my code:

void effect1(Mat& img, float amount)    // 0 ≥ amount ≥ 100
{
    vector<uchar*> addresses;
    int channels = img.channels();
    uchar* lastAddress = img.ptr<uchar>(0) + img.total() * channels;
    for (uchar* i = img.ptr<uchar>(0); i < lastAddress; i += channels) addresses.push_back(i);   //Fast Enough
    size_t count = img.total() * amount / 100 / 2;
    for (size_t i = 0; i < count; i++)
    {
        size_t addressIndex = xor128() % addresses.size();   //Fast Enough
        for (size_t j = 0; j < channels; j++)
        {
            *(addresses[addressIndex] + j) = 255;
        }   //Fast Enough
        addresses.erase(addresses.begin() + addressIndex);    // MAKES CODE EXTREMELY SLOW
    }
    for (size_t i = 0; i < count; i++)
    {
        size_t addressIndex = xor128() % addresses.size();   //Fast Enough
        for (size_t j = 0; j < channels; j++)
        {
            *(addresses[addressIndex] + j) = 0;
        }   //Fast Enough
        addresses.erase(addresses.begin() + addressIndex);    // MAKES CODE EXTREMELY SLOW
    }
}

I think rearranging vector items after erasing an item is what makes my code slow (if I remove addresses.erase, code will run fast).

Is there any fast method to select each random item from a collection (or a number range) only once?

Also: I'm pretty sure such effect already exists. Does anyone know the name of it?




How to keep track of row index of the rows I randomly select from a matrix?

I am trying to perform tournament selection in a GA whereby I need select two rows randomly. Is there a way of keeping track of the index values of the 2 random rows I select from the matrix self.population and storing those in variables?

At the moment it just outputs the two random rows but I need to keep track of which rows were selected.

Below is what I have so far although ideally I would like to store both rows I select from my matrix in separate variables.


self.population = [[0 1 1 1 0 0 1 1 0 1]
                  [1 0 1 1 0 0 0 1 1 1]
                  [0 0 0 0 0 1 1 0 0 0]
                  [1 1 0 0 1 1 1 0 1 1]
                  [0 1 0 1 1 1 1 1 1 0]
                  [0 0 0 0 1 0 1 1 1 0]]

def tournament_select(self):
    b = np.random.randint(0, self.population[0], 2) 
    return self.population[b]




How to take the most similar rand generated string to a master string, mutate the random string through generations to achieve the original string?

i have generated N random sequences of length L in the letters A, C, G, T(e.g N= 10, L= 21) and created a function that calculates the distance between two 21 letter words,

enter image description here

as you can see, the output of this consists of the master genome and the mutations of said genome and how different the mutated genomes are from the original genome(how many characters are similar).

The issue is, i would like to be able to select the random sequence that has minimum distance to the 21-letter master sequence GATACCAATTACCAGATACCA. An alternative perspective of the same thing is to find the random sequence with the maximal overlap with the master sequence. This is a measure of fitness for these random sequences, and you select the random sequence with the highest fitness. Write a function that measures this overlap/fitness between a random 21-letter sequence and the master sequence.

After this initial step, create 10 offspring copies of that maximum fitness sequence, but evolve them by having a certain probability (e.g. 1/100) for each of the 21 letters to be randomly turned into a random letter of the alphabet (a mutation).

At each generation step, select from the 10 offspring the one with the highest fitness, and use that to evolve again in the next generation.

i would like to then be able to be able to repeat this process for a number of G generations, until the original master genome has been achieved through evolution- and how many generations it took- It should look something like this:

enter image description here




array filled with unsimilar random int

excuse my english... i need an array to be filled with random integers, i need those integers to be very distincts from each another : (must at least be 20 units of separation between each items)

this is what i have tried so far :

var all = [];
var i = 0 ;

randomDiff();


function randomDiff()
{
  var num1 = randomNumber(10,290);                   //chose a first random num in the range...
  all[0]= num1;                                      //...put it in first index of array
do                                                   // until you have 12 items...
{
  var temp = randomNumber(10,290);                   //...you pick a temporary num              
  var j;
  for (j = 0; j < all.length; j++ )                  // for each item already in the array
  {
    if ((temp<all[i]-10)||(temp>all[i]+10))          // if the temporary num is different enough                                                            from others members...
            {
              all.push (temp);                       //then you can store it
             i++;                                    //increment until....
             console.log (all[i]);
            }                         
        }  
     }
     while (i<11)                                    // ...it is filled with 12 items in array    
}
////////////Radom in int range function///////////////////////////////////////
function randomNumber(min, max) {  
    return Math.floor(Math.random() * (max - min) + min); 
} 

  

it s not working!!, i have tried many other strategys but always unsuccessful, including foreverlasting loops... Hope you will help me, by advance thank you!!




jeudi 28 mai 2020

Random non overlapping circles(with circle number controlled) in python and pygame

I was writing the code for non overlapping random circles with different radii.I kind of got the deserved, but my 'if' statement that checks overlap or non overlap excludes a number of circles. So, I get lesser number of circles. Here's the code:

import pygame
import numpy as np

pygame.init()
display_width = 800
display_height = 500

black = [0, 0, 0]
white = [255, 255, 255]
red = [255, 0, 0]

display_surface = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()
pygame.display.set_caption("Random Circle")


def circle(x, y, r):
    pygame.draw.circle(display_surface, red, (int(x), int(y)), int(r), 2)


def distance(x1, y1, x2, y2):
    dsq = (x1 - x2) ** 2 + (y1 - y2) ** 2
    d = np.sqrt(dsq)
    return d


n = 100

r = np.random.randint(10, 20, size=n)
x = np.random.randint(r, display_width - r, size=n)
y = np.random.randint(r, display_height - r, size=n)

display_surface.fill(black)

for i in range(len(r)):
    valid = True
    for j in range(len(r)):
        if i != j:
            d = distance(x[i], y[i], x[j], y[j])
            if d < r[i] + r[j]:
                valid = False

    if valid:

        circle(x[i], y[i], r[i])

    pygame.display.update()
    clock.tick(100)

exit = False
while not exit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

I saw an answer to a question here which does exactly what this code does( except it uses a class of circles which I didn't use). I sense that I have to use some kind of while loop which doesn't end until I get my desired number o circles. But I find difficulty in actually writing the code. Can anyone help?




Generate a random temperature information

I'm trying to do a simple python script to generate a random temperature reading from a sensor along the day, to test an application.

The problem is, I need to generate the temperature following a normal curve, where in the morning the temperature is colder, hot in the middle day, and goes down again at night.

Generate between two numbers is a problem since give-me a wide range of numbers and doesn't follow a normal curve.

Actually I'm using a datetime function to get the hour and increase or decrease a little the range but without any success.

Any suggestion how to do it?




Random packages-IndentationError: unindent does not match any outer indentation level

random_generated = rando.randint(1,6)
print("This is the number generated", random_generated)

get_answer = input("Wanna play again!Enter: ")
           = int(input("Wanna play again? Enter y/n: "))
    while (True)
        = input("Wanna play again? Enter y/n: ")
        if get_answer == 'y':
            random_generated = random.randint(1,6)
            print('This is the number generated', random_generated)
            if get_answer == 'n':
                break



Is generating random numbers from hardware performance cryptographically secure?

Suppose I have a program that needs an RNG.

If I were to run arbitrary operations and check the ∆t it takes to do said operations, I could generate random numbers from that

For example:

double start = device.time();
for(int i=0;i<100;i++);//assume compiler doesn't optimize this away
double end = device.time();
double dt = end-start;

dt will be more or less random based on many variables on the device such as battery level, transistor age, room temperature, other processes running, etc.

Now, suppose I keep generating dts and multiply them together as I go, hundreds of times, thousands of times, millions of times, eventually I am left with a very arbitrary number based on values that were more or less randomly calculated by hardware performance benchmarking.

Every time I multiply these dts together, the possible outputs increases exponentially, so determining what possible outputs may be becomes perhaps an impossible task after millions of iterations of this, even if each individual dt value is going to be within a similar range.


A thought then occurs, if you have a very consistent device, you may have dt always in the range of say 0.000000011, 0.000000012, 0.000000013, 0.000000014, then the final output number, no matter how many times I iterate and multiply, will be a number of the form 0.000000011^a * 0.000000012^b * 0.000000013^c * 0.000000014^d, that's probably easy to crack.

But then I turn to hashing, suppose rather than multiplying each dt, I concatenate it in string form to the previous values and hash them, so every time I generate a new dt based on hardware performance's random environmental values, I hash. Then at the end I digest the hash to whatever form I need, now the final output number can't be written in a general algebraic form.

Will numbers generated in this form be cryptographically secure?




how to randomly connect 2 people swift?

I have a chat application, but I need that after tap at the button 2 random online users connect in one chat.How I can do this in swift(UIKit)? Which method or function?




Quick method of shuffling a long array python

Hi there Im looking to shuffle an array of 15 integers. I can do this in a long winded manner i'm sure however I was wondering if there is a simple function to do this? i have tried importing random and using random.shuffle however it tells me it can only take a maximum of 3 positional arguments. Is there a function that can do this for a long array? Im struggling to find a way so far

 import random

a = random.shuffle(9,
6,
7,
5,
6,
8,
8,
9,
8,
6,
6,
7,
7,
7)

print(a)



numpy random matrix with bounds along each axis

with

a = numpy.random.randomint(lo,hi,(m,n))

I can create a numpy matrix of size m, populated with random values between 'hi' and 'lo'.

Is there a way to create a numpy matrix with say random values such that

along column 1 I have numbers btween 'hi1', 'lo1' and

along column 2 I have numbers between 'hi2' and 'lo2' etc.

i.e. each column will have its own hi,low.

Any help will be much appreciated.




How do you get set.seed() and sample() to produce the same results

I have seen a couple posts on the use of the set.seed() function followed by the sample() function, but it is still not clear to me why sample() gives different results.

I have replicated a very simple example using the code below and get different results based on the respective R versions.

How do I get the same sample() result consistently as this is important when sharing the code to be reproducible on another machine / platform.

set.seed(47)
index3 = sample(rnorm(200), 200, replace = FALSE)
index3

Version of 1st run (Windows):

##                _                           
## platform       x86_64-w64-mingw32          
## arch           x86_64                      
## os             mingw32                     
## system         x86_64, mingw32             
## status                                     
## major          3                           
## minor          5.3                         
## year           2019                        
## month          03                          
## day            11                          
## svn rev        76217                       
## language       R                           
## version.string R version 3.5.3 (2019-03-11)
## nickname       Great Truth

Version of 2nd run (Mac):

##                _                           
## platform       x86_64-apple-darwin17.0     
## arch           x86_64                      
## os             darwin17.0                  
## system         x86_64, darwin17.0          
## status                                     
## major          4                           
## minor          0.0                         
## year           2020                        
## month          04                          
## day            24                          
## svn rev        78286                       
## language       R                           
## version.string R version 4.0.0 (2020-04-24)
## nickname       Arbor Day



Replacing strings with values from dictionary using random.sample

Suppose I'm creating a madLib and i want to replace each word from a string that has the word 'plural noun'. Basically, the user gets a prompt that states to input plural nouns and those inputs the go to a dictionary (pluralnoDict).

I've been using random.choice, and it's been working out, however, the repeats is obviously the issue. I tried random.sample, however, instead of choosing one word from a given sample, the code replaces the words with the whole sample.

There a way I can replace each string using random.sample from a dictionary list? For example:

Original: The 'plural noun' have 'plural noun' and 'plural noun'. Expected: The 'birds' have 'wings' and 'feet'.

Below is the for loop i use to replace the plural noun strings.

for key in pluralnoDict:
        target_word = "({0})".format(key)
        while target_word in madString:
            madString = madString.replace(target_word,random.choice(pluralnoDict[key]), 1)



replace random.sample with numpy.random python

I have 40 folders each with 10 images. this code splits each image folder in half and from those 10 images 5 are choosen in random for training and 5 for testing

for Class in allClasses:
    path = folderPath + '/' + Class
    allImages = os.listdir(path)
    imageCount = len(allImages)
    # seperating training images
    randomlist = random.sample(range(imageCount), (int)(imageCount / 2))
    trainingImagesForClass = [allImages[i] for i in randomlist]
    trainingImages.append([readImage(path + '/' + i) for i in trainingImagesForClass])
    # seperating test images
    testList = [x for x in range(imageCount) if x not in randomlist]
    testImagesForClass = [allImages[i] for i in testList]
    testImages.append([readImage(path + '/' + i) for i in testImagesForClass])

This code works perfectly fine but i want to implement this using numpy random




Nextjs mix SSR and client data in components

I faced the situation when the same component shows mixed data when randomisation involved, html get jumbled data partially from SSR and partially from client rendering.

Here is the code :

const Component = (props) => {
    const rand = Math.random();
    console.log('==========================', rand);

    return <a href={rand}>{rand}</a>
}

The result is following.

SSR :

========================== 0.30408232064749563

Client rendering :

========================== 0.6842738761932372

Result HTML :

<a href="0.30408232064749563">0.6842738761932372</a>

So the a tag get old SSR value in href while text value get updated.




Randomly Consuming a Set of Elements Indexed From 1 to N

In this problem, I have a set of elements that are indexed from 1 to n. Each element actually corresponds to a graph node and I am trying to calculate random one-to-one matchings between the nodes. For the sake of simplicity, I neglect further details of the actual problem. I need to write a fast algorithm to randomly consume these elements (nodes) and do this operation multiple times in order to calculate different matchings. The purpose here is to create randomized inputs to another algorithm and each calculated matching at the end of this will be another input to that algorithm.

The most basic algorithm I can think of is to create copies of the elements in the form of an array, generate random integers, and use them as array indices to apply swap operations. This way each random copy can be created in O(n) but in practice, it uses a lot of copy and swap operations. Performance is very important and I am looking for faster ways (algorithms and data structures) of achieving this goal. It just needs to satisfy the two conditions:

  1. It shall be able to consume a random element.
  2. It shall be able to consume an element on the given index.

I tried to write as clear as possible. If you have any questions, feel free to ask and I am happy to clarify. Thanks in advance.

Note: Matching is an operation where you pair the vertices on a graph if there exists an edge between them.




mercredi 27 mai 2020

Estimating size of a large text file

From the comment on a question about selecting n random lines from a text file here:

Select random lines from a file

User commented that they used the shuf command to randomly select lines from a text file having 78 billion lines in less than a minute.

I see from various sources on the internet that people have text file sizes varying from 100GB-200GB-300GB for mere 7-15 Billion lines, depending on the metadata.

I am curious as to :

  1. What will be the estimate size of a text file having raw data spread over 78 billion lines? (and some pointers on calculating that)
  2. How does bash - running on a system with a limited computing power(let's say 16GB RAM, ~512GB SSD, 2.5 GHz Intel Core i7 processor - a typical macBook Pro) process this data under a minute?

I get that there are several ways to store and retrieve huge amounts of data. Just curious as to how bash will process it in a short time.




How to generate random number in a list of list

I'm not good at programming so i'm here to ask help for a program that I don't know how to resolve

  1. from random import randint
  2. rain=[]
  3. x=randint(0,500)
  4. y=randint(0,500)
  5. r=2
  6. l=[x,y,r]
  7. for k in range(7):
  8. rain.append(l)
  9. print(rain)

I just want that all of the number in this list is not the same exept for r exemple:[[46, 117, 2], [46, 117, 2], [46, 117, 2], [46, 117, 2], [46, 117, 2], [46, 117, 2], [46, 117, 2]]




randomly select value from list and remove that item from the list

Apologies, up front if this has been answered elsewhere. If so, please just point me to the correct thread.

I need a script that will randomly select a value from a set of 52 values stored in a Column (e.g. Column 'A') of a Google Sheet, paste that random value in a cell (e.g., 'C1'), and remove that value from the original set, thereby leaving 51 values in the column.

If you haven't guessed, I developing a card game that will let me randomly draw a virtual "card" from a virtual "deck of cards" (i.e, values in one column of a Google Sheet sheet (e.g., 'Ace of Clubs', 'Ten of Diamonds', etc.), that will simulate drawing (and removing) that card from the virtual deck.

Can someone please point me to a thread with the solution or provide the script that will do this?

Thanks, very much!




Can I randomize a list in Python using percentage?

Recently I've been working on a project where I need to put characters in random order with a limit, for example, if I have a list with 25,000 "_" in it, I need to set 4% (1,000) of these "_" into "X" in random positions.

The list that I'm working with is a bidimensional array.




How can I loop through the function random amount of times?

I'm trying to create a random amount of squares on canvas each time I press the button and then I want them to move up. Right now it completely ignores the for loop and only generates one square instead of random amount. How to solve this?

// Spawn
var numberArray = [0, 60, 120, 180, 240, 300, 360, 420];
var posX = numberArray[Math.floor(Math.random() * numberArray.length)];
var posY = 240;

  function spawnRandomObject() {
    // Game Object
      ctx.fillStyle = '#f2a365';
      ctx.globalCompositeOperation = "destination-over";
      ctx.beginPath();
      ctx.fillRect(posX, posY, 60, 60);
      ctx.stroke();
  }


// Blocks moving up
document.getElementById("button").addEventListener("click", function(){
  // Spawn random amount of objects
  for (var i=0; i<Math.floor((Math.random()*8)+1); i++){
     spawnRandomObject(i);
  }
  posY -=60;
});



PHP Random number not staying the same in a session

I'm trying to make a site where it creates a random number, then stores it for the whole time that the tab is open. It all seems to work, except the number changes with every guess. I haven't used sessions very much so it may be obvious what is wrong. I made the code output the random number so I can check if it's changing. Ideally, the random number stays the same until they guess correctly, then they hit the retry button the reload the site. Thanks !

<?php
  if(session_status() === PHP_SESSION_NONE){
  session_start();                                      #starts a session if none are started
  }

      if(!isset($_SESSION['randomNum'])) {              #creates number 1-100
      $_SESSION['randomNum'] = rand(1,100);
    }
      $randomNum=intval($_SESSION['randomNum']);        #sets input to variable of $randomNum
      if(!isset($_SESSION['counter'])) {                #starts the counter and sets it to 1
        $_SESSION['counter'] = 1;
      }
      $output_ct = $_SESSION['counter'];

      if(isset($_GET['guess'])){                        #if its inputted, its get the guess
      $guess = $_GET['guess'];                          #the guess is assigned to $guess

      if($guess < $randomNum){                          #if the guess is lower than the randomNum
        $output = "Guess of $guess is too low";
        ++$_SESSION['counter'];                         #adds 1 to counter
      }
      elseif($guess > $randomNum){                      #if the guess is higher then the randomNum
        $output = "Guess of $guess is too high";
        ++$_SESSION['counter'];                         #adds 1 to counter
      }

      else{                                             #if the guess is equal to the randomNum
        $output_ct = "You've had . $output_ct . guesses";
        "<br>";
        $output = "Congratulations! Your guess of $guess was correct.";
        "<br>";
        $n_guesses = "You guessed correctly in $output_ct tries.";

        session_destroy();
      }
    }
 ?>

 <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <title>
        FOLIO 4
    </title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link href="stylesheet.css" type="text/css"rel="stylesheet">
  </head>

  <body>
    <div class="sidenav">
        <a href="index.php">Home</a>
        <a href="folio1.php">Folio 1</a>
        <a href="folio2.php">Folio 2</a>
        <a href="folio3.php">Folio 3</a>
        <a href="folio4.php">Folio 4</a>
        <a href="folio5.php">Folio 5</a>
    </div>

    <div class="main">
      <center>
        <h1>Folio 4</h1>
          <br>
              <h5>The user inputs a number between 1 and 100. The site will
                  tell them if their guess was too high or too low, and allows
                  them to guess again. When the user gets the number correct, the
                  site will congratulate them and tell the user how many guesses
                  they took.
              </h5>
          <br>

            <div class="form" action="folio4.php">
                <form method="get">
                  <label for="guess">Guess a number between 1 and 100 &nbsp</label>
                  <input type="number" name="guess" id="guess" min="1" max="100" required>

                    <br><br><br>

                  <button type= "submit">Submit</button>
                </form>

            <br><br>
            </div>

            <div class="output">
              <p>
              <?php
                echo $output;
                "<br>";
                echo $n_guesses;
                "<br>";
                echo $_SESSION['randomNum'];
               ?>
              </p>

            </div>

              <br>

            <div class="retry">
              <a href=folio4.php>Play again</a>

                <?php
                  session_unset();
                  session_destroy();
                 ?>

            <br><br><br>
            </div>

           <a href="">
           See planning for Folio 4
           </a>

    </div>
  </body>
</html>




How to delete a card from the deck after dealt

I want to deal a card and after that I want that specific card to pop from the deck but right now my code is always 51 cards it does not go to 0.

Thank you very much in advance

//Variable with the four suits of a deck

const suits = ['Corazon', 'Diamante', 'Trebol', 'Espada'];

//Variable with all the possible card values

const values =[2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jota', 'Reina', 'Rey', 'Az'];

//Create a class for the cards

class Card {
  constructor(suit, value) {
    this.suit = suit;
    this.value = value;
  };
};

//Create a class for the deck

class Deck{
  constructor(){
    this.deck = [];
  }

  //Creates the deck
  createDeck(suits, values) {
    for (let suit of suits) {
      for (let value of values) {
        this.deck.push(new Card(suit, value));
      }
    }
  return this.deck;
  }

//Shuffles the deck

shuffle () {
    let counter = this.deck.length, temp, i;

    while(counter) {
      i = Math.floor(Math.random() * counter--);
      temp = this.deck[counter];
      this.deck[counter] = this.deck[i];
      this.deck[i] = temp;
    }
    return this.deck;
  }

//Deals a card and discards it from the deck

deal () {
    let hand = [];
    while (hand.length < 1) {
      hand.push(this.deck.pop());
    }
    return hand;

  }

//Assigns game to the dealt card

game () {
    this.createDeck(suits, values);
    this.shuffle();
  }
};


let deck = new Deck();
deck.createDeck(suits, values);
deck.shuffle();
console.log(deck.deal());



Displaying 1024 bit binary number in base 10 c++

I'll try explaining my problem to the best of my ability. To start off, here's my code for a program I wrote that generates an array of n length, where each element is either a 1 or a 0. The next method takes in an array made from the first method and formats it into a binary number that can be printed to the console.

#include "bigNum.h"
#include <iostream>
#include <cstdlib>

short* genArr(int bits)
{
        static short *numArr = new short[bits];
        srand(time(0));
        int i;
        for (i = 0; i<bits; i++) {
                numArr[i] = rand() % 2;
        }
        return numArr;
}

void formatNum(short arr[], int size) {
        int i;
        for (i = 0; i<size; ++i) {
                std::cout<<arr[i];
        }
        std::cout<<"\n";
}

The main reason why I created this program is to generate large random numbers to the order of 1024 bits and beyond. I don't think a simple binary to int conversion will work because the size of my binary number is not constant, and it can clearly be larger than 64 bits.

For example, if I generate a 1024 bit binary number, it prints to the console:

./test 1024
00100110110011111111000111011111001001010001110111011001100010110010110010111000101101011011000100101101110110110100001000110100110110000011010000000101110110101010011010                     01101111010001000100100100011001111110010110011101101110111011111100101110000110000011001110101011010101101110000001000111101101000010011100000010010000110001111111010110                         11101001111110011100000110111010100001010101010101101110101000111101001011110000100010010111100000000110001100110011010000100000001110100011000000001010000100111000010111                         00000000101001000100010001100000000101111011001011011111001001011000111001101000011100000100101001001001101001000110110110100101011111001100100110001010100111000111101011                         00110010000111111101101010000011000001001110010100111010001000101111010001010000111011011101011110010010001000111011100010110101110110010100110111011011110101010011011001                         10011101001010111101000100011100101011101000110000001001000110100001011101010010011111001011011010011111110110011111011100001011010101110111111100001111100101000010000001 

EDIT: sorry, I can't remove the long tabs. I think it was due to a copy/paste formatting error.

What I want to do is to convert this long binary number into a string that displays the base 10 representation of this. I couldn't find similar problems online, so I'm resorting to posting a question here. I hope I described my problem thoroughly.




1) Make an array of size 10 2) Make a method called fillArray that fills an array randomly Boolean 3) Print the array using the Arrays method [closed]

I'm horrible at code so could someone cut me some slack and help me with these tasks? Just this would be enough as it's due today so someone please help.




What is the value of modulus (m) on Node.js Math.random()?

Does anybody know the value of the modulus on the random number generator algorithm used on Math.random() on Node.js? I'm using version 12.17.0




Generate uniformly distributed points in a circle

''' I am trying to generate points in a circle that should be uniformly distributed but I get a weird pattern. If I increase the radius R to a very large value, the distribution appears normal but with smaller R values it generates spirals. Any suggestions to improve the code? '''

from numpy.random import uniform
#from scipy.stats import uniform
import matplotlib.pyplot as plt
import numpy as np
import math  

R = 5
# Generate uniformly distributed random numbers.
rand_num = []
for i in range(30000):
    rand_num.append(np.random.uniform(0,1))

# Use these generated numbers to obtain the CDF of the radius which is the true radius i.e. r = R*sqrt(random()).
radius = []
for n,data in enumerate(rand_num):
    radius.append(R*math.sqrt(data))

# Generate the angle using the same uniformly distributed random numbers.
theta2 = []
for n, k in enumerate(radius):
    theta2.append(2*math.pi*radius[n])

# Calculate the corresponding x-coordinate.
x = []
for j,v in enumerate(radius):
    x.append(radius[j]*math.cos(theta2[j]))
x = np.array(x)   

# Calculate the correspoding y-coordinate.
y = []    
for j,v in enumerate(radius):
    y.append(radius[j]*math.sin(theta2[j]))
y = np.array(y)

# Finally plot the coordinates.
plt.figure(figsize=(10,10))
plt.scatter(x, y, marker='o')



Butterfly pattern appears in random walk using srand(), why?

About 3 years ago I coded a 2D random walk togheter with a coleague in C++, first it seemed to work properly as we obtained a diferent pattern each time. But whenever we decided to increase the number of steps above some threshold an apparent butterfly pattern appeared, we noticed that with each run of the code the pattern would repeat but starting on a different place of the butterfly. We concluded and reported then that it was due to the pseudorandom generator associated with srand() function, but today I found again this report and there are still some things that I would like to understand. I would like to understand better how the pseudorandom generator works in order to obtain this sort of symmetry and ciclic pattern. The pattern I'm talking about is this (The steps are color coded in a rainbow sequence to apreciate the progression of the walk):

enter image description here




VBA - Probabilistic Random Selection from Dynamic Array

I'm new to VBA here. I have 2 lists, a list of price, and a list of the probabilities assigned to the price. I need to generate a list of 300 numbers based on the probability group. However, I can't seem to get it to work. I ripped a code off another post:

Function RandItem(items As Variant, probs As Variant) As Variant
    Dim i As Long, sum As Double
    Dim spin As Double

    spin = Rnd()
    For i = LBound(probs) To UBound(probs)
        sum = sum + probs(i)
        If spin <= sum Then
            RandItem = items(i)
            Exit Function
        End If
    Next i
    'if you get here:
    RandItem = items(UBound(probs))
End Function

And also

Sub test()
    Randomize
    Dim i As Long, v As Variant
    ReDim v(1 To 50)
    For i = 1 To 50
        v(i) = RandItem(Array(1, 2, 3, 4, 5), Array(0.26, 0.18, 0.26, 0.2, 0.1))
    Next i
    Debug.Print Join(v)
End Sub

to adapt to my code. However, the problem is that the price range grows, and the probability changes over time (due to historical weightage). So I tried to switch the:

RandItem(Array(1, 2, 3, 4, 5), Array(0.26, 0.18, 0.26, 0.2, 0.1))

to

Dim i As Long, v As Variant
Dim LastRow As Long
Dim arrayPrice As Variant
Dim arrayProPrice As Variant
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
arrayPrice = Range("A2:A" & LastRow).Value2
arrayProPrice = Range("B2:B" & LastRow).Value2
ReDim v(1 To 300)
    For i = 1 To 300
        v(i) = RandItem(arrayPrice, arrayProPrice)
    Next i
    Debug.Print Join(v)
End Sub

and it returned: Run-time error '9': Subscript out of range. Anyone has any suggestions how to fix this so I can use array variables instead of listing out all the price ranges?

Credits: Generating numbers with certain probabilities visual basics vba




Generating random mock data with specific time range

I wanted to generate mock data with the below structure, But Start time and end time interval should be 30 Mins.

  [{
    Id: 1,
    Subject: 'Bob',
    StartTime: new Date(2020, 6, 11, 9, 30),
    EndTime: new Date(2020, 6, 11, 11, 0),
    CategoryColor: '#1aaa55'
  }]

I tried with this generating tool but issue is, time interval is not maintained.

Could you please suggest any alternate approach to achieve this ?




How to randomly select items from a list for random times

 mal = ["a","b","c","d","e","f","g"]
num_to_select = randint(1,4)                
list_of_random_items = random.sample(mal , num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1] 
print(second_random_item)
print(first_random_item)

I searched some questions here and tried to edit a bit but doesnt work.

I want to select random items for random times like;

python randomly chose the number 4

printed randomly 4 items from list

Thank you.




mardi 26 mai 2020

Random values +/- 10 from a supplied x that will not exceed a global range of 0-255

I have found similar, but not suitable answers to my issue. I need to build some noise into recieved RGB values, but the values cannot exceed 255 or be below 0.

I have the following example:

red,green,blue = (253, 4, 130)

print(
    (np.random.randint(red-10,red+10),
     np.random.randint(green-10,green+10),
     np.random.randint(blue-10,blue+10)))

# output values cannot be over 255 or under 0

#The following output would not be ok.
>>>(257, -2, 132)

How can I generate random +/- 10 value from any point within the range of 0-255 that will not exceed 255 or 0?




How to pick a row randomly based on a number of tickets you have

I have this table called my_users

my_id | name | raffle_tickets
1     | Bob  | 3
2     | Sam  | 59
3     | Bill | 0
4     | Jane | 10
5     | Mike | 12

As you can see Sam has 59 tickets so he has the highest chance of winning. Chance of winning:

  • Sam = 59/74
  • Bob = 3/74
  • Jane = 10/74
  • Bill = 0/74
  • Mike = 12/74

PS: 74 is the number of total tickets in the table (just so you know I didn't randomly pick 74)

Based on this, how can I randomly pick a winner, but ensure those who have more raffles tickets have a higher chance of being randomly picked? Then the winner which is picked, has 1 ticket deducted from their total tickets

UPDATE my_users
SET raffle_tickets = raffle_tickets - 1
WHERE my_id = --- Then I get stuck here...



How to generate n string (ie. twenty) from pattern?

Now I'm using this code

tr -dc 'A-X0-9' < /dev/urandom | head -c12 > test.txt

and works fine but it generate only one string without any pattern.

How to modify this string to generate n string (ie. twenty) starting with: "MyPassword" and then 12 generated digits?

thanks!




Inconsistent results between dqrng and R API for PRNG in RCPP

I am attempting to implement a particle filter within Rcpp and use OpenMP to parallelise the transition step. I am using dqrng to create threadsafe RNG with using the boost distribution functions as per here.

The code for the R API can be found here and introducing dqrng here

The issue I am having is that, using the R API, I achieve correct results, verified against alternate implementations, with the density of the estimator being roughly normally distributed as expected. However, for the dqrng version the density of the estimator does not appear correct with differing results being obtained. The density plots can be seen below.

Density of estimator with dqrng

Density of estimator with R API

Does anyone have any understanding of why this might be the case?




How do you find a seed for nextFloat() that returns a number above a threshold several times?

How would I find a seed for nextFloat() that would return a number above a threshold, say nextFloat() > 0.8, several times? Maybe five times in a row? Of course 0.8 and 5 are examples, and I know there are a very large number of solutions, but I don't know how I would even go about finding a single one. A lot of the math governing the random numbers next() returns goes way over my head. All help is very appreciated!




How to retrieve a data from a histogram gaussian fitting?

I am working with simulations in realistic conditions in python. So I acquired some noise data from a real system, after this I generated an histogram to see the noise distribution and fitted it with an (adapted) Gaussian model. So, now I need to re-build the noise data from the gaussian fitting, create a list of values with it and pick some random numbers from this list. I have the values of the fitting, but it is like Incidence (freq) vs Voltage. I want to return it to the noise domain (Voltage vs time) to pick the random values from it. How I do that? Below is my data: histogram of noise and the gaussian fitting noise histogram




Bubble sort 2D array in C

I need a function to bubble sort this randomly generated 2D array. Also with rand() method I wanted it to generate numbers between (1, 1000000) but it doesnt give the required range, any suggestion to find out a solution?

int **matrix()
{

    int **matrix;
    int row, column;
    long s, k;
    int i,j,f,swap;


    srand(time(NULL));
    printf("Number of rows: ");
    scanf("%d", &row);

    printf("Number of column: ");
    scanf("%d", &column);


    matrix = (int **) calloc(row, sizeof(int));


    for(i = 0; i < row; i++)
        matrix[i] = (int *) calloc(column, sizeof(int));


    for(s = 0; s < row; s++)
    {
        for(k = 0; k < column; k++)
        {

            matrix[s][k]=rand()%10000000;
        }
    }

    for(s = 0; s < row; s++)
    {
        for(k = 0; k < column; k++)
            printf("%4d \t\t", matrix[s][k]);

        printf("\n");
    }


    for(i = 0; i < row; i++)
        free((void *) matrix[i]);


    free((void *) matrix);

    return **matrix;

}



How to initialize an instance attribute as a numpy array?

I am trying to initialize a 10 by 5 binary matrix of random binary values as a instance attribute. At the moment I simply initialize it as a list and convert it to a numpy array in a separate function. Is there a better way to do this?

self.pop = np.random.randint(2, size=args)
self.pop = self.pop.astype(int)

This is how I do it in the function




Generate random double number in range [0, 1] in C

I have to generate random double number in between 0 and 1. How can i do this using C? I've tried to generate an integer number between 0 and one million and then divide the result by 1M but it didn't work out well.




lundi 25 mai 2020

How to optimize a simulation on more than one variable in R?

I have a dataframe organized as such: df<- dataframe(individual, group name, Z1, Z2, Z3). In my dataset each individual is a member of a group. I am interested only in certain amount of data (e.g. 15000 out of 25000). I have too many Zero's in my dataset. I want to apply two different simulations:

  1. To find all possible combinations of "individuals" where the mean(Z1)~1 and find a range for Z2 and Z3.
  2. To find all possible combinations of "individuals" where the mean(Z1), mean(Z2) and mean(Z3) ~1

The histogram of Z1 Histogram . The boxplot of Z1 shows too many outliers Boxplot. To give an overview of my dataset:

Min. 1st Qu. Median Mean 3rd Qu. Max. 0.000 0.010 0.060 1.854 0.470 108.130

I tried to do the simulation using lapply function and giving some rates to my dataset (Z=Z1):

LO<- lapply(1:5000, function(i){sample(Z,15000,replace=TRUE, prob=1/(Z+8)+(0.2*Z))})
MEANS=unlist(lapply(LO, mean))
hist(MEANS)

In this way I have to adjust the "prob" manually in order to get my histrogram centered on 1. Is this a good way to answer my first problem? Then for the second problem, how can I optimize my simulation on 3 variables? Should I use if-loop? As a side question: how can I give weigh to my dataset based on the population of the each group (the higher the population the higher the probability of individuals to be chosen from that group in my 15000 sample).




Fastest way to Select a random number from each row padded numpy array (excluding the pad) and number of non padded values, using numpy operations

I have a 2D numpy array, each row is padded with (with -1 for the example below).

For each row, I want to pick a random number, excluding the padding, and also get the number of non-padded values for each row, using only numpy operations.

Here is a minimal example. I picked -1 for the pad, but the pad can by any negative int.

import numpy as np
numList = [[0, 32, 84, 93, 1023, -1], [0, 23, 33, 45, -1, -1], [0, 10, 15, 21, 24, 25], [0, 23, -1, -1, -1, -1], [0 , 13, 33, 34, -1, -1]]
numArray = np.array(numList)
numArray

array([[   0,   32,   84,   93, 1023,   -1],
       [   0,   23,   33,   45,   -1,   -1],
       [   0,   10,   15,   21,   24,   25],
       [   0,   23,   -1,   -1,   -1,   -1],
       [   0,   13,   33,   34,   -1,   -1]])

For the lengths, the output should look something like this

LengthsResults
[5, 4, 6, 2, 4]. 

And here's an example output for picking a random non-pad number for each row.

randomNonPad
[84, 45, 0, 0, 34]

Edit:

I was looking at np.where, which lets you filter out parts of your numpy array on a conditional, and numpy random choice, which lets you pick a random number for an array. I'm not sure what to do with np.where though, it seems that you can change it to something, but I'm not sure what yet, or even if it's the right approach. For python, you could start with a list, and append it to any length, but for numpy you need to establish the array length ahead of time.




How to generate non-repeating Random Numbers in Unity

I am trying to create a simple Bingo game and want to make sure the numbers are not repeating on the bingo card. I have a random number generator, but for some reason the code I'm using doesn't work as the same numbers will constantly repeat. Could somebody please take a look at my code below and either tell me what I need to fix or fix the code for me?

public Grid(int width, int height, float cellSize)
{
    this.width = width;
    this.height = height;
    this.cellSize = cellSize;

    gridArray = new int[width, height];
    debugTextArray = new TextMesh[width, height];
    for (int x = 0; x < gridArray.GetLength(0); x++)
    {
        for (int y = 0; y < gridArray.GetLength(1); y++)
        {
            debugTextArray[x, y] = UtilsClass.CreateWorldText(gridArray[x, y].ToString(), null, GetWorldPosition(x, y) + new Vector3(cellSize, cellSize) * .5f, 20, Color.white, TextAnchor.MiddleCenter);
            Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x, y + 1), Color.white, 100f);
            Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x + 1, y), Color.white, 100f);
        }
    }
    Debug.DrawLine(GetWorldPosition(0, height), GetWorldPosition(width, height), Color.white, 100f);
    Debug.DrawLine(GetWorldPosition(width, 0), GetWorldPosition(width, height), Color.white, 100f);


    for (int x = 0; x <= 4; x++)
    {
        RandomValue(0, x);
        RandomValue(1, x);
        RandomValue(2, x);
        RandomValue(3, x);
        RandomValue(4, x);
    }

}

private Vector3 GetWorldPosition(int x, int y)
{
    return new Vector3(x, y) * cellSize;
}

public void RandomValue(int x, int y)
{

    if (x >= 0 && y >= 0 && x < width && y < height)
    {
        list = new List<int>(new int[Lenght]);

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

            Rand = UnityEngine.Random.Range(1, 50);


            while (list.Contains(Rand))
            {
                Rand = UnityEngine.Random.Range(1, 50);

            }

            list[j] = Rand;
            gridArray[x, y] = list[j];
        }


        debugTextArray[x, y].text = gridArray[x, y].ToString();
        debugTextArray[2, 2].text = "Free";
    }
}

}




Random item from iterator?

I have the following code

number_list = (i for i in range(5))
permutations = (num for num in itertools.product(number_list, repeat=9))

This is generating an iterator called permutations which will hold all permutations of 9 characters within the number_list if I'm not mistaken. This can get pretty large for a big number_list.

I can iterate through permutations with next(permutations) but the problem is that it's sequencial. I would like to be able to draw a random item from any part of the iterator. If it was a list, I could simply do random.choice() but for a big number_list I don't have near enough memory nor time for that.

I could also just use next() and store a list of X amount of items and them randomize them but that won't work either because it can get so incredibly big that the outputs would be so similar it wouldn't really be "random".

I was wondering, if it isn't possible to draw a random item from the iterator, is there an algorithm which allows me to create an iterator which will output a random set with next() but that when it ends it will have gone through the entire permutations witout repeating?

The final idea would be having an iterator that would spit a random permutation of n characters out of a list of i elements, being able to get both n and i to arbitrarily large numbers without memory constraints, making sure that when the whole iterator ends up finishing (doesn't matter when, even if it finished after years in theory), all possible permutations would be exhausted without repetitions.




How to play random sound

I'm making a discord bot, and I want it to play a random mp3 file when it joins channel.

case"join":
            message.delete( {timeout: 5000})
            const voiceChannel = message.member.voice.channel
            if(voiceChannel) {
                const connection = await voiceChannel.join()
                const files = fs.readdirSync("./sounds/")
                const randFile = files[Math.floor(Math.random() * files.length)]
                const dispatcher = connection.play(randFile)
            } else {
                message.reply("you need to be in a voice channel!").then(message => message.delete( {timeout: 5000}))
            }
            break;

When I type $join in chat, it joins voice channel that I'm in but doesn't play anything.




How to make a button to pick a random component onPress whit no repeats in react native

I am a newbee. this is my second post.

In my app in react-antive i woudl like to make a button genereta a random number that will determiny which componenet to pick to return. I woudl like to make this random fucntion to pick random component with no repeats. Could someone please help and give me an advice how could i make it happen.




sampling random values each iteration

I have some simulated data, on top of the data I add some noise to see how the noise affects my data for further analyses. I created the following function

create.noise <- function(n, amount_needed, mean, sd){
      set.seed(25)
      values <- rnorm(n, mean, sd)

      returned.values <- sample(values, size=amount_needed)    
}

I call this function in the following loop:

dataframe.noises <- as.data.frame(noises) #i create here a dataframe dim 1x45 containing zeros

for(i in 1:100){         
    noises <- as.matrix(create.noise(100,45,0,1))
    dataframe.noises[,i] <- noises
    data_w_noise <- df.data_responses+noises
    Estimators <- solve(transposed_schema %*% df.data_schema) %*% (transposed_schema %*% data_w_noise)
    df.calculated_estimators[,i] <-Estimators
}

The code above always returns the same values, one solution I tried is sending i as parameter(which i think isn't correct) for each iteration I add i to the set.seed(25+i) This gives me a unique value for each iteration, butas mentioned I don't think that this is the correct way to go with it.




Generate strings of varying in boundaries with bash script

I want to generate strings with lengths between 1-4 with my bash script. I know how to create strings with set length, but want to know if there is a slight alteration to the following command to make it choose between 1-4 length.

cat /dev/urandom | tr -dc A-Za-z0-9 | head -c 4

This will create strings with numbers/letters with standard length 4. Any way to tweek it to fit my needs?




Javascript random code for selecting array not working properly

function whosPaying(name) {
  var position = name.length;

  var randomPerson = Math.floor(Math.random() * position);

  console.log(name[randomPerson] + " is going to buy lunch.");
}


whosPaying("Jack", "Ben", "Jenny", "Michael", "Chloe");

When I run this code to get output in console log instead of selecting a name it selects one letter from the the first name (here:jack).




How to randomly mutate 5 values in a binary list?

I'm writing a genetic algorithm in which i need to select 5 numbers from the binary list 'genotype' and flip them, so a 1=0 and 0=1.I tried putting my code in a loop with a range(1,6) however when I do this it still only changes one of the numbers. Bellow if my original code without the loop which randomly selects one of the binary values and mutates it. Does anyone know a better way of doing this but for 5 of the elements in the list?

genotype = [1,0,0,1,0,0,1,1,1,0]

def mutate(self):
  gene = random.choice(genotype)
  if genotype[gene] == 1:
    genotype[gene] = 0
  else:
    genotype[gene] = 1
  return genotype



How can I produce unique values of Object via Random Process in Java

I want to produce unique values of Movie Object via Random. I wrote a code snippet but I'm not sure all values cannot be unique by using Random().

How can I do this process to produce all of these unique values?

Here is my code snippets shown below.

private static ArrayList<Movie> addMovies(ArrayList<Movie> movieList) {

        for(int i=0;i<20;i++) {
            Movie movie = new Movie();
            movie.setId(defineMovieId());
            movie.setTitle(defineMovieName(15));
            movieList.add(movie);
        }       

        return movieList;
    }


    public static String defineMovieName(int n) { 

        // chose a Character random from this String 
        String AlphaNumericString = "ABCÇDEFGHIİJKLMNOÖPQRSŞTUÜVWXYZ"
                                    + "abcçdefghıijklmnoöpqrsştuüvxyz"; 

        StringBuilder sb = new StringBuilder(n); 

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

            int index 
                = (int)(AlphaNumericString.length() 
                        * Math.random()); 

            sb.append(AlphaNumericString 
                          .charAt(index)); 
        } 

        return sb.toString(); 
    } 

    public static long defineMovieId() {
        int max = 1000;
        int min = 1;
        int range = max - min + 1;
        int res = (int) ( Math.random()*range) + min;
        return res; 
    }



howto generate random number in Haskell without using System.Random module? [closed]

does anybody have any sugestions why System.Random is not in the mini distro of Haskell?

i dont want to install cabal and i have random-1.1.tar.gz for random . is there any way to install it without cabal?

tnx




dimanche 24 mai 2020

Picking A Random Number 1-3 In ARM Assembly Language [duplicate]

I am creating a slot-machine program that requires an output that randomly choose the number 1-3.

I am extremely new to ARM Assembly Language and only know the very basics. I have written my program in Java using Math.random to generate a random number, but I'm not sure how generate random numbers in ARM Assembly.

If anyone has any code with explanation or advice I'd greatly appreciate it. Thank you!




İ have to writing random size button side by side on windows form

İ have to writing random size button side by side on windows form. Form size doesn't matter. if button on Y location 700. Button should go to the next line.




how to generate a random route

I am a beginner coder and i got a coding challenge where i got the following directions: N,S,W,E

in the challenge i need to generate a random 10 steps(directions) list and i am not allowed to have duplicate neighbors for example [n,s,w,e,w,e,n,n,w,e]

here is my code but it doesn't work eight, it stills generates me routes with duplicates

import random

def road_generator():
    directions = ['n','s','w','e']
    road = []
    for x in range(10):
        road.append(random.choice(directions))
    keep_going = True
    while keep_going:
        for x in range(1,len(road)):
            if road[x] == road[x-1]:
                road[x-1] = random.choice(directions)
            else:
                keep_going = False
    print(road)

if __name__ == '__main__':
    road_generator()

can someone please explain to me what i did wrong with my code and how can i fix this?

thanks :)




How to take out x and y from my list so I can use it to create a graph

So I made my list but after that I don't know how to take out of it my x and y so I can use it later to create a graph

import random
import numpy as np
import matplotlib.pyplot as plt

tabuletson = []

for i in range(0, 10):
    x = round(random.uniform(-1000,1000),2)
    y = (2*x+1)
    tabuletson.append([x,y])

print(tabuletson)

wielomian = np.poly1d(np.polyfit(x,y,3))
linia = np.linspace(-2000,2000,2000)

plt.scatter(x,y)
plt.plot(linia,wielomian(linia))
plt.show()



Get random Youtube video in webview by clicking button in Android studio

I want to make an app where the user can get random youtube videos in a webview by clicking a button. I already can show a video in my webview with the url but I want to get any random video from youtube by clicking my button.

In my xml file I have a webview and a button

´´´

MainActivity.java

´´´ public class MainActivity extends AppCompatActivity {

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

    String path = "https://www.youtube.com/watch?v=1uwvxTT5V5M";
    String dataUrl =
           "<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";


    WebView showYoutubeVideo = (WebView) findViewById(R.id.zufallvideo);
    showYoutubeVideo.setWebViewClient(new WebViewClient(){

        public boolean shouldoverloadUrlLoading(WebView view, String url) {
            return false;
        }
    });

    showYoutubeVideo.getSettings().setJavaScriptEnabled(true);
    showYoutubeVideo.loadData(dataUrl,"text/html", "utf-8");

}

}




Java Random generate string from array preventing duplicates

Sorry i am very new to java but i am having trouble finding a clear answer to fix the problem with my code. I am making a mad lib game that randomly generates nouns, adjectives, verbs, etc, and fills in the blanks in the story. I am finding that the code generates the same words over and over as I have multiple adjectives in the story. I am not sure how to fix this so there are no duplicates without having to change a lot of what i have already worked on. FYI i am aware my story doesn't have a spot for verbs yet. Heres my code..

public static void main(String[] args) throws FileNotFoundException {

 Scanner inputNouns = new Scanner(new File("nouns"));
ArrayList<String> nouns = new ArrayList<>();
while(inputNouns.hasNextLine())
    nouns.add(inputNouns.nextLine());
Random rNouns = new Random();

int randomNoun = rNouns.nextInt(nouns.size());
String randomNounWord = nouns.get(randomNoun);

Scanner inputVerbs = new Scanner(new File("verbs"));
ArrayList<String> verbs = new ArrayList<>();
while(inputVerbs.hasNextLine())
    verbs.add(inputVerbs.nextLine());
Random rVerbs = new Random();

int randomVerb = rVerbs.nextInt(verbs.size());
String randomVerbWord = verbs.get(randomVerb);

Scanner inputAdjectives = new Scanner(new File("adjectives"));
 ArrayList<String> adjectives = new ArrayList<>();
 while(inputAdjectives.hasNextLine())
    adjectives.add(inputAdjectives.nextLine());
 Random rAdjectives = new Random();

  int randomAdjective = rAdjectives.nextInt(adjectives.size());
String randomAdjectiveWord = adjectives.get(randomAdjective);



 Scanner inputNames = new Scanner(new File("names"));
 ArrayList<String> names = new ArrayList<>();
 while(inputNames.hasNextLine())
    names.add(inputNames.nextLine());
 Random rNames = new Random();

int randomName = rNames.nextInt(names.size());
String randomNameWord = names.get(randomName);

 Scanner inputPlaces = new Scanner(new File("places"));
 ArrayList<String> places = new ArrayList<>();
 while(inputPlaces.hasNextLine())
    places.add(inputPlaces.nextLine());
 Random rPlaces = new Random();

int randomPlace = rPlaces.nextInt(places.size());
String randomPlaceWord = places.get(randomPlace);




  System.out.println("Ladies and gentlemen, on this " + randomAdjectiveWord + " occasion");
   System.out.println("It is a privilege to address such a/an " + randomAdjectiveWord +" looking group of " +randomNounWord);
   System.out.println("I can tell from your smiling " +randomNounWord + " that you will support my");
   System.out.println(randomAdjectiveWord + " program in the coming election. I promise that, if elected,");
   System.out.println("there will be a/an " + randomNounWord + " in every " + randomNounWord+ ". I want to warn you aganist");
   System.out.println(randomAdjectiveWord + " opponent, " + randomNameWord +". They are nothing but a/an " +randomAdjectiveWord + " " +randomNounWord);
   System.out.println("They have a/an " +randomAdjectiveWord+ " character and is working "+randomNounWord+" in glove");
   System.out.println("with the criminal element. If elected for the offices of "+randomPlaceWord);
   System.out.println("I will eliminate the " +randomNounWord+ " off the streets. Thank you, and goodnight!");

}

}