mardi 31 mars 2020

Simple flip a coin Java Program

Ok, so, I'm bored like most people, and I decided to play and create different apps to build on my java programming skills.

I'm currently stumped on this flip a coin program. I am using a Random number class and asking it to add up the total heads/amount of flips.... but it's not working.

Any hints would be helpful. Currently taking my first Java Class and a University student, so don't judge too much :)

import java.util.*;
public class FlipaCoin
{
 public static void main(String [] args)
 {
Random rand= new Random();
boolean a;
  while (a=true)
  {
int flip=rand.nextInt(2);
int heads=0;
  if (flip==1)
  {

    heads++;
}
double count=0;
double percentage=heads/count;
System.out.println(percentage);
count++;
  if (percentage==50.0)
  {
  break;
}
}
}
}



np.random.seed not reproducing the same numbers

I have a code that requires a number of random vector draws (about 10K size) using np.random.normal, np.random.choice, and np.random.rand multiple times repeatedly. I set up np.random.seed(1234) at the beginning of the code, and I am expecting the code to produce exactly the same output when called twice. However, I get every time different outcomes. Is there anything I am missing about how randomization should occur when seeded?




Generate 5 random Strings and add them to a Set in Java

I am a beginner in Java and I have next issue.How can I generate 5 random Strings and add them to a Set?

Thank you




Choose randomly a number from two columns rstudio

I have this data frame and I' trying to create a new column considering the data in the first column and the column called "zero", I've been using sample(), for an interval from (0,df$firstcolumn) but It gaves me a number between 0 and the data in the first column, not one(0) or another (as an example 9).

Initial data frame:

First column: 9,8,16 Zero column: 0,0,0

What I want is something like this:

First column: 9,8,16 Zero column: 0,0,0 New column: 9,0,16

I really appreciate your answers or opinions. Thank you!




How can I count repeating characters in R

I made a random simulation of Roulette

set.seed(101)
n=10000


black <- sample("black",size=n, replace=TRUE)
red <- sample("red",size=n, replace=TRUE)
green <- sample("green",size=n, replace=TRUE)

roulette_table=matrix(NaN,n,1) 

for (i in 1:n) {
temp = runif(1, 0, 1) # uniform between 0 and 1
# determines the probability
if (temp<0.04) { 
  roulette_table [i,1]=green[i] 
} else if (temp>0.04 & temp<0.52) { 
  roulette_table[i,1]=red[i]
}  else  {
  roulette_table[i,1]=black[i] 
} 
  }

How can i count the frequency of repeating characters ? Thanks




Create an array with rand() [closed]

So my task is to create an array with rand() function. Every time this program runs, asks the size of the array, and how much is the frequency of the 0 that will input in the array. For example on 5x5 array, the zeroes must take part the 80% of this array(but every time the frequency is different). I am not sure how to use the rand() function to solve that. Anybody have any idea how to solve it ?




Draw a 3D box of peanuts (ellipsoids) in MATLAB

I am looking to draw a container of solid ellipsoids in MATLAB, to represent a box of peanuts.

The physical constraints of the problem include:

  • the 3D container (approximately 1 square foot area for the "base," a few inches deep)
  • the size of the peanut, using three radius dimensions for the peanut, each randomly selected from a normal distribution
  • peanuts must not overlap or have touching borders
  • peanuts must be inside the dimensions of the container

I've been looking around for several months now on how to solve this problem efficiently to no avail. It seems the closest I can get is this:

Update on: How to model random non-overlapping spheres of non-uniform size in a cube using Matlab?

but I'm not sure if I understand how to execute the code or what units any of the inputs are in (maybe they're nondimensional?).

I have a working proficiency in MATLAB, but I need someone to break down the problem for me as if you were explaining it to someone who has no experience coding. I'm open to using a different code if there is something that might be more appropriate to the problem at hand.




generate list of no repeated tuples and doesn't have both of (a,b) and (b,a) tuples, python

How can I generate a list of tuples whose elements are not repeated? In addition, if there is (a,b) tuple in list, (b,a) would not be generated in this list.

I use code below from here, but it doesn't provide second condition:

[tuple(i) for i in np.random.randint(5242, size=(500,2))]



How to generate a random double number in Java? (not necessarily in the range [0,1]) [duplicate]

I want to generate a random double number. My approach -

Random random = new Random();
double myDouble = random.nextLong() + random.nextDouble();

But The result is always a number between -9.99999.... to + 9.99999....

How to get a double number in the entire legal double range?

The question "Java: Generating a random double between the range of a negative double and a positive double"

does not solve my problem as it has lower and upper bound, but I want a result in the entire legal double range




Python how to create a random list only with even numbers?

I'm trying to create a random list with numbers from 0 to 10,000 (inclusive). I need to get a list with even numbers only.

This is my code:

from random import randint

def test(mini, maxx, quantity):
    myl = [randint(mini, maxx) * 2 for i in range(quantity)]
    return myl

print(test(0, 10000, 4))

If I try that, I go past the range of 10000 (because the * 2).

Also, I can only use the randint function.

How do I achieve the desired result?




Ranger Predicted Class Probability of each row in a data frame

With regard to this link Predicted probabilities in R ranger package, I have a question.

Imagine I have a mixed data frame, df (comprising of factor and numeric variables) and I want to do classification using ranger. I am splitting this data frame as test and train sets as Train_Set and Test_Set. BiClass is my prediction factor variable and comprises of 0 and 1 (2 levels)

I want to calculate and attach class probabilities to the data frame using ranger using the following commands:

Biclass.ranger <- ranger(BiClass ~ ., ,data=Train_Set, num.trees = 500, importance="impurity", save.memory = TRUE, probability=TRUE)

probabilities <- as.data.frame(predict(Biclass.ranger, data = Test_Set, num.trees = 200, type='response', verbose = TRUE)$predictions)

The data frame probabilities is a data frame consisting of 2 columns (0 and 1) with number of rows equal to the number of rows in Test_Set.

Does it mean, if I append or attach this data frame, namely, probabilities to the Test_Set as the last two columns, it shows the probability of each row being either 0 or 1? Is my understanding correct?

My second question, when I attempt to calcuate confusion matrix through

pred = predict(Biclass.ranger, data=Test_Set, num.trees = 500, type='response', verbose = TRUE)
table(Test_Set$BiClass, pred$predictions)

I get the following error: Error in table(Test_Set$BiClass, pred$predictions) : all arguments must have the same length

What am I doing wrong?




lundi 30 mars 2020

Mysql select random rows with multiple where conditions

This is my table example:

id     options     playlist_id
1      ...         7
3      ...         7
4      ...         9
11     ...         9
12     ...         7
14     ...         9

How do I select (for example) 3 random rows for each playlist_id and group results by playlist_id?

select id, options
from table
where playlist_id = 7 AND playlist_id = 9
group by playlist_id 
ORDER BY RAND()
LIMIT 3

I expect to return 3 random rows with playlist_id = 7 and 3 random rows with playlist_id = 9




Simulating a representative dataset in R

Suppose I have the following data frame:

sectoral_data <- data.frame(sector=c("a","b","c","d"),share=c(0.5,0.3,0.1,0.1),avg_wage=c(400,600,800,1000))

where "share" is the employment share in each sector. I want simulate (I guess that's the right word) the following data frame that would represent a sample of ten individuals from that economy:

personal_data <- data.frame(individual=c(1:10),
                          wage=c(rep.int(400,5),rep.int(600,3),rep.int(800,1), rep.int(1000,1)),
                          sector=c(rep("a",5),rep("b",3), rep("c",1), rep("d",1))
                          )

Any idea of an efficient way to do this and/or if there is a built in feature?




Does the secrets or os.urandom module in python provide seeding functionality?

I am looking for a cryptographically secure PRNG in python that provides deterministic seed functionality to develop a feistel network. Unfortunately since the random module is insecure I cannot use random.seed(). Does anyone know of any seed function calls using urandom, secrets, or Cyrpto.Random?




C: filling an array with random numbers in a range

I am trying accomplish the following tasks using C and arrays:

This is what I could do for now. I also need to print the output. What should I do or edit, thanks.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
    int n;
    printf("How many elements in array?:");
    scanf("%d",&n);
    int array0[n];
    for(int i = 0 ; i < n ; i++)
    {
      array0[i]= rand()%9 + 1;
    }

    int array1[10];

    for(int i = 0 ; i < 10 ; i++)
    {
      array1[i]= 0;
    }
    int index;
    for(int i = 0 ; i < n ; i++)
    {
      index = array0[i];
      array1[index-1]++;
    }
}



What is the last value of a chronometer: hour:minute:second:(what?)

Like the question above, what = milisecond or what = split-second (1/60 second?




how do i make a turtle move randomly

the turtle rec is the turtle i want to move randomly i have been trying some things but nothing has worked

import turtle

wn = turtle.Screen()
wn.setup(1440, 900)
wn.title("DVD loding Screen")

border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("black")
border_pen.penup()
border_pen.setposition(1440, 900)
border_pen.pendown()
border_pen.pensize(3)
border_pen.hideturtle()

rec = turtle.Turtle()
rec.color("red")
rec.shape("square")
rec.shapesize(5, 10)
rec.setpos(0, 0)
rec.speed(0)



turtle.done()



Does linqpad reuse the random seed between queries

For this code:

void Main()
{
    var testRandom = new TestRandom();
    testRandom.RandGen.Dump("Property1");
    testRandom.RandGen.Dump("Property2");
    TestRandom.rngStatic.Dump("Static field1");
    TestRandom.rngStatic.Dump("Static field2");
    testRandom.rngInstance.Dump("Instance field1");
    testRandom.rngInstance.Dump("Instance field2");
}

// Define other methods, classes and namespaces here

class TestRandom
{
    private static Random _rnd = new System.Random();
    public static int rngStatic = _rnd.Next();
    public int rngInstance = _rnd.Next();
    public int RandGen =>  _rnd.Next();
}

I get the following result in LinqPad:

Property1 167577867

Property2 2076433106

Static field1 1758463813

Static field2 1758463813

Instance field1 1875178546

Instance field2 1875178546

Static Field 1 and 2, Instance Field 1 and 2 show the same random number when run in the same query. This is as expected, however even when I re-run the query, Instance Field 1 and 2 will keep showing the same random number as in previous runs. So I suspect the seed is fixed, but couldn't confirm it.

Second Query run:

Property1 1860313679

Property2 1472007479

Static field1 1758463813

Static field2 1758463813

Instance field1 1370753000

Instance field2 1370753000




Randomize image once scrolled away

I have 17 different image classes that I am trying to swap between, one at a time, but only after the user scrolls it away. console.log() is also not working within this script.

View this code here: www.lobdell.me

<script type="text/javascript">
    window.addEventListener('scroll', function(e){
      if (window.scrollY >= 400 && window.scrollY <= 600){
      if (window.lastTime && Date.now() - window.lastTime < 1000) return;
      var roll = document.querySelector('#logoRoller');
        roll.classList.remove("logo1","logo2","logo3","logo4","logo5","logo6","logo7","logo8","logo9","logo10","logo11","logo12","logo13","logo14","logo15","logo16");
        roll.classList.add("logo"+ Math.floor(Math.random() * 16 + 1));
        window.lastTime = Date.now();
      }
    })

The randomize snippet is working on page refresh just fine, as shown here:

<script type="text/javascript">
document.getElementById("logoRoller").classList.add("logo"+ Math.floor(Math.random() * 16 + 1));



How do I sample and conduct a random permutation test for data with unequal list lengths in R?

I have an issue where I have 2 lists of unequal lengths, and I want to conduct a random permutation test of 5000 iterations on them to find out if the difference in means for both is significant.

dataset1v <- c(10, 10, 5, 10, 50, 2, 5, 50, 10, 40, 50, 20, 25, 20, 10, 10, 50, 10)
dataset2v <- c(50, 10, 20, 10, 40, 10, 20, 30, 10, 10, 80, 15)

All the tutorials on random permutation tests out there assume equal list lengths, and so they don't apply since a warning pops up when I run it with my lists. I've tried permutation.test.discrete among other options, but it's always the same issue: list length is unequal. Also, I would also like to resample each data into their original list lengths (18 and 12 each). I'm a beginner at coding for R, so I have spent hours upon hours trying to figure out how to solve this issue. Would appreciate some help and pointers in the right direction! Thanks!!




Python probability from sample

Here's what I'd like to do : There's 47% of girls amongst a population of 200 people. After choosing a random sample of 24 persons, I have to find the probability of having between 6 to 9 girls in that sample. I've been trying many ways but each of them just turn out wrong!

Could you help me out using NUMPY and LOOP?

Here's what I did :

import numpy as np 

population=np.random.choice(np.arange(0,2),size=200, p=[0.53, 0.47])

and I just don't know how to create a loop like : "for in range(6,9)" from my 24 persons sample ?

Thanks :)




dimanche 29 mars 2020

How to randomize images with tkinter and pillow?

in an attempt to develop a simple program I ran into a problem

the app should display a random image but its only randomized when I run the code not when i press the button to randomize it

import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
import random

root = tk.Tk()

Images = ["Image.png", "Image1.png", "Image2.png", "Image3.png"]

Canvas = tk.Canvas(root, bg="Blue", height=500, width=500)
Canvas.pack()

def Next():
    Random_Image=random.choice(Images)
    print(Random_Image)

    Random_Image_Original = Image.open(Random_Image)
    Random_Image_To_Resize = Random_Image_Original.resize((250, 250))
    Random_Image_Resize = ImageTk.PhotoImage(Random_Image_To_Resize)
    return Random_Image_Resize

Random_Image_Resize=Next()
Displayed_Image = Label(Canvas,  image=Random_Image_Resize)
Displayed_Image.place(height=250, width=250, y=125, x=125)

Button = tk.Button(root, text="Next", padx=20, pady=10, command=Next)
Button.pack()

root.mainloop()

if i try printing the output it does print random image names




Java: Math.random() returning values beyond range [closed]

new user/programmer here. I'm having trouble with the Math.random() method returning values beyond the specified range. I'm using the method to generate a random card and I get output such as 99 of hearts which is invalid, as there are only 14 ranks. I've noticed that a lot of the ranks generated are multiples of 11 if that helps, no issues with suits so far. Keep in mind I'm new and still learning basic programming and the following program isn't finished, so simple explanations/help would be greatly appreciated. Also having trouble getting the entire program into the code window on here, sorry.

    int rank = 2 + (int)(Math.random() * 15);
    int suit = (int)(Math.random() * 4);  



Confused with the random method Math.random();

I need help understanding how

50 + (int)(Math.random() * 50);

yields a random number somewhere between 50 and 99.




Array shuffle(using: RandomNumberGenerator) strange behavior

Since Xcode 11.4 the array doesn't get shuffled at all (regardless of the seed) when using the second implementation of the next function.

I don't get why, since both functions generate random numbers, even though the first only populates the least significant 32 bits of the random Int64.

You can try this minimal example in Swift Playgrounds, commenting out one of the two functions.

    import GameplayKit

    struct SeededGenerator: RandomNumberGenerator {
        static var shared: SeededGenerator?

        let seed: UInt64
        let generator: GKMersenneTwisterRandomSource

        init(seed: UInt64) {
            self.seed = seed
            generator = GKMersenneTwisterRandomSource(seed: seed)
        }

        // New alternative found to be working
        mutating func next() -> UInt64 {
            let next1 = UInt64(bitPattern: Int64(generator.nextInt()))
            let next2 = UInt64(bitPattern: Int64(generator.nextInt()))
            return next1 | (next2 << 32)
        }

        // Code previously in use that doesn't work anymore.
        mutating func next() -> UInt64 {
            return UInt64(bitPattern: Int64(abs(generator.nextInt())))
        }
    }

    var gen = SeededGenerator(seed: 234)

    var array = ["1", "2", "3"]
    array.shuffle(using: &gen)



How do I push random images from an array onto a canvas using ctx.drawImage?

I want to have a canvas that randomly displays a different animal-head every time the window is refreshed. Thus, I am trying to push a random image from my head array onto my canvas. As you can see below, this is my array.

var heads = ['animals/dog.svg', 'animals/fish.svg', 'animals/monkey.svg'];`

And here is the draw image function that I want the array to randomly push an image to:

ctx.drawImage(img, 60, 50); 

Here is the entirety of my code for context:

var heads = ['animals/dog.svg', 'animals/fish.svg', 'animals/monkey.svg'];

function gethead() { 
var number = Math.floor(Math.random()*heads.length);
document.write('<img src="'+heads[number]+'" />');}

window.onload = function () {
  var img = new Image();
  img.src = 'dog.svg';


  img.onload = function () {
      // CREATE CANVAS CONTEXT.
      var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 60, 50); 
      // DRAW THE IMAGE TO THE CANVAS.
   }
}

Can anyone explain how I can make this work?




How can I generate a random item from this element by calling the function?

I'm trying to get a random item from this list by calling the function that I made for it.
Nothing is working.

import random
def ColorText(colorText):
    colorText = ['Red', 'Blue', 'Green', 'Yellow', 'Black', 'Brown', 'Purple',
                 'Gray', 'Orange']

print(ColorText(random.choice(colorText)))



C#: How to assign random int values to variables?

I have made a dice class that includes a method which uses random.next to determine a random int value from 1-6.

Fairdice.cs:

 class FairDice
{

    //defining variable and property
    private Random rnd;
    public int Current { get; private set; }
    public FairDice()
    {
        rnd = new Random(Guid.NewGuid().GetHashCode());
        Current = 0;
    }

    public int FRoll()
    {
        Current = rnd.Next(1, 7);
        return Current;
    }

RollDice.cs that features a loop for printing.

static class RollDice
{
    public static void Roll(this int count, Action action)
    {
        for (int i = 0; i < count; i++)
        {
           action();
        }
    }
}

Program.cs includes this code, which prints out 5 random values between 1-6:

FairDice fd = new FairDice();
                    5.Roll(() => Console.WriteLine("Dice: " + fd.FRoll()));

Problem: I wish to assign the random values in each variable and store and save them in either a list or array for future use.

clarification:

lets say it prints out the numbers: 1, 2, 3, 4, 5 - i then wish to assign each value a variable: a = 1, b = 2, ... f = 5.

and/or simply store the values in an array {1, 2, 3, 4, 5}

Is there any way to do this?




How to generate a random such that the previou number does not repeat again?

Hi suppose I have this list l = [0,1,2,3,4,5,6,7,8,9]. I select a random number from this list using the random.choice() method. I get the output as 4. But for the second iteration, I don't need 4 again rather a different number from the remaining list say I got now 6. Now here I again want to add the4 back to the list and pop 6 and same for the next iteration to make sure that every time I get unique random value ut also making sure (if I am popping a number from the list) I add that number back to the list in the next iteration. For the record, is there any package available in python to provide such unique random number?




samedi 28 mars 2020

How to produce random number in C [closed]

I want to make a program that will provide me with different value of a variable every time I run the program. I have searched in google to get sample programs but found them worthless.




How to short uniform numbers of negative to positive in C? [closed]

I want to short uniformly numbers of -1 to 1 in c, but i just how to short positive numbers. I have searched, but i dint found anything about.




Python probability from a random sample [closed]

Here's what I'd like to do : There's 47% of girls amongst a population of 200 people. After choosing a random sample of 24 persons, I have to find the probability of having between 6 to 9 girls in that sample. I've been trying many ways but each of them just turn out wrong!

Could you help me out?

Thanks :)




Singleton random generator class generates always the same sequence of integers

The RandomGenerator class is meant to provide a single instance of the generator to be used among different objects. The current implementation provides a getInstance method to get the single instance of the class and a getGenerator method that should provide the single instance of the generator also. The problem with this implementation is that the provided sequence of numbers is always the same on different PCs.

RandomGenerator.cpp

#include "RandomGenerator.h"

RandomGenerator::RandomGenerator() : generator(std::random_device()()) {}

RandomGenerator *RandomGenerator::getInstance() {
    std::call_once(inited, [&]{
        instance = new RandomGenerator();
    });
    return instance;
}

std::mt19937& RandomGenerator::getGenerator() {
    return generator;
}

RandomGenerator.h

#include <mutex>
#include <random>

class RandomGenerator {
private:

    inline static RandomGenerator* instance;
    inline static std::once_flag inited;
    std::mt19937 generator;

    RandomGenerator();
public:
    static RandomGenerator* getInstance();
    std::mt19937& getGenerator();
};



Exclude random number in PHP WHILE KEEPING chr(49+rand(0,1))

I have a random number. 1 or 2 for sake of testing.

$rn = chr(49+rand(0,1)) ;

I want to then exclude that $rn from another $rn2. So if the first $rn is 2, I want the second $rn2 to be 1.

Currently this KIND OF works...

while( in_array( ($rn2 = rand(1,2)), array($rn) ) );

...although this is NOT correct as I NEED the

chr(49+rand(0,1))

to remain in the code, where the rand(1,2) currently is.




Placing objects randomly in a procedurally generated level

I was having trouble with placing different objects in my platformer 2d game, I tried some probability but it doesn't seems to work.Are there any resources or methods?




How to exclude random number from another random number in php

I have a random number. 1 or 2 for sake of testing.

$rn = chr(49+rand(0,1)) ;

I want to then exclude that $rn from another $rn2. So if the first $rn is 2, I want the second $rn2 to be 1.

I've tried things like,

$rn2 = chr(49+rand(0,1)) ;  
$rn2 != $rn ;

and

$rn2 = chr(49+rand(0,1, !$rn));



rand() always gives the same number [duplicate]

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



int main(void){
  int i,res;
  scanf("%d",&i);
  res = rand() % 36;
  printf("%d\n",res);
  if(i == 'O' && res % 2 == 1){//odd-win
    printf("WIN 2x\n");

  } 
  else if(i == 'E' && res % 2 == 0 && res != 0){ // even-win
    printf("WIN 2x\n");

  }
  else if(i == res){
    printf("WIN 35x\n");
  }
  else{
    printf("LOSE!\n");
  }


  return 0;
}

Well, I just made a simple roulette game but whenever I scan user's input, rand function always gives the same number 19. How can I fix this ?




Random number Generator with time interval

I cant code or anything but I need a random number generator wich will generate ever 2 seconds a random number between 1-77. I googled all day long but couldnt find anything like that. So does anybody know where I can find something like that or might actually be nice to code that for me ?




vendredi 27 mars 2020

how do i write a code for a button to generate random background color gradients

i want to add a button that generates random linear-gradients at the background. The code below generates linear gradients when i click on one button or the other.

var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var gradient = document.querySelector("body");
var css=document.querySelector("h3");
var random = document.getElementById("random")

css.textContent = gradient.style.background  = "linear-gradient(to right," + color1.value + "," + color2.value +")"; 

function setBackground(){
    gradient.style.background = "linear-gradient(to right," + 
    color1.value + "," + color2.value +")";
    css.textContent = gradient.style.background + ";"

}
color1.addEventListener("input", setBackground);

color2.addEventListener("input", setBackground);





How do I keep the score in my guessing game?

I want to reward the player with a point when they guess the random number correctly and retain that value when they decide to play again by recalling the game function and not have it reset back to zero. Thanks in advance.

# 'Guess Again' by Brent K Kohler AKA deusopus
def guess_again():
  import random
  n = random.randrange(1,6)
  t = 0
  s = 0
  print("Guess a number between 1 and 5")
  while True:
    i = int(input("Guess: "))
    if i == n:
      print("You Win!")
      print(f"The number was {n}")
      s += 1
      print(f"Score: {s}")
      break
    if t == 2:
      print("Sorry...")
      print("Game Over")
      print(f"The number was {n}")
      break
    else:
      print("Wrong")
      print("Try again")
      t += 1
  return
guess_again()

while True:
  x = input("Press 'enter' to play again. Type 'exit' to quit: ")
  if x.lower() != "exit":
    guess_again()
  else:
    print("Thanks for playing!")
    break



Looking for critique on my first Python Code and a way to keep variables

After just learning a bit of Python I tried coding something myself. I attempted to do a game of Blackjack, which is far from perfect, and still doesn't have some rules a real game has (in my game an ace is always 11 points, whereas in reality it can also be counted as 1 point).

There is however an issue that I'm having, simply because I don't understand it: I would like pack some of my code in methods and call them, but I'm having an issue with some variables. I use j as a variable for the card that would be on top of the deck. By default it is set to 4, because after the starting hands have been dealt the top card of the deck is the fourth one. Each time the player is dealt an additional card j is increased by 1. When the user finishes playing and it's the dealers turn I want to keep the current value of j and not revert to j being 4. How do I need to restructure my code in order to keep the changes that have been made to j in the while loop, if I put that loop into its own method? Is there a way I can "extract" a value of a variable from another method?

Additionally I want to develop good habits right from the start and tried using the best practices I know of, like using formatted Strings or using j += 1instead of j = j + 1. Are there any bad practices in my code, where can I improve? Here's the game in its current state, it seems to be working correctly, as I haven't found a way to break it. (A minor flaw is that you have to press "Y" or "y" for another card, but instead of having to press "n" or "N" for no more cards you can press anything)

import random

# the player plays first
# dealer goes second
# dealer hits on 16 and stands on 17

deck_of_cards = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
cards = {
    "Two": 2,
    "Three": 3,
    "Four": 4,
    "Five": 5,
    "Six": 6,
    "Seven": 7,
    "Eight": 8,
    "Nine": 9,
    "Ten": 10,
    "Jack": 10,
    "Queen": 10,
    "King": 10,
    "Ace": 11,
}


def drawing_a_card(card_num):
    i = card_num - 1
    drawn_card = deck_of_cards[i]
    return drawn_card


random.shuffle(deck_of_cards)
players_first_card = drawing_a_card(card_num=1)
players_second_card = drawing_a_card(card_num=3)

dealers_first_card = drawing_a_card(card_num=2)
players_total = cards[players_first_card] + cards[players_second_card]

print(f"Your first card: {players_first_card}")
print(f"Your second card: {players_second_card}")
print(f"Dealer's first card: {dealers_first_card}")
decision = input(f"You are standing at {players_total}, would you like another card? (Y/N) ")
if players_total == 21 :
    print(f"You hit 21! That's Blackjack, you win!")

j = 4
while decision.lower() == "y":
    if decision.lower() == "y":
        players_next_card = drawing_a_card(card_num=j)
        print(f"Your card: {players_next_card}")
        players_total += cards[players_next_card]
        j += 1
        if players_total > 21:
            print(f"That's a Bust! Your total was {players_total}")
            break
        elif players_total == 21:
            print(f"You hit 21! That's Blackjack, you win!")
            break
        else:
            decision = input(f"You are now standing at {players_total}, would you like another card? (Y/N) ")

k = j+1

if players_total < 21:
    print("The Dealer will now take his turn...")
    dealers_second_card = drawing_a_card(card_num=k)
    k += 1
    print(f"Dealer's cards are {dealers_first_card} and {dealers_second_card}")
    dealers_total = cards[dealers_first_card] + cards[dealers_second_card]
    if dealers_total == 21:
        print(f"The Dealer hit 21! That's Blackjack, the Dealer wins!")
    while dealers_total <= 16:
        print(f"Dealer's total is {dealers_total}, he'll take another card.")
        dealers_next_card = drawing_a_card(card_num=k)
        print(f"The Dealer's card: {dealers_next_card}")
        dealers_total += cards[dealers_next_card]
        k += 1
    if dealers_total == 21:
        print(f"The Dealer hit 21! That's Blackjack, the Dealer wins!")
    elif dealers_total > 21:
        print(f"The Dealers total is {dealers_total}, he has bust and you win!")
    if dealers_total >= 17:
        print(f"The Dealer stands at {dealers_total}")
        if dealers_total < players_total:
            print(f"Your total is {players_total}, which is higher than the Dealer's {dealers_total}, you win!")
        elif dealers_total == players_total:
            print(f"You and the Dealer are both standing at {dealers_total}, it's a draw!")
        elif dealers_total > players_total:
            print(f"The Dealer beats your {players_total} with his {dealers_total}, you lose!")




Display random div from X divs selected by CSS-Class

I have, on a homepage, X html div elements in one page, with X different classnames:

  • class="home-1"
  • class="home-2"
  • class="home-3"
  • class="home-4"
  • etc.

My goal is, to dislpay only one of these "divs" randomly, so when the page is refreshing, everytime a randomly different div is displayed. The rest should be hidden. it would be very nice if the same div was not shown twice in a row I think, i can't do this, only with css.

what i manually can do is

.home-1 { display: none; }
.home-3 { display: none; }
.home-4 { display: none; }

So in this Case home-2 is displayed.

Of course i want that automated with javascript, can someone please help me?

that yould be very nice!




Numpy: Generate multiple random samples from parameter arrays

I have three parameter arrays, each containing n parameter values. Now I need to draw m independent samples using the same parameter settings, and I was wondering if there is an efficient way of doing this?

Example:

p1 = [1, 2, 3, 4], p2 = [4,4,4,4], p3 = [6,7,7,5]

One sample would be generated as:

np.random.triangular(left=p1, mode=p2, right=p3)

resulting in

[3, 6, 3, 4.5]

But I would like to get m of those, in a single ndarray ideally.

A solution could of course be to initiate a sample ndarray of size [n, m] and fill each column using a loop. However, generating all random values simultaneously is generally quicker, hence I would like to figure out if that's possible.

NOTE: adding the parameter 'size=(n,m)' does not work for array valued parameter values




python list with random values and random numbering [closed]

I would like to do a list with random values and random positions between sqrt(2) and 5e.

I am a beginner and can't find a solution for the problem.

Thank you.




jeudi 26 mars 2020

I've Invented a data encryption method. I wish to know if it's safe

I'm not 100% sure if this is the best place to ask this. If so, can you please suggest a better site to me.

I've written a program in python 3 to encrypt data. But it uses a completely new data encryption method I made. And I wish to know whether any of you think it's secure enough for any practical use. Or, if you see any flaws in it.

The basic gist of the program is this:

The program converts each character of the data into their ASCII numbers. Then to encrypt it, it "randomly" adds a large number to the original ASCII number of each character.

But it's not random, because the seed has been set using the random.seed() function. And The seed the program sets it to is determined by the key.

And then it shuffles each digit.

Due to lack of a better name, I called this method SABONK. It doesn't stand for anything.


import random


def ASCII(x): #converts string to ASCII and returns as a list.
    return [ord(c) for c in x]

def ASCII_char(x): #turns a list of ASCII numbers back into text and in a string
    try:
        result = ""
        for i in x:
            result = result + chr(i)
        return result
    except:
        return None

def modifier(key): #returns the "modifier" value used for encryption
    return len(key)*sum(key)

def pad(n, x): #adds 0 to front of number so the length is as required.

    if len(str(x)) >= n: return x
    return ("0"*(n-len(str(x))))+str(x)

class SABONK:
    def __init__(self, key, max=856076, min=100, length=7):
        self.keyString = key
        self.key = ASCII(key)
        self.m = modifier(self.key)

        self.length = 7
        self.maxLength = max
        self.minLength = min

    def setKey(self, newKey):
        pass

    def Encrypt(self, data, password=None): #the main encrypt function
        if data == "": return ""
        #setting up variables needed.
        key = password
        if password == None: key = self.key #If password is None, use the password saved in the class.

        return self.shuffle(self.combine(self.basicEncrypt(data, key)))

    def Decrypt(self, data, password=None, toText=True): #the main encrypt function
        if data == "": return ""
        #setting up variables needed.
        key = password
        if password == None: key = self.key #If password is None, use the password saved in the class.

        if toText: return ASCII_char(self.basicDecrypt(self.disjoin(self.unshuffle(data)), key)) #if toText is True, the function wil return decrypted text and translate it back to characters.
        return self.basicDecrypt(self.disjoin(self.unshuffle(data)), key)#If not, will return list of ASCII numbers


    def basicEncrypt(self, data, password=None): #does the 1/3 part of the encryption process.
        #setting up variables needed.
        key = password
        if password == None: key = self.key #If password is None, use the password saved in the class.

        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the encryption process.
        result = []
        data = ASCII(data)

        for x in data:
            random.seed(key[current]*m)#setting the seed
            result.append(pad(self.length, random.randint(self.minLength, self.maxLength)+x))#encrypted character to result

            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            else: current +=1

            m += x*random.randint(0, 100000) #chaning the modifier

        return result


    def basicDecrypt(self, data, password=None): #does the 1/3 part of the decryption process.
        #setting up variables needed.
        key = password
        if password == None: key = self.key#If password is None, use the password saved in the class.

        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the encryption process.
        result = []

        for x in data:
            random.seed(key[current]*m)#setting the seed
            d = x-random.randint(self.minLength, self.maxLength)
            result.append(d)#encrypted character to result

            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            else: current +=1

            m += d*random.randint(0, 100000) #chaning the modifier

        return result

    def combine(self, data):#combine the numbers from the encrypted data
        result = ""
        for x in data: #going through data list, converting it into string and joining it into single string to retrun
            result = result + str(x)
        return result

    def disjoin(self, data):#disjoin the list of data that was combined by the "combine" function
        l = self.length
        result = []

        while len(data) != 0: #going thorugh the data, converting it into intager and putting it in result list
            result.append(int(data[:l]))
            data = data[l:]
        return result

    def shuffle(self, data, password=None): #data should be a string
        #setting up variables needed.
        key = password
        if password == None: key = self.key#If password is None, use the password saved in the class.

        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the random.seed.
        result = []

        l = (len(data) - 1)

        #firist we split the data string into a list, so that every elemnt in the list is a single number
        for x in data:
            result.append(x)


        #And now we shuffle the list
        for x in range(6*len(data)):
            random.seed(key[current]*m)#setting the seed

            i1 = random.randint(0, l) #choosing the two indexes of the data list to swap
            i2 = i1
            while i2 == i1: i2 = random.randint(0, l) #this makes sure i2 is different from i1
            result[i1], result[i2] = result[i2], result[i1]

            current +=1
            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            m += 1

        return "".join(result)

    def unshuffle(self, data, password=None): #data should be a string
        #setting up variables needed.
        key = password
        if password == None: key = self.key#If password is None, use the password saved in the class.
        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the random.seed.
        result = []
        actionsList = []
        l = (len(data) - 1)

        #firist we split the data string into a list, so that every elemnt in the list is a single number
        for x in data:
            result.append(x)

        #figure out list of swaps the shuffle dunctionn would have taken.
        for x in range(6*len(str(data))): 
            random.seed(key[current]*m)#setting the seed

            i1 = random.randint(0, l) #choosing the two indexes of the data list to swap
            i2 = i1
            while i2 == i1: i2 = random.randint(0, l) #this makes sure i2 is different from i1

            actionsList.append([i1,i2])
            current +=1
            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            m += 1

        actionsList = list(reversed(actionsList))#Then reverse the list, so the swaps can be undone.


        #And now we unshuffle the list
        for x in range(6*len(str(data))):
            result[actionsList[x][0]], result[actionsList[x][1]] = result[actionsList[x][1]], result[actionsList[x][0]]

        return "".join(result)


if __name__ == "__main__":
    key = input("Please type out key: ")
    s = SABONK(key)
    text = input("Please type out text to encrypt: ")
    print("You have typed: " + text)
    e = s.Encrypt(text)
    print("Text Encrypted: "+ e)
    print("Text Decrypted: "+ str(s.Decrypt(e)))




Generate Random Number and add it to the List C# with for loop

Below my Do method inside it I want to generate a random number and then use for loop to add that number. Anybody can help me to finish the loop?

 void IInventoryCommand.Do()
    {
        TargetList = new List<InventoryItem>();
        string[] randomNumber = { "First", "Second", "Third", "Fourth", "Fifth" };



        var rnd = new Random();
        number = rnd.Next(1, 6);
        int size = 5;

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



        }
    }



Random numbers in a constructor of an object array

Firstly, sorry if it's a silly question, but I have recently learn how to deal with classes. My problem is that I've created a constructor which gives every data member a random number, with the following syntax:

#include <random>

...

//Constructor
cSystem::cSystem(void)
{
//Range of random numbers
double lower_bound = -100;
double upper_bound = 100;
std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
std::default_random_engine re;

/*Initialization of data members*/
sMass=1.0014;
sPositionX= unif(re);
sPositionY= unif(re);
}

But then, I want to create an array of these "systems" in my main function

int main (void)
{
cSystem systems[numsist]; //numsist is a constant defined to be 1000

//Function that writes its characteristics in a file using a method that returns positions
getPositions(systems);

return 0;
}

But in the file, I just get

-73.6924    -8.26997
-73.6924    -8.26997
-73.6924    -8.26997

I thought that I was going through the constructor for every element of the array, giving it a different random value, but it seems like a single value is given at the beginning and then it is repeated throughout the vector. What can I do to get a constructor that initializes every element in a random way?

Note: I also get the same values everytime I run the program, I suppose that the seed does not change, why is that the case?




Random strings with random words from a text - Python

I am working with Python and I would like to create a function that returns me '100' random strings with some random words from a text (every string should have a length from 2 to 5 words - lenght randomly choosen by Python as well).

PS. the words can be repeated

text= ['word_1, word_2, word_3, word4, word5, word6, word7 ... word999]

str_1 = [word3, word2]

(...)

str_n = [word4, word5, word,1, word6]



Using random.choice() with classes

As a predisposition to this post, I'm very new to programming. I've been a sound engineer for the last 5+ years but due to lack of work in my area I've decided to go back to school for software development. Classes start in September but while I have downtime due to the state of the world right now (Coronavirus), I figured I'd use my time to my advantage and get a head start. I've decided to start with python because the syntax is pretty simple and I have dabbled in it years ago when I was a kid.

Anyway, I was following along with youtube tutorials and just copying peoples code and felt like i wasn't learning anything. So once I had a basic concept of enough fundamentals to get started I figured I'd just started coding something and learn by trial and error, and documentation reading. I started to program a simple text based RPG game.

The problem I have encountered is when using the random.choice() function along with a list of objects representing monsters, when a monster is chosen with a certain set of stats and level etc, it locks them in as that initial choice. for example.

I have a list of two monster objects like so :

monster = [Monster_Blob("Blob", 0, 0, 0, 0, 0), Monster_Skeleton("Skeleton", 0, 0, 0, 0, 0)]
pick = random.choice(monster)

Their stats inside the class such as Level are determined by random integers. Then along with that the player has a search function:

def monster_search():
    global pick
    pick = random.choice(monster)
    print()
    print("You found a " + pick.Name)
    print()
    print("Name: " + str(pick.Name), "Level: " + str(pick.Lvl))
    print("HP: " + str(pick.BaseHP), "MP: " + str(pick.BaseMP))
    print("Str: " + str(pick.BaseStr), "Dex: " + str(pick.BaseDex))
    battle()

When the monsters HP is reduced to 0 and the battle function ends, when you call the search function again it repeats the same 2 monsters with the same stats that were locked in during the initial search. Is there something else I should be doing other than just defining pick as a random choice of monster during the search function?

I know this is pretty basic stuff but its had me stuck long enough that I took the time to write this out.

Thanks for reading.




I really can't help to get my head around this homework I was given

So because of the Corona virus, my university is locked down, and we use e-learning. I study programming. I was given a homework in Java, and it goes like this: "Make a runnable class, in wich you create 10 rectangle type objects (so multiple instance of one object), store their references in a block, and randomly generate the rectangle's sides." I just can't get my head around this. Can anyone help?




Mean Squared Displacement for Random Walk in Python

I've been trying to compute the mean squared displacement of a random walk. The random walk function is mult_RW and outputs an array of 2d array's that are random walks starting at (0,0) that have step size 1 and step in a random direction determined by a random theta. I want to calculate the MSD of this and have tried doing so below. I'm fairly sure this is wrong but I can't figure out why as I'm fairly new to coding. Firstly, I'm not actually sure how to compute the MSD in python but my definition is:

  • MSD(δt) =〈|r(t+δt)−r(t)〉2t,ensemble

where ensemble means the mean over all the random walks I've computed and the rest of it means:

  • 〈|r(t+δt)−r(t)〉2t=(1/Nt) ∑ k|r(k+δt)−r(k)|2

My code is as follows:

def msd_calculate(N,steps):

big_array = mult_RW(N,steps) # gets our array

msd = np.zeros(steps-1) # creates an array of zeros to store the MSD for each delta*t

for i in range(1,steps-1): # iterates over each step size 
    for array in big_array: # iterates over each array
        s = [] # creates a list for the
        x, y = zip(*array) # creates seperate arrays for x and y

        x_splice, y_splice = x[1::i], y[1::i] # selects the values that are 1+i*dt
        x_splice = np.array(x_splice)
        y_splice = np.array(y_splice)
        x_diff, y_diff = np.diff(x_splice), np.diff(y_splice) # finds r(k+dt) - r(k)
        r = np.sqrt(np.square(x_diff) + np.square(y_diff)) # finds interior of sum |r(k+dt)    - r(k)|**2
        r_sq = r**2
        s.append(r_sq) #appends the value to the list so we can then calculate the mean
        '''Ignore the below commented bit I'm pretty sure that's wrong''' 
        #             r = np.sqrt(np.square(x) + np.square(y)) # calculates r for each 
        #             splice = r[1::i]
        #             r_diff = np.diff(splice)
        #             diff_sq = r_diff**2
        #             s.append(diff_sq)
    s = np.array(s)
    msd[i] = np.mean(s) # calculates mean of all of them

# Plotting the MSD function

z = [j for j in range(1,steps)] 
plt.figure(figsize=(12,12))
plt.plot(z,msd,'-b',label='MSD')
plt.xlabel(r'$\deltat')
plt.ylabel('MSD')
plt.title('MSD calculation for {} iterations of the Random Walk for {} steps'.format(N, steps))
plt.show()

return msd

If anyone can tell me whether my definition of MSD is wrong or whatever else it may be that would be amazing thank you. Also, if my code for my random walk is required (I've checked and it 100% works) I can upload that too.




Efficient way to generate a random alphabet in Python skewed towards popular letters? [duplicate]

I want to generate a random letter but the randomness is skewed towards how popular the letter is. For example 'E', is the most common letter in the English alphabet, so it should have the highest probability.

I found this frequency table to define the popularity of a letter.

My naive approach is as follows:

import random

popularity_dict =  {'E': 21912, 'T': 16587, 'A': 14810, 'O': 14003, 'I': 13318, 'N': 12666, 'S': 11450, 'R': 10977, 'H': 10795, 'D': 7874, 'L': 7253, 'U': 5246, 'C': 4943, 'M': 4761, 'F': 4200, 'Y': 3853, 'W': 3819, 'G': 3693, 'P': 3316, 'B': 2715, 'V': 2019, 'K': 1257, 'X': 315, 'Q': 205, 'J': 188, 'Z': 128}
#scraped from the given link

letter_list = []
for letter, popularity in popularity_dict.items():
    letter_list.extend([ letter] * popularity)


print(random.choice(letter_list))

I was wondering if there was a more effiecient approach to the problem




There is problem with word randit in my code

I tried to use moudul random in this code but problem is in word random. I'm not sure how to use random color, width or height of window.

from random import*
colours=["blue","red","yellow","green","purple","orange","violet","gray"]
t=Tk()
t.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t1=Tk()
t1.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t2=Tk()
t2.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t3=Tk()
t3.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t4=Tk()
t4.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t5=Tk()
t5.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t6=Tk()
t6.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t7=Tk()
t7.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t8=Tk()
t8.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t9=Tk()
t9.config(bg=colours[randit(0,7)],width=randit(0,200),height=randit(0,500))
t.mainloop()```




R function for manipulative field experiment design - Plant ecology

I am a plant ecologist and I would like to design a field manipulative experiment. To achieve a good degree of randomisation in the disposition of plants inside experimental plots, I would like to use R (with which I'm familiar) but I cannot seem to find a package flexible enough for my purpose, so I'm considering writing a formula but I don't know where to start. The picture is a schematisation of the design: in total there would be 6 plots, each containing 24 different plant species. In total I have 36 plant species, from which I would like to randomly sample 24 species per plot (with high variation between plots). Each species should be present in 4 out of the 6 plots but in different positions, twice along the border (in two of the warm colours) and twice in the core area (once per cold colour); in the picture I visually explain what I mean using 4 different species (A,B,C,D).

Could anyone suggest a way to do it or some insight to write the function? Thank you very much!!

Plot design




A weighted version of random.randint

I would like to choose a random integer between a and b (both included), with the statistical weight of c.

c is a value between a and b.

Which is the most efficient way to apply the weight factor c to random.randint?

The closest I got was this question, but there is a big difference:

I have only one single statistical weight c, not a statistical probability for every value between a and b.

Example:

a = 890
b = 3200

c = 2600

print(random.randint(a,b))

>>>> supposed to result most frequently in a value around 2600

I don't really care about the distribution between a and b, as long as there is a weight on c. However, a Gaussian distribution would be appreciated.




Can't get random numbers in c

I am trying to get two random numbers between 0 and 11 but i get the same number whenever i execute my code. These numbers are 7 and 10. Here is my code:

void track_machine(){
        int X = 0,Y = 0; //Coordinates
        double D = 0,R = 0; //Distance and replacement
        refresh_position(&X,&Y,&D,&R);
        printf("%d\n",X);
        printf("%d\n",Y);
}
void refresh_position(int *X, int *Y, double *D, double *R){
        *X = rand()%12;
        *Y = rand()%12;
}



Getting c core dumped error and trying to get random integers [duplicate]

I am trying to get random numbers between 0 and 11 but I am getting segmentation fault core dumped error here is my code:

void track_machine(){
        int *X = 0,*Y = 0; //Coordinates
        double *D = 0,*R = 0; //Distance and replacement
        refresh_position(X,Y,D,R);
        printf("%d",*X);
        printf("%d",*Y);
}
void refresh_position(int *X, int *Y, double *D, double *R){
        *X = rand();
        *Y = rand();
}

I am running the track_machine() from my main function then i get an error.




Python - define a function with probability distribution in arguments

In python, I would like to write a function which takes in arguments the name of a distribution (from scipy.stats), and returns an array of samples from that distribution.

How would I do that? I guess I would have to convert a string in some sense.

In addition, from specifying the name of a distribution in argument, how could I use its cdf or density in the function?




How to make 10 different windows (colors and sizes) from random module using tinkter?

I have to write code that opens 10 windows (from tkinter import) that are different color and sizes with modul random. Can somebody help?




mercredi 25 mars 2020

Choosing a function randomly and calling it with the appropriate attributes in Python

The answers to Choosing a function randomly tell us how to pick and call a random function from a list using random.choice.

But what if the functions in the list take different attributes? How do we call the function with the appropriate attributes?

Example:

from random import choice

def fun_1():
    ...
def fun_2(x: int):
    ...
def fun_3(y: bool):
    ...

my_integer = 8
my_boolean = True

random_function_selector = [fun_1, fun_2, fun_3]

print(choice(random_function_selector)(???))

The function fun_1 takes no attributes. Whenever fun_2 is selected, I want to call it with my_integer, and whenever fun_3 is selected, I want to call it with my_boolean.

What do I put in the brackets in the last line?

Do I have to rely on if statements to check what random function was selected, and choose the appropriate attribute based on that? Or is there a shortcut?




C++ Magic 8 Ball Program

I have to make a program on C++ that simulates a Magic 8 ball, and I am close to finishing, but whenever I compile it is missing some of the output? It doesn't even show any errors or warning, but it's still missing some of the output. At first I had the functions as char types, but I changed it to string and they compile now, but are missing some text.


#include <iostream>             // to use cin and cout
#include <typeinfo>             // to be able to use operator typeid
#include <iomanip>
#include <time.h>

// Include here the libraries that your program needs to compile



using  namespace  std;

// Ignore this; it's a little function used for making tests
inline void _test(const char* expression, const char* file, int line)
{
    cerr << "test(" << expression << ") failed in file " << file;
    cerr << ", line " << line << "." << endl << endl;
}
// This goes along with the above function...don't worry about it
#define test(EXPRESSION) ((EXPRESSION) ? (void)0 : _test(#EXPRESSION, __FILE__, __LINE__))

// Insert here the prototypes of the functions
int randNumGen(int highRange, int lowRange);

string fortuneTellerA(int randomNumber);

string fortuneTellerB(int randomNumber);

    int main()
 {
    // Declare a variable named randomNumber that holds whole numbers
    int randomNumber;

    // Declare a variable named lowRange that holds whole numbers and initializes it to 0
    int lowRange = 0;

    // Declare a variable named highRange that holds whole numbers and initializes it to 4
    int highRange = 4;

    // Seed the random number generator using expression 1) on my handout
    srand(static_cast<int> (time(NULL)));

    // Prompt the user to enter a question
    cout << "Ask the Magic 8 Ball a question: ";

    // Ignore the user input
    cin.ignore(100, '\n');

    // Call function randNumGen() to generate a random number and assign it to randomNumber
    randomNumber = randNumGen(highRange, lowRange);

    // Display title "Part A solution"
    cout << endl << "Part A solution" << endl << endl;

    // Display the message shown below
    //  "Answer: “, call function fortuneTellerA() to get the answer
    cout << "Answer: " << fortuneTellerA(randomNumber);

    // Display title "Part B solution"
    cout << "Part B solution" << endl << endl;

    //Displays the message shown below
    //  "Answer: “, call function fortuneTellerB() to get the answer
    cout << "Answer: " << fortuneTellerB(randomNumber) << endl << endl;

    system("pause");

    // Do NOT remove or modify the following statements
    cout << endl << "Testing your solution" << endl << endl;

    test(randomNumber >= 0 && randomNumber <= 4);           // Incorrect random number (out of range)

    test(fortuneTellerA(0) == "Yes");                       // Incorrect answer
    test(fortuneTellerA(1) == "Maybe");                     // Incorrect answer
    test(fortuneTellerA(2) == "No");                        // Incorrect answer
    test(fortuneTellerA(3) == "Ask again later");           // Incorrect answer
    test(fortuneTellerA(4) == "I don't know");              // Incorrect answer
    test(fortuneTellerA(14) == "I don't know");             // Incorrect answer

    test(fortuneTellerB(0) == "Yes");                       // Incorrect answer
    test(fortuneTellerB(1) == "Maybe");                     // Incorrect answer
    test(fortuneTellerB(2) == "No");                        // Incorrect answer
    test(fortuneTellerB(3) == "Ask again later");           // Incorrect answer
    test(fortuneTellerB(4) == "I don't know");              // Incorrect answer
    test(fortuneTellerB(14) == "I don't know");             // Incorrect answer

    system("pause");
    return 0;
}

//************************  Function definitions  *************************
// Read the handout carefully for detailed description of the functions that you have to implement

// This function generates a random number within a specified range.
// It receives two whole numbers : the first one is the upper boundary and
// the second one is the lower boundary used to generate the random number.
// Returns the random number generated using expression 2) on my handout

int randNumGen(int highRange, int lowRange)
{
    return (rand() % (highRange - lowRange + 1)) + lowRange;
}


// Thisfunction uses multi - branch if - else statements to determine the answer to be 
// returned based on the number received.
// It receives the random number(whole number) and returns the corresponding answer
// based on the table shown on my handout
//
// Important: in this solution make your function directly return the answer in each
// branch of the multi - branch if - else statements.
string fortuneTellerA(int randomNumber)
{
    if (randomNumber == 0)
        cout << "Yes";
    else if (randomNumber == 1)
        cout << "Maybe";
    else if (randomNumber == 2)
        cout << "No";
    else if (randomNumber == 3)
        cout << "Ask again later";
    else if (randomNumber == 4)
        cout << "I don't know";

    return 0;
}


// Thisfunction uses switch statements to determine the answer to be 
// returned based on the number received.
// It receives the random number(whole number) and returns the corresponding answer
// based on the table shown on my handout
//
// Important: in this solution declare a local variable that holds text and assign
// the corresponding answer in each case of the switch statement. Upon exiting the
// switch return the value in the local variable.

string fortuneTellerB(int randomNumber)
{
    switch (randomNumber)
    {
    case 1:
        cout << "Yes";
        break;
    case 2:
        cout << "Maybe";
        break;
    case 3:
        cout << "No";
        break;
    case 4:
        cout << "Ask again later";
        break;
    case 5:
        cout << "I don't Know";
        break;
    }

    return 0;
}



How can I put random number values into "rgb()" for the svg "fill" attribute?

I have an svg element on my website, and I want to animate it so that it changes from a random color value to another random color value. What I have right now looks like this:

<?xml version="1.0" standalone="no"?>
<svg width="8cm" height="3cm" viewBox="0 0 800 300" xmlns="http://www.w3.org/2000/svg">
  <desc>Example anim01 - demonstrate animation elements</desc>
  <rect x="1" y="1" width="900" height="400"
        fill="none" stroke="none" stroke-width="2" />
  <!-- The following illustrates the use of the 'animate' element
        to animate a rectangles x, y, and width attributes so that
        the rectangle grows to ultimately fill the viewport. -->
  <rect id="RectElement" x="300" y="100" width="300" height="100"
        fill="rgb(0,255,0)"  >
    <animate attributeName="fill" begin="0" dur="1.3"
    fill="remove" from="rgb(0,255,0)" to="rgb(255,0,0)" repeatCount="indefinite"/>
    <animate attributeName="x" begin="0s" dur="1.3s"
             fill="freeze" from="300" to="0" repeatCount="indefinite"/>
    <animate attributeName="y" begin="0s" dur="1.3s"
             fill="freeze" from="100" to="0" repeatCount="indefinite"/>
    <animate attributeName="width" begin="0s" dur="1.3s"
             fill="freeze" from="300" to="800" repeatCount="indefinite"/>
    <animate attributeName="height" begin="0s" dur="1.3s"
             fill="freeze" from="100" to="300" repeatCount="indefinite"/>
    
    
  </rect>
  <!-- Set up a new user coordinate system so that
        the text string's origin is at (0,0), allowing
        rotation and scale relative to the new origin -->
  <g transform="translate(100,100)" >
    <!-- The following illustrates the use of the 'set', 'animateMotion',
         'animate' and 'animateTransform' elements. The 'text' element
         below starts off hidden (i.e., invisible). At 3 seconds, it:
           * becomes visible
           * continuously moves diagonally across the viewport
           * changes color from blue to dark red
           * rotates from -30 to zero degrees
           * scales by a factor of three. -->
    <text id="TextElement" x="0" y="0"
          font-family="Verdana" font-size="35.27" visibility="hidden"  >
      Buy our crap!
      <set attributeName="visibility" to="visible"
           begin="0s" dur="1.3s" fill="freeze" repeatCount="indefinite"/>
      <animateMotion path="M 0 0 L 100 100"
           begin="0s" dur="1.3s" fill="freeze" repeatCount="indefinite"/>
      
      <animateTransform attributeName="transform"
           type="rotate" from="-30" to="0"
           begin="0s" dur="1.3s" fill="freeze" repeatCount="indefinite"/>
      <animateTransform attributeName="transform"
           type="scale" from="0.5" to="2" additive="sum"
           begin="0s" dur="1.3s" fill="freeze" repeatCount="indefinite"/>
    </text>
  </g>
</svg>

But what I want is instead for the rectangle to be assigned a random color value (something like "rgb(random#,random#,random#)")

How would I go about doing that to make sure that every single color is possible?




In Python is it possible to execute while loops in a random order?

I made a password generator that creates a random set of numbers, letters, and symbols, but the results are always printed in that order. Each character type is created through its own while loop and I'm wondering if there is a way to for the while loops to execute at random rather than in a top down order. Thank you!

import random

alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet_up = alphabet.upper()
numz = '0123456789'
symz = '~@!#$%&*'
alpha_character_type = [alphabet, alphabet_up]
index_counter_num = 0
index_counter_letter = 0
index_counter_symz = 0
print('Welcome to password generator')
pw_length = int(input('Please enter password length: '))
if pw_length < 6:
    pw_length = int(input('Password must be at least 6 characters long. Please enter a larger number: '))
letters_num = int(input('Enter desired number of letters: '))
numbers_num = int(input('Enter desired number of numbers: '))
if letters_num + numbers_num>= pw_length:
    print('Please leave room for symbols. Reduce the amount of letters and/or numbers')
    letters_num = int(input('Enter new desired number of letters: '))
    numbers_num = int(input('Enter new desired number of numbers: '))
    characters_left = pw_length - letters_num - numbers_num
    print('Thank you. There is now', characters_left, 'spaces left for symbols. Your password will now be generated' )
print('Here is your password: ')
#NUMBERS LOOP
while index_counter_num < numbers_num:
    selected_numz = random.choice(numz)
    index_counter_num += 1
    print(selected_numz, end= '')
#LETTERS LOOP
while index_counter_letter < letters_num:
    style = random.choice(alpha_character_type)
    style_character = random.choice(style)
    selected_letters = style_character
    index_counter_letter += 1
    print(selected_letters, end= '')
# SYMBOLS LOOP
characters_left = pw_length - letters_num - numbers_num
while index_counter_symz < characters_left:
    selected_symz = random.choice(symz)
    index_counter_symz += 1
    print(selected_symz, end = '')



How to generate random numbers in C with an appropriate spacing?

I had to generate a given number of float random values in the range [1,10] for some code. However, due to some constraints, the spacing between the random numbers has to be at least dx(given).

I'm using code blocks. (float)rand()/(float)(RAND_MAX/(10)) generates random numbers in the range.

Now, to achieve the desired spacing as said earlier, any suggestions for a simple strategy easily implementable in C?




How to generate an input file for diehard test?

I've been trying to create an input file specifically for ASC2BIN.exe and it says:

You must first create the ascii file.  To do that,
generate your 32-bit integers and write them to a file,
in hex format, 80 characters (ten 32-bit integers) per
line.

So I understand that my RNG code will return an integer output (line by line in this case). So if I want to test it with Diehard, I need to convert them into the proper binary file. To do so, we have ASC2BIN.exe here which aims to create the binary file.

FOr example, my RNG outputs look like:

2
3
4
5
.
.

Follow to the message above of ACI2BIN.exe, I have to:

1, generate your 32-bit integers as follows

2 -> '00000000000000000000000000000010'
3 -> '00000000000000000000000000000011'
4 -> '00000000000000000000000000000100'
5 -> '00000000000000000000000000000101'

2, write them to a file, in hex format????

Does it seem I have to again convert the binary to hex format? if so, how can I do that? it sounds does not make sense to me. Or do I have to convert the file format to hex? I'm stuck here!

3, 80 characters (ten 32-bit integers) per line

okay, it's clear that 234567891011 in 32-bit integers should be in the same line under the "hex format"?




Generating big random JSON dataset for ElasticSearch

I am currently required to generate a few hundred GB worth of test data for an ElasticSearch index for load testing. This means hundreds of millions of "docs".

The format I need to generate looks like:

{
field 1 : <ip>
field 2 : <uuid>
field 3 : <date>
field 4: <json-array of string>
...
...
}

for around 40-50 fields per doc. Generated data needs to match the index template for the specific index I am required to test.

Ok, so sounds straight forward right? A normal JSON dataset generator that can handle generating a few hundred million Json docs is the way to go provided I can find one that supports format.

The problem is that the ES Bulk upload API requires upload to be supplied following way. For EACH doc, first a "command json" containing meta-data for a doc, then the json doc itself:

POST _bulk
{ "index" : { "_index" : "test", "_id" : "1" } }
{ "field1" : "value1" }

The one free solution that look like it might support generating huge datasets only support generating Json with uniform format. Which means I can't make it generate the command followed by the doc.

So I tried to generate using my own bash script based on some pre-existing data (I randomize doc-id and some other fields) to generate data. But the problem with that is I need to run my bash script in parallel up to 100s of times at once to generate the data in a timely manner. And the /dev/urandom in bash is "conflicting", as in it is generating the -same- random data across different scripts when ran in parallel when I need the doc-id to be unique.

This is getting long, but any help for either

1) A free solution which can generate the large datasets in JSON and in the format I need

OR

2) A solution for bash random generation process when ran in parallel

Would be appreciated. Thanks.




Python program fails to run (pane is dead) using AWS Cloud9

I am new too python and had some basic programs earlier work flawlessly. However this simple lottery generator is failing too compile. I have little errors with indentation that I fixed but it still fails to run. Below is my code for this project. I am having trouble seeing where or why this will not run correctly.

import random 
def main():
    print('**** Welcome to the Pick-3, Pick-4 lottery number generator *********')
    print('Select from the following menu:')
    displayMenu()
    menu=int(input())
    while(menu==1 or menu==2):
    displaySelection(menu)
    print(lotteryNumber(menu))
    displayMenu()
    menu=int(input())

    displaySelection(menu)
    print('Thanks for trying the Lottery Application.')
    print('*********************************************************')

def displayMenu():
    print('Select from the following menu:')
    print('1. Generate 3-Digit Lottery number')
    print('2. Generate 4-Digit Lottery number')
    print('3. Exit the Application')
    return

def displaySelection(selected):
    if (selected ==1):
        print('You selected 1. The following 3-digit lottery number was generated:')
    elif(selected==2):
        print('You selected 2. The following 4-digit lottery number was generated:')
    else:
        print('You selected 3.')
        return

def lotteryNumber(menu):
    ran=''
    digits=3 if menu==1 else 4
    while digits>0:
        ran=ran+str(random.randint(0,9))
        digits=digits-1
        return ran

    if __name__ =='__main__':
        main()



Python choice in an ordered array, picking value one after another

I am trying to do a simple process on python, I know there is an answer out here on how to achieve this, but I can't seem to find it.

Python should make selection from a list of data on a txt file, but in an ordered form. Say it would pick the first value when prompted, then the second value,and so on until the list is exhausted.

Is there a way to achieve this without random? The only way I have seen so far are randomly, and randomly without/with replacement. The order of choice is very important here.

              import random
              with open ("questions.txt","r") as f:
              question = f.readlines()
              post = (random.choice(question).strip())
              print (post)

The code above only do so randomly and not what I want, I want it ordered and stop when the list is finished.




constant shuffling of Pandas dataframe "alway get same result" [duplicate]

I want to shuffle one dataframe and get the same result dataframe every time

import random
x = [1, 2, 3, 4, 5, 6]
random.seed(4)
random.shuffle(x)
print x

I found this code but shuffle() method not accept pandas dataframe also I want to get the result in form of dataframe




How can the machine generate random numbers

The Computer is designed to execute certain tasks exactly. It is not able to make arbitrary tasks : So how can It generate random numbers?




mardi 24 mars 2020

How can we get a randomly selected element from an array in Scala?

How can i find or get a randomly selected element from an array in Scala ???

The code for getting a random value is simple that is :

var rand :Int= scala.util.Random
println(rand.nextInt)



How do I make an Array of Buttons out of this in JS? And How do I set Random Images with this?

So I`m trying to make a Memory Game. At the moment I´m trying to set the Image of the card randomly but if my code just changes to top Image.

var images = ["url(IMG1.jpg)","url(IMG2.jpg)"...];
var randomIMG =0;

var card = "<div class='flip-card'><div class='flip-card-inner'><div class='flip-card-front'><button id='button'onclick='Flipfront(this)'style='width:300px;height:300px; marign:50px; background-image:url(Frontpage.jpg);'></button></div><div class='flip-card-back'><button id='button2'onclick='Flipback(this)'style='width:300px;height:300px; marign:50px; background-image:images[randomIMG];background-repeat:no-repeat;background-size:contain;'></button></div></div></div>"



for (let i = 0; i < level; i++) {
    document.querySelector("#container").innerHTML +=card;
}
function RandomBG(){
    for (let i = 0; i<level;i++){
        randomIMG = Math.floor(Math.random()*9)+0;
        document.getElementById("button2").style.backgroundImage = images[randomIMG]; 
    }
}
function Flipfront(el){
            RandomBG();
             el.closest('.flip-card').classList.add('flipped');
            flipped++;

}

And Also for later on, how do I put all my Buttons into an array?




How to dynamically keep elements inside their parent container when animating?

I am animating divs'. The animation is very simply moving each div along x and y axis. I am randomly setting the x and y axis value using javascript. I want the animation to be bound only inside the its containing element.

But despite getting height and width using clientHeight & clientWidth in javascript. The animation is getting out the container.Animation is done using Anime.js

I have put all required code.

JAVASCRIPT:

//function to create div and insert it to DOM
function domDiv(count, element, className, elementId) {
    let i = 0;
    while (i != count) {
        let div1 = document.createElement(element);
        div1.setAttribute('class', className);
        document.getElementById(elementId).appendChild(div1);
        i++;
    }
}

//function to generate random numbers bounded with container's height and width
function seed(property) {
    let ranNum;
    if (property == 'H') {
        let height = document.getElementById('parent1').clientHeight;
        ranNum = Math.floor((Math.random() * height) + 1);
        console.log("H: ", height);
        console.log("ranNum ", ranNum);
        return ranNum;
    }
    else {
        let width = document.getElementById('parent1').clientWidth;
        ranNum = Math.floor((Math.random() * width) + 1);
        console.log("W: ", width);
        console.log("ranNum ", ranNum);
        return ranNum;
    }
}

//animation function, animation done using anime.js
function randomValues() {
    anime({
        targets: '#parent1 .divs1',
        translateX: function () {
            return anime.random(seed('W'), seed('W'));
        },
        translateY: function () {
            return anime.random(seed('H'), seed('H'));
        },
        scale: [
            { value: .1, easing: 'easeOutSine', duration: 500 },
            { value: 1, easing: 'easeInOutQuad', duration: 1200 }
        ],
        delay: anime.stagger(200, { grid: [14, 5], from: 'center' }),
        duration: 800,
        easing: 'easeInOutSine',
        complete: randomValues
    });
}

//execution starts from here or main control takes place below
domDiv(50, 'div', 'divs1', 'parent1');
randomValues();

HTML:

<body>
    <section id="parent1"></section>
</body>

CSS:

#parent1 {
    width: 100vw;
    height: 100vh;
    /* padding: 50px; */
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    justify-items: center;
    border: solid red 2px;
}

.divs1 {
    margin: 5px;
    width: 3vw;
    height: 3vw;
}

.divs1:nth-child(odd) {
    background-color: yellow;
    border-radius: 50%;
}

.divs1:nth-child(even) {
    background-color: aquamarine;
    border-radius: 50%;
}



Threads and sum of random numbers

How do I make one thread store random numbers in shared memory and the other reads those numbers and prints the sum?

I made 2 threads, and I know how to write sum, but I am probably doing something wrong with the printing random numbers because it doesn't want to print them. I need two inputs/threads N and M. N is generating random numbers and stores them in shared memory. The other is M. I also need to make that the code repeats M more times with M being the second input argument of the program at its startup.

my code looks like this. It's a mess.

enter image description here




Target specific class + numbers

I'm trying to get images of different sizes to appear randomly one by one around the center of the page, for now I managed to have them randomly appear and to have them with different width and therefor height. However I am SURE I can target all of the classes instead of copying every single code with a different name? I remember once seeing a function that targeted a class and automatically the number that followed it, like .item +(and then the extension?)

Any tips regarding letting them appear around the center instead of spread across are welcome. I patched this together with a lot of different codes, so it's bit of a Frankenstein.

$(".grid-item").hide().each(function(i) {
  $(this).delay(i*500).fadeIn(500);
});

var pane_width = $(".random-pane").width() - $(".grid-item").width();
var pane_height = $(".random-pane").height() - $(".grid-item").height();

$(".random-pane").children().each( function(){

  var x = Math.round(Math.random() * pane_width);
  var y =  Math.round(Math.random() * pane_height);

  $(this).css("top",y);
  $(this).css("left",x);

});

var rand=Math.floor(Math.random()*30)+10;
var width=Math.round(($(window).width()/100)*rand);
$('.item-1').width(width);

var rand=Math.floor(Math.random()*30)+10;
var width=Math.round(($(window).width()/100)*rand);
$('.item-2').width(width);

var rand=Math.floor(Math.random()*30)+10;
var width=Math.round(($(window).width()/100)*rand);
$('.item-3').width(width);

var rand=Math.floor(Math.random()*30)+10;
var width=Math.round(($(window).width()/100)*rand);
$('.item-4').width(width);

var rand=Math.floor(Math.random()*30)+10;
var width=Math.round(($(window).width()/100)*rand);
$('.item-5').width(width);




how get random row from =>1 in table of database in MySQL?

this is my PHP code, How can I get randomly row from 'featured'=>1 in table of database in MySQL? which part of my below code should change?

$featured_movie = $this->db->get_where('movie', array('featured'=>1))->row();




How to create a "post of the day" with flask [duplicate]

I have a flask app which uses SQLAlchemy. This my Flask app have randomly selected posts (using random.choice) in the home page. This randomly selected post(s) changes every time when the page refreshes. But I want to randomly select a post and keep it for a specific time period and changed the post itself when that time period passed. In simple English, I want to make a "Post of the day" or "Post of the week". How can I do this using flask ?




How do I generate n true random numbers using quantum mechanics in Python? [duplicate]

Say that we need n numbers in the range [0, maxnum] with a decimal precision dec. What's a robust approach for finding a useful solution in Python?




Random Number Generator in Python

just started learning Python(2) and was wondering what the best way to make a Random Number Generator. I have made a very basic one so far with: "import random for x in range(1): print random.randint(0,5)" but was wondering if there was a better way to do this with the ability to have numbers that are not integers generated. The end goal for this code is to make a random period of time pass in a game using "time.sleep(x)", would love to know if there is a better way of doing this.




Want to select a random item from a list and reuse the item in a different function

my code is pretty messy as I am new but I cant figure this out!

I have only included the relevant pieces of my code btw.

Pretty much What i want it to do is say the same location twice for random_place1 and then a new location for random_place2. Currently it just gives me three separate locations, because i am just calling for random_place1 to rerandomize.

def random_place1():

import random

locations = ["Paris" , "New York", "San Francisco" , "Tokyo", "Istanbul", "São Paulo", "Xi'an", "Bogotá", "Casablanca", "Rabat"]


first_place = random.choice(locations)

return (first_place)

def random_place2():

import random

locations = ["London" , "Miami" , "Chicago", "Cairo", "Vienna" , "Manila", "Munich", "Delhi"]


second_place = random.choice(locations)
return(second_place)

def main():

answer = input("Type Yes to continue or No to exit: ")
if answer == "yes":
    print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
    restart2()
elif answer == "y" :
    print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
    restart2()
elif answer == "Yes":
    print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
    restart2()
elif answer == "YES":
    print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
    restart2()
elif answer == "Y":
    print("\nLast summer, we went for a vacation with " + random_name(), "on a trip to " + random_place1(), ". The weather there is very " + random_adj(), "! Northern " + random_place1(), " has many " + random_plural_noun(), ", and they make " + random_plural_noun(), " there. Many people there also go to the " + random_place2()," to " + random_action_verb(), ". The people who live there like to eat " + random_food(), ". They also like to " + random_action_verb(), " in the sun and swim in the " + random_noun(), ". It was a really " + random_adj(), " trip!")
    restart2()

elif answer == "no":
    print("\nThanks for trying out the Madlibs Generator!")
elif answer == "n":
    print("\nThanks for trying out the Madlibs Generator!")
elif answer == "No":
    print("\nThanks for trying out the Madlibs Generator!")
elif answer == "NO":
    print("\nThanks for trying out the Madlibs Generator!")
elif answer == "N":
    print("\nThanks for trying out the Madlibs Generator!")
else:
    print("\nInvalid response please try again!")
    restart()



how to get random string value from list - android

i have few youtube api keys for my android project. eg :

YOUTUBE_API_KEY1 = XXXXXXXXXXX
     YOUTUBE_API_KEY2 = BBBBBBBBBBB
     YOUTUBE_API_KEY3 = NNNNNNNNNNN

and i want that my String YOUTUBE_API_KEY = random key from the keys list.

how can i do it? thanks




lundi 23 mars 2020

sorting using same random array

I want to make an array sorting in three ways using one random array. i have:

import sort.bub;
import sort.ins;
import sort.sel;

import java.util.Arrays;
import java.util.Random;

public class sorting{

    public static int[] arr = new int[10];
    public static bub bubble = new bub();
    public static sel selection = new sel();
    public static ins insertion = new ins();


    public static void main(String[] args) {

        getMathRandom();
        bubble.bub(arr);
        getMathRandom();
        insertion.ins(arr);
        getMathRandom();
        selection.sel(arr);
    }


    public static void getRandom(int[] arr) {
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt();
            //System.out.println(arr[i]);
        }
        System.out.println(Arrays.toString(arr));

    }

    private static void getMathRandom() {

        for (int j = 0; j < arr.length; j++) {
            int number = (int) (Math.random() * 1000);
            arr[j] = number;
        }
        System.out.println("Random  " + Arrays.toString(arr));
        System.out.println("");
    }   
}

bub.java

import java.util.Arrays;
public class bub {
    public bub() {
    }
   public void bub(int[] arr) {
        System.out.println("bubble sort");
        for (int i = arr.length - 1; i >= 0; i--) {
            System.out.println(Arrays.toString(arr));
            for (int index = 0; index < i; index++) {
                if (arr[index] > arr[index + 1]) {
                    int tmp = arr[index];
                    arr[index] = arr[index + 1];
                    arr[index + 1] = tmp;
                }
            }
           // System.out.println(Arrays.toString(arr));
        }
        System.out.println("");
    }
}

sel.java

import java.util.Arrays;
public class sel {
    public sel() {
    }
    public void sel(int[] arr) {
        System.out.println("selection sort: ");
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.println(Arrays.toString(arr));

            for (int index = i + 1; index < arr.length; index++) {
                if (arr[i] > arr[index]) {
                    int tmp = arr[index];
                    arr[index] = arr[i];
                    arr[i] = tmp;
                }
            }
//            System.out.println(Arrays.toString(arr));
        }
        System.out.println("");
    }
}

ins.java

import java.util.Arrays;
public class ins {
    public ins() {
    }
    public void ins(int[] arr) {
        System.out.println("insertion sort: ");
        for (int i = 1; i < arr.length; i++) {
            System.out.println(Arrays.toString(arr));

            int newElement = arr[i];
            int location = i - 1;
            while (location >= 0 && arr[location] > newElement) {
                arr[location + 1] = arr[location];
                location--;
            }
            arr[location + 1] = newElement;
        }

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

output

Random  [928, 469, 309, 30, 344, 230, 924, 628, 319, 275]

bubble sort
[928, 469, 309, 30, 344, 230, 924, 628, 319, 275]
[469, 309, 30, 344, 230, 924, 628, 319, 275, 928]
[309, 30, 344, 230, 469, 628, 319, 275, 924, 928]
[30, 309, 230, 344, 469, 319, 275, 628, 924, 928]
[30, 230, 309, 344, 319, 275, 469, 628, 924, 928]
[30, 230, 309, 319, 275, 344, 469, 628, 924, 928]
[30, 230, 309, 275, 319, 344, 469, 628, 924, 928]
[30, 230, 275, 309, 319, 344, 469, 628, 924, 928]
[30, 230, 275, 309, 319, 344, 469, 628, 924, 928]
[30, 230, 275, 309, 319, 344, 469, 628, 924, 928]

Random  [909, 584, 169, 129, 175, 297, 733, 473, 619, 745]

insertion sort: 
[909, 584, 169, 129, 175, 297, 733, 473, 619, 745]
[584, 909, 169, 129, 175, 297, 733, 473, 619, 745]
[169, 584, 909, 129, 175, 297, 733, 473, 619, 745]
[129, 169, 584, 909, 175, 297, 733, 473, 619, 745]
[129, 169, 175, 584, 909, 297, 733, 473, 619, 745]
[129, 169, 175, 297, 584, 909, 733, 473, 619, 745]
[129, 169, 175, 297, 584, 733, 909, 473, 619, 745]
[129, 169, 175, 297, 473, 584, 733, 909, 619, 745]
[129, 169, 175, 297, 473, 584, 619, 733, 909, 745]

Random  [404, 277, 798, 863, 163, 163, 984, 638, 248, 561]

selection sort: 
[404, 277, 798, 863, 163, 163, 984, 638, 248, 561]
[163, 404, 798, 863, 277, 163, 984, 638, 248, 561]
[163, 163, 798, 863, 404, 277, 984, 638, 248, 561]
[163, 163, 248, 863, 798, 404, 984, 638, 277, 561]
[163, 163, 248, 277, 863, 798, 984, 638, 404, 561]
[163, 163, 248, 277, 404, 863, 984, 798, 638, 561]
[163, 163, 248, 277, 404, 561, 984, 863, 798, 638]
[163, 163, 248, 277, 404, 561, 638, 984, 863, 798]
[163, 163, 248, 277, 404, 561, 638, 798, 984, 863]

i want the array just one random array, but with three different sorting. I tried to use only one getmathrandom but only one sort that runs the other only shows the results of the top sorting. how would I do that? Or any other solution I'd appreciate.




How to write a code for the lambda method with pandas and random?

So I am working on this python code where I have imported a excel file in from my desktop. Currently in my code I am having problem with executing my lambda function. I am to use the lambda function in the apply() method for the data column(s) with outliers (i.e., z-scores > 3 or < -3), set the value for the outliers to null (i.e., np.nan), otherwise retain the original value. I have types the line of code 2 different ways with the same outcome. However when I check to see if my overall code used the lambda function it did not and I don't know how to get my code to use the function instead of just running lambda as no part of the overall code.

data.SalaryZScores.apply(lambda SalaryZScores:np.nan if SalaryZScores > 3 or SalaryZScores<-3 else SalaryZScores)

Or

data['Salary'] = data['Salary'].apply(lambda Salary: random.randrange(data['Salary'].min(), data['Salary'].max())if pd.isnull(Salary) else Salary)



I am trying to create a list of 9 randomly generated numbers, all of which are different

I am trying to create a list of 9 randomly generated numbers, all of which are different numbers. The end goal is to create a magic square (sums of 15). I am trying to confirm that my list mat1 correctly generated the 9 random numbers, but my output is nothing.

import random
while True: # keep trying until you find a magic square 
    magic=True # assume that magic is True, as a start
    mat1=[] # intialize matrix1 (mat1) to hold 9 unique numbers
    i=1
    while i < 10:
        val=random.randint(1,9) # generate a random number between 1 and 9
        if val not in mat1: # check if the generated number exists in the list
            mat1.append(val) # if it doesn't exist in the list then append it to the list
    print(mat1)



Unable to call a function within a function in python [duplicate]

Build a "mimic" dict that maps each word that appears in the file to a list of all the words that immediately follow that word in the file. The list of words can be be in any order and should include duplicates. So for example the key "and" might have the list ["then", "best", "then", "after", ...] listing all the words which came after "and" in the text. We'll say that the empty string is what comes before the first word in the file.

With the mimic dict, it's fairly easy to emit random text that mimics the original. Print a word, then look up what words might come next and pick one at random as the next work. Use the empty string as the first word to prime things. If we ever get stuck with a word that is not in the dict, go back to the empty string to keep things moving.

Defining first function:

def mimic_dict(filename):
    with open (filename, 'r+') as x:
        x = x.read()
        x = x.split()
        dic = {}
        for i in range(len(x)-1):  
            if x[i] not in doc:    
                dic[x[i]] = [x[i+1]]   
            else:                      
                dic[x[i]].append(x[i+1])

    print(dic)


mimic_dict('small.txt')

OUTPUT:

{'we': ['are', 'should', 'are', 'need', 'are', 'used'], 'are': ['not', 'not', 'not'], 'not': ['what', 'what', 'what'], 'what': ['we', 'we', 'we'], 'should': ['be'], 'be': ['we', 'but', 'football'], 'need': ['to'], 'to': ['be', 'be'], 'but': ['at'], 'at': ['least'], 'least': ['we'], 'used': ['to']}

Defining second function with first fucntion called within it

import random

def print_mimic(x): 
    l = []
    for i in range(5):
        word = random.choice(list(x.items()))
        l.append(word)

    print(l)      

print_mimic(mimic_dict)

AttributeError                            Traceback (most recent call last)
<ipython-input-40-c1db7ba9ddae> in <module>
      8 
      9     print(l)
---> 10 print_mimic(d)

<ipython-input-40-c1db7ba9ddae> in print_mimic(x)
      4     l = []
      5     for i in range(2):
----> 6         word = random.choice(list(x.items()))
      7         l.append(word)
      8 

AttributeError: 'NoneType' object has no attribute 'items'

Please advise why is the second function failing to call the first function? Or why am I getting this error?




Does JMeter support to select a sampler in Thread Group randomly?

In my Test Plan, I have Thread Group with 5 Samplers. Is there a way with JMeter that I want to select one among the 5 samplers in Thread Group Randomly and do performance testing to only that particular sampler ?




Random window movement in C# [closed]

i need to do window, thats randomly moving on the screen. How to do it? Example: virus Trojan.JS.YouAreAnIdiot - https://www.youtube.com/watch?v=LSgk7ctw1HY




Correct way to draw random seeds

I would like to store and access a large $(n, k)$ array. The first dimension are items and the second is "universe".

We can say n = 10^7 and k = 10000".

In my use case, I want to access a small number b=32 of items at a time, and the queries are always different.

The twist is that my array is composed of random numbers, following a distribution I know.

Furthermore, I want reproducibility.

Thus, my idea is the following:

Generate random states

import numpy as np

# for reproducibility
np.random.seed(1337)

n = 100
random_states = [np.random.RandomState(np.random.randint(2**32)).get_state() for i in range(n)]

Draw numbers

for i in [23, 12, 42, 26]:
    r = np.random.RandomState()
    r.set_state(random_states[i])
    print(r.random())

The problem is that my random states are quite big in memory.

I could draw random seeds and use then to initialize RandomState, but is it statistically correct?




Why when cycling through a txt document can I not use .nextInt?

So for school I'm making a project that's going to take in a confirmation number, send out a confirmation number, and generate confirmation numbers. Right now I'm working on the generation of the confirmation number, and it was working, but I wanted to add a check to make sure that the generated confirmation number was not already generated. So I made a txt document, and added one so that it wouldn't just send back an error. So, I'm confused as to where my error is coming from. I am also aware of the issues in my code besides this, and it feels sloppy, but I'm working on it, I made all of these classes separate and now am trying to merge them together in to one program. thank you for your help and for putting up with my grammar.

another method is calling numberGen(); just for reference. I commented on the line I think the error is in because it's one listed in the error code. Method:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;

public class Conformation {
    static boolean check;

    static PrintWriter writer = null;
    static File conNums = new File("/Workspace/IA Crit C/Res/ConNums.txt");
    static File usedNums = new File("/Workspace/IA Crit C/Res/UsedConNums.txt");
    static Scanner in;

    public Conformation() throws IOException {
        int conNum = numberGen();
        check = checkNum(conNum);
        if (check == true) {
            checkUse(conNum);
        }
        addNum(conNum);

    }

    public static int numberGen() {
        Random rand = new Random();
        int max = 999999999;
        int min = 100000000;
        int conNum = 0;

        boolean run = true;

        while(run == true) {
            conNum = rand.nextInt((max - min) + 1) + min;

            check = checkNum(conNum); //if true it means it's already listed

            if (check == false) {
                run = false;
                addNum(conNum);
            }

        }
        return conNum;
    }

    private static void checkUse(int conNum) {
        try {
            in = new Scanner(usedNums);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        while (in.hasNextLine()) {
            if (check == false) {
                int next = in.nextInt();
                if (next == conNum) {
                    check = true;
                }
            }
        }


    }

    private static void addNum(int conNum) {

        if (check == false) {

            try {
                writer = new PrintWriter(conNums);
                writer.println(conNum);
                writer.close();

            } catch (FileNotFoundException e) {
                System.out.println("File Not Found");
            }

        }
    }

    private static boolean checkNum(int conNum) {
        try {
            in = new Scanner(conNums);
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }

        while (in.hasNextLine()) {
            int next = in.nextInt();//this line
            if (next == conNum) {
                check = true;

            }
        }

        return check;
    }

}

Error:

java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at Conformation.checkNum(Conformation.java:93)
    at Conformation.numberGen(Conformation.java:37)
    at GUI.<init>(GUI.java:55)
    at GUI$1.run(GUI.java:41)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)