mardi 31 décembre 2019

Python - schedule with random delay

I'am learning python by doing little projects on my own. I'am struggling to schedule scripts with random delay in a range. In the code below, the delay is random but always the same ... I Really need help.

import schedule
import time
import random
import datetime


def job():
    t = datetime.datetime.now().replace(microsecond=0)
    print(str(t) + "  hello")


i = 0
while i < 10:
    delay = random.randrange(1, 5)
    schedule.every(delay).seconds.do(job)
    i += 1

    while True:
        schedule.run_pending()
        time.sleep(1)







lundi 30 décembre 2019

Generate random numbers by finding the best fitting distribution for the data in pyspark

basically my problem statement is to find the best fit distribution for my data (just suppose i have already extracted a column from dataframe). after finding the best fit distribution of my data i have to generate random numbers .

Heading

import numpy as np
import scipy.stats as st
def bestFitDist(dist_list):
  distributions = [st.beta,
              st.expon,
              st.gamma,
              st.lognorm,
              st.norm,
              st.pearson3,
              st.triang,
              st.uniform,
              st.weibull_min, 
              st.weibull_max,
              st.laplace,
              st.exponpow
                  ]
  mles = []
  for distribution in distributions:
    pars = distribution.fit(dist_list)
    mle = distribution.nnlf(pars, dist_list)
    mles.append(mle)
  results = [(distribution.name, mle) for distribution, mle in zip(distributions, mles)]
  best_fit = sorted(zip(distributions, mles), key=lambda d: d[1])[0]

  #print ('Best fit reached using {}, MLE value: {}'.format(best_fit[0].name, best_fit[1]))
  return best_fit[1]

this function i have written to find the best fit distribution i m not getting how to generate radom number based on the return value of this function

matlab code for this problem is something like : (just ignore (isMonth & sensorData.isLoad & isValid) and Pratio is a column for i have to find best distribution and then generate random values (rPratio)

NSEED=10000;
[D, PD] = allfitdist(Pratio(isMonth & sensorData.isLoad & isValid), 'AIC');
 ksd_Pratio = PD{1};
rPratio = random(ksd_Pratio,NSEED,1);       

i hav to convert this logic into pyspark




Math.random() when used in loop will not give new number

When I try to generate a new random number using Math.random() it gives me the EXACT same answer every single time no matter what, but only in certain uses.

By the way I have a custom random function:

function random(min, max) {
 return Math.random() * (max - min + 1) + min;
}

For example, this code does exactly what I want it to, it fills each slot in dataset.data[I][ii] to a NEW random number.

dataset.data.forEach((point, index) => {
 //fill dataset with random numbers
 dataset.data[index] = point.map(() =>
    Math.round(random(0, screen.get().width))
 );
});

However, when I use this code, It fills the array with the exact same random number each time.

dataset.data.forEach((point, index) => {
 //fill dataset with random numbers
 dataset.data[index][0] = Math.round(random(0, screen.get().width));
 dataset.data[index][1] = Math.round(random(0, screen.get().height));
});

I keep encountering this issue and I do not understand it, I do understand that there are at times large quantities of the same number, but no matter what I do, in certain circumstances like these, only one way of writing it works, which is not helpful.




How to create random list without repeating one previous value?

This code creates list of random numbers, but sometimes value of one previous index is repeated. I can use code below to avoid repeating, but it creates random integer, not list. So, I need to avoid list to be like this [1,1,0,5] and want it to be like this [1,0,1,5]

var previousIndex = 0

private fun getNewRandomIndex(): Int {
        var newIndex = -1
        while (true) {
            newIndex = random.nextInt(randomValues.size)
            if (previousIndex != newIndex) {
                previousIndex = newIndex
                break
            }
        }
        return newIndex
    }



getting a random file from a folder

i'm trying to get a random file out of a folder. I have absolutely no clue what I'm doing.

my html:

<script src="javascript.js"></script>
<img id="myimage" alt="" />
<div>if you want to request a removal of a image, contact me at -----------</div>

what would be the JavaScript for this, and where would I put the JavaScript?




Random Positions of an Array

I have a question. Attached is a section for my code needed for this question. I am shuffling the y position for 5 rectangles. (drag1, drag2, drag3, drag4, and drag5). The Y position shuffles and so do the rectangles but some of them land in the same spot on top of each other. Am I missing something? I need the for loop to start at 1.

var self=this;

dragPos = ["0","0","0","0","0","0"];//These arrays help in the rest of my code. They both ignore the 0 position.

correctPos = ["0","1","2","3","4","5"];//These arrays help in the rest of my code. They both ignore the 0 position.

yPos = [];

function shuffle(array){
   counter = array.length;

   while (counter > 0) {

      index = Math.floor(Math.random() * counter);

      counter--;

      temp = array[counter];

      array[counter] = array[index];

      array[index] = temp;

   }

   return array;

}

function positionAnswers() {

   for(e=1; e < dragPos.length; e++){

      yPos.push(self["drag" + e].y);

      shuffle(yPos);

      for(h=0; h < yPos.length; h++){

         self["drag" + e].y = yPos[h];

      }

   }

}

positionAnswers();



How does this random number generator work?

While browsing in through some examples, I ran into this code:

Math.random = function (x) {
  return function () {
    x ^= x << 13;
    x ^= x >>> 17;
    x ^= x << 5;
    return 1 - (x >>> 0) / 0xFFFFFFFF;
  };
}(1);

But now, I am unable to understand how it works.

What I am able to understand is:

  • Since the x parameter is closure to inner returned function, the value 1 passed to it is the seed value.
  • (x >>> 0) / 0xFFFFFFFF is a random decimal decmal in 0 (probably exclusive) and 1 (probably inclusive). So we 1 - the value.

The output of first few runs:

0.9999370498116913

0.9842525718231342

0.3835958974397732

0.928381365008741

0.44151164182496994




Pandas: create a random sample and correlation matrix

How to create a subset of the data that contains a random sample of 200 observations (database create form a csv file)

Data columns (total 10 columns): longitude 20640 non-null float64 latitude 20640 non-null float64 housing_median_age 20640 non-null float64 total_rooms 20640 non-null float64 total_bedrooms 20433 non-null float64 population 20640 non-null float64 households 20640 non-null float64 median_income 20640 non-null float64 median_house_value 20640 non-null float64 ocean_proximity 20640 non-null object

How to determine the correlations between housing values(median_house_value) and the other variables and display in descending order.

df.corr() gives me all the correlations. How to make it show only the median house value?




How to get a random number/letter combination in Javascript? [duplicate]

i am trying to create a program which puts random numbers/letters in a textbox using javascript (in the browser console). I have tried my best to do it but i just couldn't do it.

my best attempt was:

var key = ((nums[Math.floor(Math.random() * nums.length)].toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()));
var key2 = ((Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()));
var key3 = ((Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()) + (Math.floor((Math.random() * 10)).toString()));

But unfortunately it only generates numbers. Does anyone know how to randomize both? Would appreciate if anyone could help me .

Regards, 3hr3nw3rt




Label background color mix

I have three labels and one button. I want to randomize the background color for label1 and label2, on the condition that not come the same color in label1 and label2, and with the click of a button I want to get label3 background color, which is a mixed color between label1 color and label2 color. In my code i have colorlist with some colors. I want to randomize colors that are included in my colorlist only thanks for your help

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' Create a List
    Dim colorList As New List(Of SolidBrush)

    ' Add colors to it
    'red
    colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 0, 0)))
    'white
    colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 255, 255)))
    'Blue 
    colorList.Add(New SolidBrush(Color.FromArgb(100, 0, 0, 255)))
    'Yellow 
    colorList.Add(New SolidBrush(Color.FromArgb(100, 244, 255, 16)))
    'Green 
    colorList.Add(New SolidBrush(Color.FromArgb(100, 0, 255, 0)))
    'Pink 
    colorList.Add(New SolidBrush(Color.FromArgb(100, 255, 16, 22)))
    'Brown 
    colorList.Add(New SolidBrush(Color.FromArgb(100, 120, 37, 37)))
    Dim rnd = New Random()

    ' Get a random item from the list between 0 and list count
    Dim randomColour = colorList(rnd.Next(0, colorList.Count))
    Dim randomColour1 = colorList(rnd.Next(0, colorList.Count))

    ' Assign the color to the label

    Label1.BackColor = randomColour.Color
    Label1.Text = randomColour.Color.Name.ToString
    Label2.BackColor = randomColour1.Color
    Label3.BackColor = (Color.FromArgb(Label1.BackColor.ToArgb + Label2.BackColor.ToArgb))
End Sub



Displaying The Individual Random Numbers And The Sum Of A Python Array

What logic would you use to display the randomly generated numbers of an array, while simultaneously printing out the sum of said random numbers? This was for an assignment and it was supposed to be done with a few functions, similar to how I have it set up.

I've been able to display the random numbers in the array, but when I try to sum them it calls the function again and gives me the sum of a new set of randomly generated numbers. I've reset the code a bit as that chunk of code didn't really help me.

import random
import math

def fillList(count):
    list = []
    for i in range(0, count):
        list.append(random.randint(0, 10))
    return list

def sumList(val):
    total = 0
    for i in val:
        total = total + val
        total += total
    return total

def printList(lst):
    for val in lst:
        print(val)
        sum = sumList(val)
    return sum

myList = fillList(25)
printList(myList)



dimanche 29 décembre 2019

How to apply random list of numbers for selection from array to select image?

How to make list of random numbers and use it to set image from array?

val randomValues = List(15) { Random.nextInt(0, 5) }
var array = intArrayOf(R.drawable.cat1,R.drawable.cat2,R.drawable.cat3,R.drawable.cat4,R.drawable.cat5)
imageView.setImageResource(array[randomValues])

I'm getting Type mismatch on randomValues in imageView.setImageResource(array[randomValues]). Required: Int and Found: List >int< (I changed "<" signs directions because they becomes invisible here)




my program does not pass the test.error Unlikely event: found 2424 out of 2400 times the same number on the same position. Are the cards random?

public class BingoCard
{
    public static String Card []= new String[24];

  public  static String[] getCard() {
      int cardLength = 0;
      number(1,15,0);
      number(16,30,5);`
      number(46,60,14);
      number(61,75,19);

        for (int i =  0; i < 5; i++)    Card[i]="B"+Card[i];
                cardLength+=5;
            for (int i =  cardLength; i < 5+cardLength; i++) Card[i]="I"+Card[i];
                cardLength+=5;
                for (int i =  cardLength; i < 4+cardLength; i++)  Card[i]="N"+Card[i];
                    cardLength+=4;
                 for (int i =  cardLength; i <5+cardLength; i++) Card[i]="G"+Card[i];
                        cardLength+=5;
                        for (int i =  cardLength; i < 5+cardLength; i++) Card[i]="O"+Card[i];

                return Card;
    }       

    public static void number(int min, int max, int index){
        int arr[] = new int[5];
        int temp;
    for (int i =index; i<index+5; i++ ){
        temp=(int)(min+Math.random()*(max-min+1));
            if(temp==arr[0]||temp==arr[1]||temp==arr[2]||temp==arr[3]||temp==arr[4]){
                i--;
                continue;
                }else   
        arr[i-index]=temp;
            Card[i]=String.valueOf(temp);
    }

    }

}

Can you help the association by writing a method to create a random Bingo card? A Bingo card contains 24 unique and random numbers according to this scheme: 5 numbers from the B column in the range 1 to 15 5 numbers from the I column in the range 16 to 30 4 numbers from the N column in the range 31 to 45 5 numbers from the G column in the range 46 to 60 5 numbers from the O column in the range 61 to 75

The card must be returned as an array of Bingo style numbers: { "B14", "B12", "B5", "B6", "B3", "I28", "I27", ... }




Sampling 5 observation from a data-set, where the ranked variable does not always have 5 observations

I have a data-set of bank business units (branches) and accounts (account numbers). Some branches have 2 accounts, while others can have 50 - it varies. I need to randomly sample 5 accounts from each branch. I tried using the code below, but get the following error :

ERROR: The sample size, 5, is greater than the number of sampling units, 2.

I need it to be LIKE SMAPSIZE < 6, i.e if there are only 2 obs per branch, bring only the 2.

This is the code:

PROC SQL ;
    CREATE TABLE FINAL_RANDOM as
    SELECT  t1.mis_division_id,
            t1.mis_wing_id,
            t1.region_id,
            t1.account_branch_id,
            t1.branch_name,
            t1.acc,
            t2.Attribute,
    FROM work.ORGANIZATION_STRUC2 t1
    INNER JOIN work.UNION_ALL_RANDOM t2
    ON t1.account_id = t2.account_id
;
QUIT ;

PROC SORT DATA=work.FINAL_RANDOM ;
BY Account_Branch_Id ;
RUN ;

PROC SURVEYSELECT DATA=FINAL_RANDOM OUT=FINAL_RANDOM_1 NOPRINT
     METHOD=srs
     SAMPSIZE = 5 ;
     STRATA Account_Branch_Id ;
RUN; 



How to RNG and delay bash script pressing RETURN for an autotyper script

Currently I'm using a bash script that automatically types out a phrase, but I wonder how to RNG the sleep counter for example to like 1800-1900 seconds. If possible I'd also like to know how to make the script delay pressing RETURN. Thanks.

this is the script

#!/usr/bin/env bash
function autotype_loop()  {
xdotool key space
xdotool type "Text here"
xdotool key Return
sleep 1810
autotype_loop
}
autotype_loop



Select enum by ordinal; java

Is it possible to get an enum with its ordinal?

enum SimpleJackCards {
    As(11), König(10), Dame(10), Bube(10), Zehn(10), Neun(9), Acht(8),
    Sieben(7), Sechs(6), Fünf(5), Vier(4), Drei(3),Zwei(2), Yolly (1);
    private int value;
    SimpleJackCards(int val) {
        value = val;
    }
    int getValue (){
        return value;
    }
}

For example

I want to write a method that gives me a random card ... I would randomize an integer.

And want to get that enum with the generated ordinal number.

i.e.: ordinal value 0 would be enum As with value 11.




samedi 28 décembre 2019

How to loop print output and write each result to csv?

I have written the following code to generate a random 12 number string:

import uuid

def my_random_string(string_length=12):
    """Returns a random string of length string_length."""
    random = str(uuid.uuid4()) # Convert UUID format to a Python string.
    random = random.upper() # Make all characters uppercase.
    random = random.replace("-","") # Remove the UUID '-'.
    return random[0:string_length] # Return the random string.

print(my_random_string(12)) # For example, D9E50Cd

How can I loop it and save each string output to a .csv file?




Generate an random round race track with any given number of straights and 90° curves

i'm trying to build an small script to generate an random racing track that always connects to its start out of an fixed set of tiles.

Does anyone have an hint or an link to some algorithms that can help me with this?

For better understanding: 1. Give an number for available straight pieces 2. Give an number for available curved pieces 3. Generate an round course that always connects to its starting point without using more than the given tile numbers.

Sorry for my bad english. Thanks in advance for all your help. :)




Shuffling buttons on tkinter GUI

I am building a multiple choice game using Python and tkinter and I need to be able to shuffle the buttons on the GUI so that the position of the button containing the correct answer changes. I have written this code so far but it seems like the same rely value is often taken from the y_list multiple times leading to buttons hiding each other. How is it possible to ensure that each rely value is only taken once?

y_list=[0.2,0.4,0.6,0.8]

def randy():
    xan = random.choice(y_list)
    return xan

y_list.remove(xan)


wordLabel = Label(newWindow, text=all_words_list[randWord])
wordLabel.place(relx=0.49, rely=0.1)
choice1=Button(newWindow, text=all_definitions_list[randDefinition], height=5, width=20)
choice1.place(relx=0.5,rely=randy(), anchor=N)
choice2=Button(newWindow, text="gangsta", height=5, width=20)
choice2.place(relx=0.5, rely=randy(), anchor=N)
choice3=Button(newWindow, text="gangsta", height=5, width=20)
choice3.place(relx=0.5, rely=randy(), anchor=N)
choice4=Button(newWindow, text="gangsta", height=5, width=20)
choice4.place(relx=0.5, rely=randy(), anchor=N)



vendredi 27 décembre 2019

Single random number for input field javascript

I have created a love calculator i have published it on internet the logic which i have created is i have used math.random()*100; which produce a random love percentage also there is two input fields name and love where anyone can input there data the problem is that when a person click on calculate it produce a percentage but when he or she click again on this button it display another percentage for the same inputs i want it to generate single input for single input how it possible in simple javascript because i am beginner thanks in advance




Generating random uniform random numbers from coin flip algorithm tends to generate more 0s than expected

I am trying to generate random numbers in the range from 0 to 99 using a function rcoin that returns 0 or 1 with equal probability. I have written the following code that converts a binary number generated from successive calls of rcoin function, and then returns it with the condition that the number is less than 100. Here is the R code.

rcoin <- function() {
  rbinom(n = 1, size = 1, prob = 0.5)
}

r100 <- function(n=100) {
  v = n + 1
  while(v > n) {
    v = sum(sapply(0:6, function(i) rcoin() * 2 ^ i))
  }
  v
}

val_plot <- function() {
  N = 10000
  rand_sample <- rep(0, N)
  for (i in 1:N){
    rand_sample[i] = r100()
  }
  hist(rand_sample, breaks = 100)
}

val_plot() 

It is supposed to produce uniform random numbers from 0 to 99, as truncated uniform distribution is also uniform. But when I plot the histogram of 10000 generated values, I see the value 0 is generated for unusually large number of times, but all other values follow a uniform distribution. Why? I guess this is because the binary number "1111111" is getting rejected whereas "0000000" is not. But how do I solve this issue? Is there any way to improve it?




How to constrain items with multiple randomly selected positions so that the average position for each is within a certain range

Problem: In total, I have 1-300 positions to fill in, I have 50 items, each item has 6 unique positions to choose (300 total positions). The average position for each of these items needs to be in range 145-155 (the closer to 150 the better)

Constraints: For each item, each of its 6 positions must fall within a list of fixed ranges (called runs), but not be within the same run,

e.g. The runs are: [(1,36), (37,73), (74,110), (111,148), (149,186), (187,225), (226,262), (263, 300)]. So item 1 can have position 1, 38, 158, 198, 238, 271 - so not within the same run twice.

The positions chosen should be random - or as random as possible

The issue I'm having: Constraining the randomly selected positions to be an average of 150 (or very close) seems to be really difficult. I've tried various different implementations of the code but most will result in it hanging close to the end (due to not having enough positions to choose from), or don't get very close. My best attempt just involves if statements I've placed to at least try to restrict the range but it still only gets a range of around 130-170. This feels like a really poor method and I was wondering if there was a way to do it algorithmically instead of just pasta'ing if statements in hopes something will work.

My best attempt with random band-aid restrictions: https://pyfiddle.io/fiddle/dfc6dfd1-1e12-46df-957c-d7ae0e94fbe3/?i=true

^ as you can see the averages vary, with most things being in an acceptable range and some just being off/really off

I've spent several weeks on this but genuinely cannot think of anything to restrict it to an appropriate average (145-155) and was hoping for any help here




Analyzing large amount of numbers using Python

I just start to learn programing using Python...

I need to analyze large amount of random numbers in Python... 108 000 to be exact.

Need to put them in a list and count for how many times number appears, they are in range 1-80...

What would you do in my situation and how to approach to that problem?




The threshold function of the r-connectedness of random bipartite graph G(n,m,p)

I need prove the threshold function of the r-connectedness for random bipartite graph G(n,m,p), but I can't find the related references about it. Is there any reference recommendation for this question? Besides,I found that someone recommends paper "I. Palasti, On the connectedness of bichromatic random graphs, Publ. Math. Inst. Hung. Acad. Sci., 8 (1963), 341-440" in the following question, but I cannot find this paper online, is there any sources for this paper?

https://mathoverflow.net/questions/76227/random-bipartite-graphs/76289?newreg=78e4f06c7da54cfaad72f5776be64cef




Generate random password based on user input in Javascript

The assignment is to prompt for length of the password and character type from the user, then generate a random password. I think the for loop isn't working correctly. The retVal is returned empty because the for loop isn't passing it anything. I tried removing the charAt function and having the Math.floor give me just and index, that just gave me undefinedundefinedundefinedundefinedundefinedundefined. Back with the regular charAt function I'm getting nothing.

var length = prompt("How many characters will your password be? Enter a number between 8 and 128");

//ask for character type
var charType = prompt("Enter a character type: special, numeric, uppercase, lowercase.");

//generate password
function generatePassword() {
  //evaluate character type
  var charSet = "";
  if( charType.toLowerCase === "lowercase" ) {
    charSet = "abcdefghijklmnopqrstuvwxyz";
  } else if( charType.toLowerCase === "uppercase" ) {
    charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  } else if( charType.toLowerCase === "numeric" ) {
    charSet = "0123456789";
  } else if( charType.toLowerCase === "special" ) {
    charSet = " !\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~";
  } 
  //return value
  var retVal = "";
  //for (var i = 0, n = charSet.length; i < length; i++) {
    for (var i = 0, n = length; i < length; i++) {
    //picks a character within charSet at index of random number
    retVal += charSet.charAt(Math.floor(Math.random() * n));
  }
  console.log(retVal);
  return retVal;
}```



Python: Long list with weighted probabilities, choose one element [duplicate]

This question already has an answer here:

I have two lists, each of length 100. The first list contains indices (call this list i) and the second contains the probability that each of those indices will be selected (call this list P). I would like to choose one index using the given probabilities.

I have tried to use the following code:

index = random.choice(i, P)

to select one index from the list. However, I get the error:

ValueError: sequence too large; cannot be greater than 32

Is there a way to get around this error and select an element from a larger (100 element) list with weighted probabilities? Perhaps there is another function besides numpy.random() that I can use? Or maybe a way to look at only 32 elements of the list at one time (although I'm concerned about altering the given probability distribution)? Thank you in advance for your help!




Make a dice rolling game

A normal six-sided dice is thrown six times; the user must guess a number each time the dice is thrown. If the number matches the guess, the user wins a point. Score 4 points to win. I'm working on a project to make a dice throwing game. The goal is to guess the number that the dice is going to land on, and to repeat this loop until the user chooses to exit the program. Currently I'm just working on getting the inital stage to work, but for some reason my dice is coming up with an extremely large number and due to my limited understanding of srand I don't know how to fix it, so any help would be greatly appreciated

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

int main()
{
    int runs, correct, correct_guesses, guess;

    srand(time(NULL));
    correct_guesses = 0;

    int roll = ((rand() % 6) + 1);
    printf("Please guess the number the dice will land on\n");
    printf("%d", &roll);
    scanf("%d", &guess);
    {
        switch (guess)
        {
        case '1': correct = 1 == roll; break;
        case '2': correct = 2 == roll; break;
        case '3': correct = 3 == roll; break;
        case '4': correct = 4 == roll; break;
        case '5': correct = 5 == roll; break;
        case '6': correct = 6 == roll; break;
        default: correct = 0; printf("Not a possible outcome\n");
        }
    if (correct)
    {
        printf("You guessed correctly!\n");
    }
    else
        printf("You guessed incorrectly\n");
    }
}



jeudi 26 décembre 2019

How do I grab random elements on python from paired lists?

I tried to compare drop height versus rebound height and have some data here:

drop_heights = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.7, 2.0]
rebound_heights = [0.16, 0.30, 0.46, 0.6, 0.74, 0.88, 1.02, 1.15, 1.34, 1.51]

I want to select 5 random data points off of these variables, so I tried

smol_drop_heights = []
smol_rebound_heights = []

for each in range(0,5):
     smol_drop_heights.append(drop_heights[randint(0, 9)])
     smol_rebound_heights.append(rebound_heights[randint(0, 9)])
print(smol_drop_heights)
print(smol_rebound_heights)

When they print, they print different sets of data, and sometimes even repeat data, how do I fix this?

[0.8, 1.6, 0.6, 0.2, 0.12]
[1.02, 1.15, 0.88, 0.88, 0.6]

Here is a sample output, where you can see .88 is repeated.




how to generate random numbers in integer range in python

How can i generate random numbers in range of integer or float in python? Something like this code:

random.randrange(int)

I don't like enter number directly like the below code:

random.randrange(32768)



Using Event Listeners (Javascript, jQuery) to change BG color to a random color?

I am attempting a simple random background color generator. When a user clicks the button, the background color changes to a random RGB value. However, I also want the button itself to change to that random color when clicked.

I tried putting DOM manipulators in the event listener and in the random RGB function. However I keep getting this error message:

script.js:19 Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
    at randomBgColor (script.js:19)
    at HTMLButtonElement.<anonymous> (script.js:7)
randomBgColor @ script.js:19
(anonymous) @ script.js:7

The code is as follows:

<html>
<button id="press" class="button">Press me to change the background color!</button>
</html>
var changeColor = document.getElementById("press");
var button = document.getElementsByClassName("button");



changeColor.addEventListener("click", function(){
    randomBgColor();

})


function randomBgColor() {
    var x = Math.floor(Math.random() * 256);
    var y = Math.floor(Math.random() * 256);
    var z = Math.floor(Math.random() * 256);
    var bgColor = 'rgb(' + x + ',' + y + ',' + z + ')';
    console.log(bgColor);
   document.body.style.background = bgColor;
   button.style.backgroundColor = bgColor;

} 



Randomness and multiprocessing [duplicate]

This question already has an answer here:

I've got a c++ program which is executed multiple times in parallel in a python script. The c++ program generates data utilizing rand(). The multiple processes are all generating identical data, presumably because they are all opened at the same time (I use srand(time(NULL)) as the seed.) How do I force the sub processes to diverge?




How to avoid randomizing image from array which is in image_view?

If I do this, it sometimes sets the same image as it was in image_view. For example, if R.drawable.cat__5_ is in image_view I want to select from R.drawable.cat__3_,R.drawable.cat__4_,R.drawable.cat__6_,R.drawable.cat__7_,R.drawable.cat__8_. How it can be done?

 var cats = intArrayOf(
                R.drawable.cat__3_,
                R.drawable.cat__4_,
                R.drawable.cat__5_,
                R.drawable.cat__6_,
                R.drawable.cat__7_,
                R.drawable.cat__8_)

    button.setOnClickListener{
    random = Random()
    image_view.setImageResource(cats[random.nextInt(cats.size)])



How to prevent an object from being randomly extracted from a list if it has already been extracted?

Once a movie gets extracted, I want the function not to randomly extract it anymore the next time (since I've alreadt watched it). How do I do this? Thank you!

import random
from typing import List

sad_movies = random.choice(["Sad1", "Sad2", "Sad3"])
happy_movies = random.choice(["Happy1", "Happy2", "Happy3"])


mood = input("How are you feeling today? ").lower().title()

def moodmovie():
    if mood == "Happy":
        print("Since you're feeling " + mood.lower() + ", watching... " + happy_movies + " sounds good")
    elif mood == "Sad":
        print("Since you're feeling " + mood.lower() + ", watching... " + sad_movies + " sounds good")
    else:
        print("Try again. Either you're happy or you're sad. How are you feeling today? ")

print(moodmovie())



mercredi 25 décembre 2019

Random sinusoidal signal generation with defined Amplitude and Phase

Write a MATLAB program to generate and display five sample sequences of a random sinusoidal signal of length 31

{X[n]} = {A · cos(ωon + φ)}

where the amplitude A and the phase φ are statistically independent random variables with uniform probability distribution in the range 0 ≤ A ≤ 4 for the amplitude and in the range 0 ≤ φ ≤ 2π for the phase.




Python while loop, print one item from array without it being printed twice in a row

I want pyautogui to type days in a month from 1 to 31. Bellow each number I want it to type city name from an array. Problem is that when loop finishes, in the next run it has a chance to print the same city which I don't want. It can and should print it again just not twice in a row.

I tried several options I was able to Google but none worked. Here's my code. If you have suggestions on how to fix it or completely new code please let me know.

import pyautogui, random

dayDate = 1
while dayDate < 32:
    pyautogui.click(380, 325)
    pyautogui.typewrite(str(dayDate))
    pyautogui.click(380, 345)
    cities = ['London', 'Paris', 'Berlin', 'Barcelona', 'Moscow']
    city = random.choice(cities)
    print(city)
    pyautogui.typewrite(str(city))
    dayDate += 1

Just that I'm clear, preferable output in terminal should not have same city twice in a row.

Eg:

  1. London 2. Berlin 3. Berlin 4. Moscow - wrong

  2. Berlin 2. London 3. Berlin 4. Moscow - correct




How can i make my random number generator stop producing the same numbers?(Java)

I have created a random number generator and i want to avoid repeating the same values. Here is my code:

function function1(){
var randomNumber = Math.floor(Math.random() * 30) + 1;
var imgName = "pic (" + randomNumber + ").jpg";
document.getElementById("imgid2").src="Pictures" + "/" + imgName;



Generating a random integer in a range while excluding a number in the given range

I was going through the BERT repo and found the following piece of code:

for _ in range(10):
    random_document_index = rng.randint(0, len(all_documents) - 1)
    if random_document_index != document_index:
        break

The idea here being to generate a random integer on [0, len(all_documents)-1] that cannot equal document_index. Because len(all_documents) is suppose to be a very large number, the first iteration is almost guaranteed to produce a valid randint, but just to be safe, they try it for 10 iterations. I can't help but think there has to be a better way to do this.

I found this answer which is easy enough to implement in python:

random_document_index = rng.randint(0, len(all_documents) - 2)
random_document_index += 1 if random_document_index >= document_index else 0

I was just wondering if there's a better way to achieve this in python using the in-built functions (or even with numpy), or if this is the best you can do.




Is there a way to ordinate numbers in a list?

I'm working on a table game called 'tombola' (I don't know the name in English). The code gives me a list of numbers:

['22', '25', '75', '52', '70', '14', '5', '60', '81', '83', '72', '2', '36', '78', '10', '65', '43', '74', '51', '9', '29', '49', '24', '76', '23', '67', '35', '8', '85', '59', '18', '66', '38', '27', '19', '57', '77', '42', '84', '11', '46', '13', '89', '62', '7', '39', '32', '50', '86', '44', '64', '79', '54', '12', '68', '34', '15', '69', '71', '45', '20', '41', '82', '16', '1', '48', '37', '58', '61', '56', '53', '40', '80', '31', '87', '73', '90', '3', '88', '55', '30', '21', '4', '63', '26', '28', '33', '6', '17']

I need to ordinate these numbers in a crescent way and have an output that looks something like this:

['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90']



how to randomize an json array php

<?php
header('Content-type: application/json');
$arr = array('success' => true, 'key' => "random", 'valid_until' => "2020-12-23 23:38:53", 'pid' => LssBot, 'token' => "QmBLOJmCRWe+jdVyKKSUJaxtMDPloLFyuQ490USkRQSFxEiBMjzsjd+34IoxryTVw7OZH8p7zY4vdewkyML5oLe75VchNTaWTS6OUPCDaPEM+nevz\/3n9NBv+v2mm\/C2YamlApCPhR+vJm376MFKYuNZz1CqUgt5LhEG3lgAOHHlqydS5tBc1L\/0VrnHuvWzClCUcrQ31s9Igo2C2+g\/LosARCqSIZB+1x9nOiFhiSKYKPqzEbHXwZybEhX7ztQ63U0bQEG6k0qHl+PObkR8ap7qHXDjrj2Dh5BVOe5jVQZC19qt8NQ9qlnxfqOqPIKaC\/2fLrWCJAGpfxanltNuXW+HXAnulrTDKrO430tbwR0=", 'r' => "b22831623da8b1e20a76376f057455da", 'xt' => "2");

echo json_encode($arr);

?>

i want to randomize the key value 'key' => "random" as 32 random numbers




why is this code not putting out the questions?

import random

def get_questions():
    questionBank = []
    questionBank.append(["how many steps are in the eiffel tower?", "1770", "10838"])
    questionBank.append(["how many different flavours of gummy bears are there?", "4", "5"])
    questionBank.append(["how many pizzas are eaten in the US per year?", "3 billion", "1,5 million"])

    return questionBank


def play_quiz():
    questions = get_questions()

    random.shuffle(questions)

    s: List[str]
    for s in questions:
        print(s[0] + "is it" + s[1] + "or" + s[2])

When I run this it simply does not print anything. Can someone help me understand why




Using SMOTE Function with Multi levels class

My data set contains 14 variables and my class has 4 levels. The data set is heavily imbalanced and I'm trying to use the SMOTE function to balance it. However it under samples my data. Is there any one who knows how to use the SMOTE function with 4 level classifiers?

The code I used is

smoteprogram1 <- SMOTE(Programs ~ ., DecisionT_dATA,perc.over = 100 , perc.under = 200)

where DecisionT_dATA is my data set and program is my classifier

My data have 1143 obs and when I run the command I get 116 obs which is really weird.

appreciate your help thanks




mardi 24 décembre 2019

Unique Id Generator and Randomizer VBA

I am trying to a few items for a Secret Santa spreadsheet.

  1. A Unique ID generator to print the UID in Column B for a list of names in Column A and

  2. A randomizer to print the ID numbers in a random order in Column C with the restraint that Column B UID cannot equal Column C UID, ensuring no one "gets themselves in the Secret Santa."

  3. List Name for the random UID in Column C in Column D.

The UID's are to start at 1 and then count until the last name receives an ID. I also want the generator to be able to handle creating an ID for a name that is added anywhere within the list (beginning, middle, end).

I have done some research, but found some quite complicated answers here and on other websites. Some use complicated looping others the GUID function that I am not quite sure I understand. In general, the answers are for existing lists and not a new list with no UID's.

I am a beginner at coding/software architecture so I assume that I would want to:

1) Create the UID's and print them to Column B. 2) Save Column A and B into an array?? 3) Randomize and Print the UID's into Column C. 4) Use the array to get the name for the randomized UID's in Column C and print the corresponding name in Column D.

I am unsure if this methodology is a "good" approach for this type of problem, but I would be interested in hearing any other methodologies as well. If any one could help me with the code it would be greatly appreciated. The only thing I have so far is the row counter which is below.

Sub secret_santa()

Dim person_count As Integer
Dim uid As Integer

'Count Number of Used Rows
person_count = ActiveSheet.UsedRange.Rows.Count

'Subtract Header from person_count
person_count = person_count - 1

End Sub




More efficient and general way of getting a random integer from multiple lists of different lengths

What I want is to be able to have mutable lists of mutable length and draw a random number from these lists. The trick is that these lists are different sizes so if a list is smaller than the others a number from it should not come up as often as from the other bigger lists.

Here's what I have now:

 import random

 a = 1
 b = 11
 c = 111
 d = 1111
 e = 11111
 f = 111111
 g = f - e
 q = (f - e) + (d - c) + (b - a)
 r = ((f - e) / q ) * g
 s = g - ((b - a) / q ) * g

 low = 1
 mid = 1
 high = 1

 i = 1
 while i < 666666:
     x = random.randint(a, b)
     y = random.randint(c, d)
     z = random.randint(e, f)
     v = random.randint(1, g)
     if v < r:
         print(z)
         high += 1
     else:
         if v > s:
             print(x)
             low += 1
         else:
             print(y)
             mid += 1
     i += 1

 print(low, mid, high)



  ...
  72027
  81188
  57 6579 660032

It works, but it's very crude and requires me to know which list is the longest, etc. Thanks.




PHP Random string generation miraculously generated the same string

So I've got a fairly simple function in PHP that renders 10 character long order IDs:

function createReference($length = 10)
    {
        $characters = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $string;
    }

However, today on the 154020th table record, it generated the same 10-character ID as a previous order ID (which was the 144258th record in the table), and tried to insert it. Since I have a UNIQUE restriction on the column, I got an error and I received a notification from this.

According to my calculations, the script above creates 34^10 = 2.064.377.754.059.776 different possibilities.

I've read some stuff about rand() and mt_rand() doing different stuff but that shouldnt be an issue on PHP 7.1+. The script is running on PHP 7.3.

So should I buy a lottery ticket right now, or is there something predictable about the pseudo-randomness being used here? If so, what is a solution to have better distribution?




Random word generator from external file in Python

I'm trying to create a small program to allocate words randomly to describe a tree. For some reason only the first letter of the word is printed. The "words.txt" file contains ~ 3000 adjectives. Please advise on how to print the full word. I've been trying to figure this out for a while and cannot find a solution.

Here is the code:

import random


def a_word():
    file = open('words.txt', 'r')
    random_word = random.choice(file.readline())
    print('The %s tree.' % random_word)
    return


a_word()



How do I fix my For loop and Random problem in Android?

 public class PlayerData{

int id; // id means Player's order
boolean isTeacher;

public PlayerData() {

}

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

public void setTeacher() {
    isTeacher = true;
}

}

public class Singleton {

public int time;
public int total; // number of total players
public int teacher; // number of teachers
public int student; // number of students
-
public int count = 1;
public String keyWord; // 
ArrayList<PlayerData> playerArrayList = new ArrayList<PlayerData>();

// method init creates Objects of players
public void init() {
    for (int i = 1; i <= total; i++) {
        PlayerData player = new PlayerData();
        player.setID(i);  // set id
        playerArrayList.add(player); // add player Object to ArrayList
    }
}

public void JobSelection() {

    int a[] = new int[teacher]; // Make array to the number I will select
    Random r = new Random(); // Random Object
    PlayerData player = new PlayerData();
    for (int i = 0; i < teacher; i++)    // for loop to select Teachers 
    {
        a[i] = r.nextInt(total) + 1; //select a number from 1~total and Save in a[0]~a[total]
        for (int j = 0; j < i; j++) //for loop to avoid overlap
        {
            if (a[i] == a[j]) {
                i--;
            }
        }

        if (a[i] == player.id) { 
            playerArrayList.get(player.id - 1).isTeacher = true;
        }
    }
} ...

public class RoleSelection extends AppCompatActivity {
Singleton s1 = Singleton.getInstance();
PlayerData player = new PlayerData();

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

    TextView t1 = (TextView) findViewById(R.id.textJobConfirm);

    if (s1.playerArrayList.get(s1.player.id-1).isTeacher == true) {
        t1.setText(" You job is Teacher ");
    } else {
        t1.setText(" Your job is Student ");

I am making an app game whose job consists of only Teacher and Student. Codes above shows my app.

  1. There is a player class that has its data and setters
  2. There is a Singleton class that saves values in a variable such as total(total players), teacher, student etc.. Also Singleton class has ArrayList that creates Player's Objects.
  3. In Singleton class I made 2 methods: One for creating Objects in a ArrayList, the other for giving objects their jobs.
  4. JobSelection Method is trying to give a job to each player. For example if the total player chosen at game setting is 10 and teacher chosen is 4, I have to give 4 teacher jobs randomly to 10 player objects.
  5. After giving the players a job, I wrote code in 'Role Selection' class to setText differently considering player's job.

I don't have any errors in my logcat or in my app. However, I am only receiving "Your Job is Student". I guess the JobSelection method haven't worked well. So I tried to fix these codes ` for (int i = 0; i < teacher; i++) // for loop to select Teachers { a[i] = r.nextInt(total) + 1; //select a number from 1~total and Save in a[0]~a[total] for (int j = 0; j < i; j++) //for loop to avoid overlap { if (a[i] == a[j]) { i--; } }

    if (a[i] == player.id) { 
        playerArrayList.get(player.id - 1).isTeacher = true;
    }
}

`

But I failed to solve these problems... I will be grateful if someone answers me how can I make jobs distributed and see different TextView according to their jobs. Thank you




How to generate random numbers from the given numbers [duplicate]

This question already has an answer here:

I have an scenario to generate random numbers that should generate from the given numbers.

for example, I have an array num=[23,56,12,22]. so i have to get random number from the array




lundi 23 décembre 2019

Android show random numbers in TextViews

I want to generate random numbers from 1 to 9 and show each number in a different TextView (It is for a sudoku)

I have nine TextViews.

private TextView textView1;
private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
private TextView textView6;
private TextView textView7;
private TextView textView8;
private TextView textView9;

public void generateNumbers() {

// Random numbers int numbers =

textView1.setText();
textView2.setText();
textView3.setText();
textView4.setText();
textView5.setText();
textView6.setText();
textView7.setText();
textView8.setText();
textView9.setText();

}

In some squares I need to show 3 numbers and in other squares 4 numbers




Blackjack program with a problem with concationation

This is my blackjack python script. I was having an issue and I think it is a problem with the concatenation of the hit function. I have tried looking online and reading other questions but couldn't find one that applied. I am not sure if there are other problems with this script and if you find any please share. Thanks for any help if you can give any. This is my code:

import random
#run = True is a setup for a later use in a while true loop
run = True
#prints out a welcome
print("Welcome to blackjack in Python, hope you enjoy")
print("Side note: All Ace's are treated with a value of one")
#This generates all the cards and since their are 13 card not counting suites              
dealer_showing = random.randint(1, 13)
dealer_hiding = random.randint(1, 13)
player_1st_card = random.randint(1, 13)
player_2nd_card = random.randint(1, 13)
dealers_cards = dealer_hiding + dealer_showing
player_cards = player_1st_card + player_2nd_card
#Their is no card worth 11, 12, or 13 points in blackjack so this gives all "face cards" a value of 10
def check_13(who_to_check):
    if who_to_check >= 11:
        who_to_check = 10
        return who_to_check
#This uses the function seen up above
check_13(dealer_showing)
check_13(player_1st_card)
check_13(player_2nd_card)
check_13(dealer_hiding)
#This tells the user what their card value is and what the user is showing
print("Your card value is {}".format(player_cards))
print("The dealer is showing a {}".format(dealer_showing))

# Here I put in a function that checks if the player or computer have busted or won
def check_cards():
    if player_cards > 21 and dealers_cards > 21:
        print("Both you and the computer have busted")
        run = False
    elif player_cards > 21:
        print("I'm sorry the computer has won")
        run = False
    elif dealers_cards > 21:
        print("The computer has busted you win")
        run = False
    elif player_cards == 21 and dealers_cards == 21:
        print("Both you and the dealer have won")
    elif player_cards == 21:
        print("You have brought down the house")
    elif dealers_cards == 21:
        print("I'm sorry the computer has won")
    # Here I put in a function that hits
    def hit():
        player_cards = player_cards + check_13(random.randint(1, 10))
        return player_cards
        print("Your card value is now {}".format(player_cards))
    # Here I put in a function that lets the player stay
    def stay():
        if player_cards > dealers_cards:
            print("Congratulations you have won and beat the Computer")
            run = False
        elif player_cards == dealers_cards:
            print("You and the Computer have tied")
        else:
            print("I'm sorry the computer has won")
            False
    #Here is what the program runs over and over again in this loop
    while run == True:
        check_cards()
        print(player_cards)
        input_hit = input("Would you like to hit y/n:  ")

    if input_hit == "y":
        hit()
    elif input_hit == "n":
        stay()



Is there a way of combining the TRY and CATCH method and WHILE loop whilst using the RANDOM function [closed]

Is there a way to combine the try and catch method with the the while function whilst using the RANDOM function.

For Example:

      Console.WriteLine(guess a number);
      int b=Convert.ToInt32( Console.ReadLine());
      Random rnd = new Random();
      rnd.Next(1, 100);
      int a=0;


      while (a<15) 
      {

          try
            {
             Console.WriteLine`("invalid input outside the ranges:");
            }
        catch
            {

                Console.WriteLine("please write only whole numbers");
            }
      a++
    }

Thank you




php show data from an array in an order instead of random

I am showing data from an array in random using rand() . Is it possible to show the data in a systematic order instead of random ?

$one = data1;
$two = data2;
$three = data3;
$myarray = array($one, $two, $three)
$show = $myarray[rand(0,2)];

Note the $show variable is called dynamically in page & it outputs values of $myarray at many places on page

Ex. It outputs above array in random orders as data2,data1,data3,data3,data2,data1......

How do i code the above so that the result on page will be in a systematic order i.e. first to be shown will be the 1st value of array i.e. data1 then data2 then data3 then again data1 then data2 then data3 & so on...




Trying to add a unique record_id number to a php RAND function

I have a website that I use PHP and mysql database and Apache server and I have a record page and it has a unique record_id number each record gets a unique record_id number and I get to my photo gallery page from the record page and the unique record_id number goes to the photo gallery page throw the URL, and in the photo gallery page I can upload image to my server uploads folder where the image ($image_name) and the thumbnail ($image thumbnail_name) go to and the unique record_id number and title and record_date and image_name and thumbnail_name go to my database in the recoed_images table. and when I upload a image it gets the name of the image change to a rand number by using a php ($image_name = rand (1000,9999).".".$fileExt;) all that works good but I need the unique record_id number to be add infront of the RAND number so the images will have a name like (record_id=1_5826) and (record_id=1_thumbnail_5826) or like (record_id=2_9631) and (record_id=1_thumbnail_9631) so I can filter the image by the record_id number in the photo gallery page so you will only see the images for that one record.can that be done?




Python- np.random.choice

I am using the numpy.random.choice module to generate an 'array' of choices based on an array of functions:

def f(x):
    return np.sin(x)

def g(x):
    return np.cos(x)


base=[f, g]

funcs=np.random.choice(base,size=2)

This code will produce an 'array' of 2 items referencing a function from the base array.

The reason for this post is, I have printed the outcome of funcs and recieved:

[<function f at 0x00000225AC94F0D0> <function f at 0x00000225AC94F0D0>]

Clearly this returns a reference to the functions in some form, not that I understand what that form is or how to manipulate it, this is where the problem comes in. I want to change the choice of function, so that it is no longer random and instead depends on some conditions, so it might be:

for i in range(2):
    if testvar=='true':
        choice[i] = 0 
    if testvar== 'false':
        choice[i] = 1

This would return an array of indicies to be put in later function

The problem is, the further operations of the code (I think) require this previous form of function reference: [ ] as an input, instead of a simple array of 0,1 Indicies and I don't know how I can get an array of form [ ] by using if statements.

I could be completely wrong about the rest of the code requiring this input, but I don't know how I can amend it, so am hence posting it here. The full code is as follows: (it is a slight variation of code provided by @Attack68 on Evolving functions in python) It aims to store a function that is multiplied by a random function on each iteration and integrates accordingly. (I have put a comment on the code above the function that is causing the problem)

import numpy as np
import scipy.integrate as int

def f(x):
    return np.sin(x)

def g(x):
    return np.cos(x)

base = [f, g]

funcs = np.random.choice(base, size=2)
print(funcs)
#The below function is where I believe the [<function...>] input to be required
def apply(x, funcs):
    y = 1
    for func in funcs:
        y *= func(x)
    return y

print('function value at 1.5 ', apply(1.5, funcs))

answer = int.quad(apply, 1, 2, args=(funcs,))
print('integration over [1,2]: ', answer)

Here is my attempt of implementing a non-random event:

import numpy as np
import scipy.integrate as int
import random
def f(x):
    return np.sin(x)

def g(x):
    return np.cos(x)

base = [f, g]

funcs = list()
for i in range(2):
    testvar=random.randint(0,100) #In my actual code, this would not be random but dependent on some other situation I have not accounted for here
    if testvar>50:
        func_idx = 0 # choose a np.random operation: 0=f, 1=g
    else:
        func_idx= 1
    funcs.append(func_idx)
#funcs = np.random.choice(base, size=10)
print(funcs)
def apply(x, funcs):
    y = 1
    for func in funcs:
        y *= func(x)
    return y

print('function value at 1.5 ', apply(1.5, funcs))

answer = int.quad(apply, 1, 2, args=(funcs,))
print('integration over [1,2]: ', answer)

This returns the following error:

TypeError: 'int' object is not callable



Random Equation Test. Correct or Wrong answer

I have been trying to write a test which involves random numbers to make equations for the user to answer. I have wrote it so that two int are assigned to a random number and the console writes the equation. I have used an if statement for the program to dictate whether the users answer is correct or incorrect. However it is always either correct or incorrect depending on the code i write. I can't write it so that the program decides the answer.

        int iE3 = rnd.Next(1, 11);
        int iE13 = rnd.Next(1, 11);
        int iA3 = iE3 * iE13;
        int answer3 = iE3 * iE13;
        Console.WriteLine("The third equation is {0} * {1}", iE3, iE13);
        Console.ReadLine();

        if ( answer3 == iA3)
        {
            Console.WriteLine("Well done you got it right!");
        }
        else
        {
            Console.WriteLine("Unfortunately you got it incorrect.");
        }



dimanche 22 décembre 2019

C++ Arduino - Random Function doesn't work

Hi C++ Devs and StackOverflow users!

The code following is what I did, but some reason, random function doesn't work, or output for a result always the same value which is '1', did I do anything wrong? How should I fix this issue?

  void setup()           
  {
  int randNumber;
  int i;

  randNumber = random(2);
  Serial.println(randNumber);
  pinMode(PIEZO, OUTPUT);
  delay(3000);

  if (randNumber == 0)
  {
    for (i = 0; i < 105; i++)                                       
    {
      tone(PIEZO, notes[i], time[i]);                                
      delay(time[i]);
    }
  }
  else if (randNumber == 1)                                     
    for (i = 0; i < 116; i++)                                       
    {
      tone(PIEZO, Snowman_Notes[i], Snowman_Rhythm[i]);                                  
      delay(Snowman_Rhythm[i]);
    }
}
void loop()                                                      
{
}



std::rand and randomized quick sort algorithm [duplicate]

This question already has an answer here:

I am trying to implement a quick sort algorithm in c++ where the pivot used for the partitioning is randomly selected. Currently, I am using std::rand() to randomly select the pivot.

However, I have read that the header contains more varied and useful algorithms for randomly generating numbers.

I am unsure if I should just use std::rand() or if I should use one of the random number generators in the header. I feel like the header seems to be a bit more than I need because I do not need any special algorithm to generate random numbers.

My question is, am I wrong in this assessment and, if so, which random number engine from the header should I use?




How to randomize image from array but don't repeat previous image after, which is in image_view?

I want to set random image from array

var randomElement = array[random.nextInt(array.size)]
                image_view.setImageResource(randomElement)

But after that don't repeat it

 button.setOnClickListener {
        if (image_view.drawable.constantState != ContextCompat.getDrawable(
                            this,
                            R.drawable.myImage
                        )?.constantState{
        var randomElement = array[random.nextInt(array.size)] //but exclude R.drawable.myImage
    }
}

How it can be excluded from array and after that added to avoid repeating only last previous image?




random sampling and assigning weights

Are there functions in R that I can use to create or assign weight (from 0 to 1) to variables? How do I custom make weights based on other variable characteristics (such as geographic location and or urban location(yes=1 or no=2).

I want the weight to increase (the probability to be sampled increases) as the variable (location) gets closer to large urban centers

Any ideas of the R code for this?




Genetic algorithm tournament selection, random.choice() pick same parents

I'm trying to implement a genetic algorithm, the problem is when population gets smaller, my function tournament_selection return the same parents. Here is the two main function

def crossover(agents, x):
offspring = []

for _ in range(len(agents)):
    p1 = tournament_selection(agents)
    p2 = tournament_selection(agents)
    split = random.randint(0, len(p2.individual) - 1)
    child1 = p1
    child1.individual = p1.individual[0:split] + p2.individual[split:len(p1.individual)]
    offspring.append(child1)
agents = offspring
return agents


def tournament_selection(population):
parents = random.choices(population, k=5)
parents = sorted(parents, key=lambda agent: agent.fitness, reverse=True)
bestparent = parents[0]
return bestparent



How to get 5 random numbers with a certain probability? [duplicate]

How to write python with:

Generate 5 random numbers with a certain probability from number 1-25(no repeat)

Like generate 1 has 5%, 2 has 7% something like that




samedi 21 décembre 2019

How can i randomize a list of questions in python 3.8?

def get_questions():
    # Notice how the data is stored as a list of lists
    return [
            ["What color is the daytime sky on a clear day? ", "blue"],
            ["What is the answer to life, the universe, and everything? ", "42"],
            ["What is a three letter word for a mouse trap? ", "cat"],
            ["Who portrayed Edward Scissorhands? ", "Johnny Depp"],
            ["What are made and repaired by a cobbler? ", "shoes"],
            ["Apart from womanizing and producing films, what was the other passion of Howard Hughes? ", "aviation"],
            ["How many states make up The United States of America? ", "50"],
            ["H20 is the chemical formula for what? ", "water"],
            ["Complete the title of the play by Shakespeare - 'The Merchant of ? ", "Venice"],
            ["Brie and Camembert are types of what food? ", "cheese"],
            ["What type of creature lives in an aviary? ", "bird"],
            ["How many players make a Rugby Union team? ", "15"],
            ["What decade Did Elizabeth become Queen? ", "1950's"],
            ["The phrase '3 strikes and you are out' is in what sport? ", "baseball"],
            ["In which sport can a player score a 'Birdie,' 'Eagle,' 'Albatross'? ", "golf"],
            ["How many English monarchs have been named 'Edward'? ", "8"],
            ["Where is the Great Barrier Reef? ", "Australia"],
            ["Which English county is known as 'Shakespeare's County'? ", "Warwickshire"],
            ["A pug is a breed of what animal? ", "dog"],
            ["How many colors are in a calico cat? ", "3"]]

This is part of my python code I'm attempting to make into a quiz. I have tried to use the random.shuffle(get_questions) code after the questions, but it doesn't work. I'd like to know what else i can do to make this produce random questions each time it's run.




How do i get a random int with 2 variables?

im trying to build a little number guessing game. im trying to pass 2 variables into a random.randint function but can't get it to work. im trying to get the users input on what the lowest possible secret number and the highest possible secret number i gonna be in the particular game. and then take a random number between the two inputs

this is how my code looks.

 lower_limit_sn = int(input('Decide the lowest possible secret number: '))
print(f'{lower_limit_sn}')

upper_limit_sn = int(input('Decide the highest possible secret number: '))
print(f'{upper_limit_sn}')

secret_number = random.randint({lower_limit_sn}, {upper_limit_sn})

and this is the error i get:

Traceback (most recent call last):
  File PycharmProjects/HelloWorld/While_loops.py", line 26, in <module>
    secret_number = random.randint({lower_limit_sn}, {upper_limit_sn})
  File AppData\Local\Programs\Python\Python37-32\lib\random.py", line 222, in randint
    return self.randrange(a, b+1)
TypeError: unsupported operand type(s) for +: 'set' and 'int'



How to sample different number of rows from each group in DataFrame (Python)

I have a dataframe with a category column. Df has different number of rows for each category.

category number_of_rows
cat1     19189
cat2     13193
cat3     4500
cat4     1914
cat5     568
cat6     473
cat7     216
cat8     206
cat9     197
cat10    147
cat11    130
cat12    49
cat13    38
cat14    35
cat15    35
cat16    30
cat17    29
cat18    9
cat19    4
cat20    4
cat21    1
cat22    1
cat23    1

I want to select different number of rows from each category. (Instead of n fixed number of rows from each category)

Example input:
size_1 : {"cat1": 40, "cat2": 20, "cat3": 15, "cat4": 11, ...}
Example input: 
size_2 : {"cat1": 51, "cat2": 42, "cat3": 18, "cat4": 21, ...}

What I want to do is actually a stratified sampling with given number of instances corresponding to each category.

Also, it should be randomly selected. For example, I don't need the top 40 values for size_1.["cat1"], I need random 40 values.

Thanks for the help.




Why does this randint not work in an if statement?

import time
import random
def printgrid():
  print(grid[0][0],grid[0][1],grid[0][2])
  print(grid[1][0],grid[1][1],grid[1][2])
  print(grid[2][0],grid[2][1],grid[2][2])
grid=[['-','-','-'],['-','-','-'],['-','-','-']]
print('TIP: It might be a good idea to turn on CAPSLOCK for this game.')
time.sleep(2)
printgrid()
print('This is the Noughts and Crosses board. Make your move: \n |topleft=TL   |topcenter=TC   |topright=TR  |\n |middleleft=ML|middlecenter=MC|middleright=MR|\n |bottomleft=BL|bottomcenter=BC|bottomright=BR|')
validmove=False
while validmove==False:
  move=str(input('move:'))
  if move=="TL":
    grid[0][0]='x'
    validmove=True
  elif move=="TC":
    grid[0][1]='x'
    validmove=True
  elif move=="TR":
    grid[0][2]='x'
    validmove=True
  elif move=="ML":
    grid[1][0]='x'
    validmove=True
  elif move=="MC":
    grid[1][1]='x'
    validmove=True
  elif move=="MR":
    grid[1][2]='x'
    validmove=True
  elif move=="BL":
    grid[2][0]='x'
    validmove=True
  elif move=="BC":
    grid[2][1]='x'
    validmove=True
  elif move=="BR":
    grid[2][2]='x'
    validmove=True
  else:
    print('invalid move')
printgrid()
omove=random.randint(0,8)
print(omove)
validmove=False
while validmove==False:
  omove=random.randint(0,8)
  print(omove)
  if omove=="0":
    grid[0][0]='o'
    validmove=True
  elif omove=="1":
    grid[0][1]='o'
    validmove=True
  elif omove=="2":
    grid[0][2]='o'
    validmove=True
  elif omove=="3":
    grid[1][0]='o'
    validmove=True
  elif omove=="4":
    grid[1][1]='o'
    validmove=True
  elif omove=="5":
    grid[1][2]='o'
    validmove=True
  elif omove=="6":
    grid[2][0]='o'
    validmove=True
  elif omove=="7":
    grid[2][1]='o'
    validmove=True
  elif omove=="8":
    grid[2][2]='o'
    validmove=True
  else:
    print('something is wrong')
    validmove=False
time.sleep(2)
printgrid()

It just continually out puts "something is wrong" and the omove it is using. BTW I am doing Naughts and crosses project. I have tried to make this work and checked everything so either i am blind(most likely) or there is somthing wrong with Repl.it (I am using Repl.it (https://repl.it/)).

Here is the output:

something is wrong
6
something is wrong
3
something is wrong
7
something is wrong
8
something is wrong
2
something is wrong
5
something is wrong
8
something is wrong
3



Why do I get several records in select using random function in postgres?

This is my query:

SELECT id, geom from lars.punkt where id = (floor(random () * 99))::integer;

This is the result:

id    geom
40  "010100000000000000000010400000000000000000"
80  "010100000000000000000020400000000000000000"
88  "010100000000000000000020400000000000002040"

What is happening? I can also get 2 lines or zero lines.

I am expecting 1 line.

Is it the database which is "slow" or the code?




How can I save the random numbers and count how many times they appeared throughout the game?

So I'm trying to do lottery game and I'm supposed to write down top 3 numbers that appeared throughout the game in the Statistics. But I'm not sure how to save or count how many times a number appeared.

int i,s,ans,ans1;
 MENU: ;
srand(time(0));
printf("[1]-Play The Game\n[2]-Statistics\n");
scanf(" %d",&ans1);

if(ans1==1){

PLAY: ;
    for(i=1;i<=5;i++){
      s=1+rand()%9;
      printf("%d.number=%d \n",i,s); }

 QUESTION: ;
  printf("\nWant to roll again? \n [1]-Yes\n[2]-No\nAnswer:");
  scanf("%d",&ans);
      if(ans==1)
        goto PLAY;
      else if (ans==2)
        goto MENU;
      else
        goto QUESTION;
  }

   else if (ans1==2){
    printf("\n\t Welcome to Statitistics");

    for(int a=0;a<3;a++){
        printf("\n%d",s);
    }

   }
  return 0;
 }



use Math.random inside ReactHook

I'm learning react since 2-3 days and I've stumbled into a problem when using Math.random() inside a functional component with React Hook.

Let me explain: suppose I want to code a game where there is a random number generated and the user needs to guess it. I thought about something like that:

function App() {
    const [users, setUsers] = useState("")
    let tbg = Math.floor(Math.random()*100)

    const handleSubmit = () => {
        if(users === tbg) {
            alert("Correct")
        }
        else if(users < tbg) {
            alert("More")
        }
        else {
            alert("Less")
        }
    }
  return (
    <div className="App">
      <h2>Guess the number</h2>
        <h3>(for debug=>) the number is : {tbg} </h3>
        <br/>
        <form onSubmit={handleSubmit}>
            <input type="text" value={users} onChange={e => setUsers(e.target.value)} />
        </form>
    </div>
  );
}

The problem is each time the user input a character/digit the number to be guessed is changed. I thought about a solution by putting the Math random into a function and execute it conditionally. But, I wanted to know if there is a better "a react-hook-way" to do it.

Thank you




vendredi 20 décembre 2019

Looping inside a Postgres UPDATE query

(Postgres 10.10) I have the following fields in my_table:

loval INTEGER 
hival INTEGER 
valcount INTEGER 
values INTEGER[]

I need to set values to an array containing valcount random integers each between loval and hival inclusive. So for:

loval: 3 
hival: 22 
valcount: 6

I'm looking to set values to something like:

{3, 6, 6, 13, 17, 22}

I know how to do this with an inefficient "loop through the cursor" solution, but I'm wondering if Postgres has a way to do a looping computation inline.

Note: I looked at generate_series, but I don't think it produces what I need.




Max Length of ThreadLocalRandom.current().nextLong()

I'm planning to use ThreadLocalRandom.current().nextLong() to generate IDs across various threads. The application's criteria is to have 19 digits numeric value. We used System.nanoTime() before with padding but lately its been generating same IDs.

I tried using ThreadLocalRandom.current().nextLong() and it's generating 19 digits long value. Is the value for it always 19 digits or it can be less than 19 digits too? And is it safe to use between multiple threads?




Weird behavior of zipped tensorflow dataset with random tensors

In the example below (Tensorflow 2.0), we have a dummy tensorflow dataset with three elements. We map a function on it (replace_with_float) that returns a randomly generated value in two copies. As we expect, when we take elements from the dataset, the first and second coordinates have the same value.

Now, we create two "slice" datasets from the first coordinates and the second coordinates, respectively and we zip the two datasets back together. The slicing and the zipping operations seems inverses of each other, so I would expect the resulting dataset to be equivalent to the previous one. However, as we see, now the first and second coordinates are different randomly generated values.

Maybe even more interestingly, if we zip the "same" dataset with itself by df = tf.data.Dataset.zip((df.map(lambda x, y: x), df.map(lambda x, y: x))), the two coordinates will also have different values.

How can this behavior be explained? Perhaps two different graphs are constructed for the two datasets to be zipped and they are run independently?

import tensorflow as tf

def replace_with_float(element):
    rand = tf.random.uniform([])
    return (rand, rand)

df = tf.data.Dataset.from_tensor_slices([0, 0, 0])
df = df.map(replace_with_float)
print('Before zipping: ')
for x in df:
    print(x[0].numpy(), x[1].numpy())

df = tf.data.Dataset.zip((df.map(lambda x, y: x), df.map(lambda x, y: y)))

print('After zipping: ')
for x in df:
    print(x[0].numpy(), x[1].numpy())

Sample output:

Before zipping: 
0.08801079 0.08801079
0.638958 0.638958
0.800568 0.800568
After zipping: 
0.9676769 0.23045003
0.91056764 0.6551999
0.4647777 0.6758332



Randomly assigning a waiter from a list of waiters and cooks

I have tried to assign a random waiter using a while loop and then an if statement however when choosing a second index inside the while loop the java gives error is the cohsen index is a cook how can I fix this? This is my method:

public Waiter assignWaiter() {

    Random rand = new Random();

    int index = rand.nextInt(employees.size());
    Employee assignedWaiter = employees.get(index);
    while (!(employees.get(index) instanceof Waiter)) {
        index = rand.nextInt(employees.size());
        if ((Waiter) employees.get(index) instanceof Waiter) {
            assignedWaiter = (Waiter) employees.get(index);
            return (Waiter) assignedWaiter;

        }

    }
    return (Waiter) assignedWaiter;
}



not able to convert multidimentional list to a sentence using python

import random
p = ['hello','hey','hi'],['brother','bro','sir'],['me','myself'],['a'],['hero']
print(random.choices(random.choices(p)))

Desired output : hello bro myself a hero




jeudi 19 décembre 2019

Create a race in Python?

I'm very new to python 3. As an assignment, I am supposed to make a race in python basic Syntax and without importing any other additional function, where 3 mice are racing with different odds of winning.

from random import randint
import time


def race():
    z = '----{,_,">'  # The mouse.
    j = ' '
    print('\t'*13, '|')  # The finish line. Very sophisticated.
    while len(z) < 50:
        time.sleep(1)
        #or k in range(3):
        x = randint(1, 6)
        j = ' ' * x
        z = j + z
        print("\r" + str(z), end="")  # For clearing printed text. I prefer not to import os.

As you might see, I've managed to make one; Two to go. But I've scratching my head for three hours on how to do it, that is how to make them go simultaneously ... Any help will be appreciated.




generate Random uuid Javascript

I'm trying to build a function to generate a random uuid, I found some thing on stack and I need to understand a little bit how that function work to create it with typescript :

public generateUniqSerial() {
    return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

is that writen good in es6 and can you help to understand how that line works :

*var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);*




Key generation that is random, unique DB-wide and bounded

I have three main constraints for int8 key generation:

  • Keys need be unpredictably random
    • Number of rows created should not be calculable
    • Order of row creation should not be calculable
  • Keys need to be unique across the entire db
    • Future table merges should not require changing keys
    • Future Table-Per-Class superclass additions should not require changing keys
  • Keys need to be bounded
    • These keys will be base58 encoded in various places such as URLs
    • Range will be narrower at first but should be adjustable in future to meet demand

I have heard of a few approaches to tackling at least some of these constraints:

DB-wide serial8

Does not meet the first constraint, but meets the second and third constraints.

DB-wide serial8 combined with a cipher

If the cipher key is leaked or discovered at any point then this becomes just DB-wide serial8, since the cipher key can't be changed without changing all the existing keys.

UUIDs

Does not meet the last constraint due to their 128-bit nature, but meets the first and second constraints.

Set default to floor(random() * n)

Does not meet the second constraint due to collision risk, but meets the first and last constraints.

Using random combined with a keys base table to keep track of all the keys

This does sort of meet all the constraints. However if a duplicate key is generated the insertion will fail. I am also concerned about any performance / locking issues.

If there is a nice way to make this re-roll until a non-colliding key is found, with good performance, then this would be an acceptable solution.


What is the best way to generate keys in PostgreSQL that meets the three criteria I listed?




Does random.shuffle() uses uniform distribution?

I am using the following shuffling algorithm in my code to shuffle a list. But I would like to know what sort of distribution is assumed in random.shuffle().

import random

random.shuffle(x)

where x is a list.

I read somewhere that random function in general uses uniform distribution but I could not find any clear information on random function page for random.shuffle

Does anyone know?




Random default column value that rerolls on conflict

I have a column that I would like to default to a randomly generated int8 in a specified range. I would also like this column to be unique, so if a random value is generated that already exists, it should be rerolled.

So my question is what the most idiomatic way to do the above is in PostgreSQL, ideally with good performance and supporting bulk inserts.




Module object in callable in python - Atom.io as as Jupyter notebook

import random

for i in random(10):
    x = random.random()
    print(x)

TypeError: 'module' object is not callable

I am getting the following error when I am trying to run this program in the atom.io




mercredi 18 décembre 2019

Cloverlist abckdidndd

List and send bshskdjdndf shdbdjdhdnfffhdndkdudndudd




Random Algorithm in java [closed]

I am doing a project in algorithms which consists in associating a word with a seed and a after to the word a sentence. I should have the same words on different platforms, but this doesn't happen. In fact I get different words from the ones I should get. This is my code:

import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Random;
import java.util.Scanner;
import java.io.*;

public class Esercizio1 {
    public static void main(String[] args) {
         try {
            Dictionary<String, String[]> poesie = new Hashtable<String, String[]>();
            Scanner scanner = new Scanner(new FileReader(args[0]));
            BufferedWriter fileWriter = new BufferedWriter(new FileWriter(args[1]));
            Random random = new Random();
            long seed = scanner.nextLong();
            System.out.println("Seed: "+seed);
            scanner.nextLine();
            // lettura delle chiavi
            String[] keysArray = scanner.nextLine().split(" ");
            String[] selectedKeys = scanner.nextLine().split(" ");
            // lettura a vuoto
            scanner.nextLine();
          for(int i=0; i<keysArray.length; i++){
                String[] temp = scanner.nextLine().replaceAll("\\s", "").split(":");
                String key = temp[0];
                String[] frasi = temp[1].substring(1, temp[1].length()-1).split(",");
                poesie.put(key, frasi);
            }
            scanner.close();
            // scrivo output su file
            for(int i=0; i<  selectedKeys.length; i++){
              Casuale rnd = new Random ();
               rnd.setSeed (seed);
                //random.setSeed(seed);
                // estraggo frase tramite chiave
                String[] frasiEstratte = poesie.get(selectedKeys[i]);
                int bound = frasiEstratte.length;
                fileWriter.write(frasiEstratte[rnd.nextInt(bound)]+". ");
            }
            fileWriter.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}



generate a random range between two numbers

What is the pythonic (can use numpy) way to generate a random range of length [range_length_min, range_length_max] in the range [range_start, range_end]?

Example:

  • range_length_min = 5
  • range_length_max = 10
  • range_start = 0
  • range_end = 2000

Allowed Solutions:

  • [53, 59]
  • [934, 941]

Invalid Solutions:

  • [92, 94] because length of range is less than range_length_min
  • [92, 104] because length of the range is more than range_length_max
  • [-4, 3] because start of range is less than range_start
  • [1998, 2004] because end of range is less than range_end

Current Solution:

start = np.random.randint(range_start, range_end - (range_max_length - range_min_length))
end = start + np.random.randint(range_min_length, range_max_length)

This gives the correct result but does not sample uniformly. The range_end - (range_max_length - range_min_length) is a hack.




std::random_device constructor overhead

From many sources in the net, it is suggested the use of random_device to produce random numbers. All of the code instantiate random_device, applies the proper random_engine or distribution, and makes use of it. I'm wondering, what is the overhead of such pattern? Instantiating the random_device will require the opening of /dev/urandom on linux, so the overhead may be heavier than it seems to appear from that sources. Shouldn't be recommended of a monostate/singleton pattern for this instead?

Thanks in advance.




How to generate a random float in range [-1,1] using numpy.random.rand()?

Numpy's random.rand() function produces random floats between 0 and 1. How do I transform the output of this function to produce random floats between -1 and 1?

Current output:

In[]: numpy.random.rand(3, 2)
Out[]: 
array([[0.13568674, 0.72465483],
       [0.48726461, 0.68867378],
       [0.50463821, 0.28619853]])

Desired (example) output:

In[]: numpy.random.rand(3, 2)
Out[]: 
array([[-0.13568674, 0.72465483],
       [-0.48726461, 0.68867378],
       [0.50463821, -0.28619853]])

I would not like to use random.uniform().




how to set the "Color.rgb" in Java to random?

I'm experimenting with Android studio and I wanted to pass a random value to the color.rgb. This is the code that I tried

int x  = rand.nextInt(9);
int y  = rand.nextInt(9);
int z  = rand.nextInt(9);

viewTest.setBackgroundColor(Color.rgb(x,y,z));

edit: the color range is between 0 and 255 so to right code is

int x  = rand.nextInt(255);
int y  = rand.nextInt(255);
int z  = rand.nextInt(255);

viewTest.setBackgroundColor(Color.rgb(x,y,z));

not the best solution but it works Thanks to jon Skeet for remembering me :)




mardi 17 décembre 2019

sas select 10 random obs from a table

I have a data set with 1000 OBS and I wish to select 10 random OBS. To my understanding, I need to use RANUNI or RAND, but I can't figure out how to implement.

tanks




How to get the Nth instance of a Random.Next()?

I was hoping there's a built in method in Random for this, but there isn't? So I came up with this function to return the nth instance of a random seed:

public class Program {
static int seed = 123; // This could be anything

static int NextN(int n, int range) // Get the nth instance of seed
{
    Random rand = new Random(seed);
    List<int> pool = new List<int>();
    while( pool.Count< n+1 ){ pool.Add(rand.Next(range)); }
    return pool[n];
}
public static void Main() 
{
    Console.WriteLine(NextN(8,100)); // Return 19 as the 8th value of seed 123 at 100 range.
}}

As you can see, the NextN() function generate the sequence of random numbers first, then return the value of the nth instance. This will perform badly once you're trying to reach a very high instance (like in the millions). Since random always return the same value each time you restart an app, I need to keep track how many times the random seed is accessed between session. is there a way around this?




Make two functions use the same number (generated by findRandom) in Typescript

The problem now I'm facing is functions call findRandom twice and get two different value at the end. How to make findRandom randomly pick a number and store it at one place where the number will be unchanged.

Expected result: all the functions share the same number or value.

getRandom = a.findRandom(0,1);
storeRandom = getRandom; 

functionA() {
   if (storeRandom = 0){
       console.log("0");
   }
}

functionB(){
    if (storeRandom = 1){
        console.log("0");
    }
}



Stata simulate doesn't seem to use seed option

Say that I define this simple program in Stata that creates 100 observations populated with random numbers and returns the mean:

clear all

program define a, rclass
    set obs 100
    gen a = runiform()
    sum a
    return scalar mean=r(mean)
end

I then run this program using simulate:

simulate mean = r(mean), reps(1): a seed(123)

I get .5793895. I run the exact same line, expecting to get the same result:

simulate mean = r(mean), reps(1): a seed(123)

But I don't. I get another result! I thought that because the seed was equivalent in both cases, the seed would control what is generated by runiform(), thus giving me the same mean.

I did another test using seed:

clear all
set obs 100
set seed 123
gen a = runiform()
sum a

This gives .4948977. I then run the same code again:

clear all
set obs 100
set seed 123
gen a = runiform()
sum a

This also gives .4948977 as expected. What is different about the seed from simulate and not using simulate, and how can I get reproducible results using simulate?




Generate two standard Gaussian random variables for 100.000 samples

Generate two standard Gaussian random variables for 100.000 samples. Makesure you generate the random variables correctly by checking their means and variances.

I have a question like this. İt can be make in MATLAB but I want to make it by using python. But I didn't understand the question. What does it mean 'for 100.000 samples' ? What commands should I use to make this in Python?




Chasing game in C , robots and person

I am in my first year of uni (first semester) and this is my assignment for the programming class . I think its way harder than it should be , and i don't know where to start . I would appreciate any kind of advice , guides , examples . I have 20 days to finish this of . Some first questions i have : -How can i put things in random places (that are currently free in the board ). -Pdcurses will let me refresh the monitor in real-time ? How should i approach such a thing? -What is the thought process for the cumputer to know where the person is and to move all the robots towards it? I am not looking for a solution , i am trying to get help . Thank you .

The game is played in a board 60x20 , virtual squares that they don't separate with some indication (vertical lines etc.). In the beginning of every level , there are : a person [M] that is controlled by the player through the keyboard and the enemy robots[R] , which are controlled by the computer , chasing the person.The goal is to finish as many levels as possible . A level is finished when all robots have been destroyed . The person [M] has one life only .

In the beginning of every level the person and robots are placed in random free spots . The person and robots are moving alternatively .First move is for the player , and then the computer that moves all of its robots at the same time . When a robot moves in the same spot with the person , the game ends . The robots are moved in the next square(vertically , horizontally , diagonally) , trying to reduced their distance from the person , vertically and horizontally . If two robots move in the same square , they are killed, leaving a pile behind [#] .A robot can be also killed if it steps in a pile . The robots cant see the piles , they cant avoid them . In every round the player can : -Move the person in all direction with arrow keys and keys home, end , page up and page down (for the diagonal moves).Every move that are off the limits of the game or that is on a square with piles or robot are ignored. -Use a bomb . In the beginning of every level the player gains a bomb . If the bomb is not used , it is transferred to the next level. Player can use the bomb with the key 'B' . A bomb clear all the squares near the person from robots and piles . -Teleport in a random free spot with the key 'T' . -With key 'space' or '5' to pass its turn . -To finish the game with key 'Q' .

The player shouldn't use the key 'Enter' to enter a command . The screen will refresh and not reload . The library pdcurses is recommended . Cant use goto or break commands .




Bifurcation plot displays empty set after a certain value

As said, when plotting my bifurcation plot it does not show its chaotic tendency after r=4a nd it only plots two points at the last given value (in this case 5, but the same applies to any value over 4 or under -2).

def f (A, R):
        A = A*(R*((A/N)-1)-1)+N+A
        B = N-A
        return A

def bifurcation(r, iter):
    # One initial condition for each value of r
    a = np.linspace(0,1000,len(r))
    # We are first going to get rid of the transients
    for i in range(5000):
         a = f(a,r)
    # Assuming we are now on the limit cycle, we plot value of iter outputs
    for i in range(iter): 
        a = f(a,r)
        b = N-a
        plt.plot(r,a, '.', color = 'r', markersize = 1)
        plt.plot(r,b, '.', color = 'b', markersize = 1)

N = 1000
plt.figure()
r = np.arange(0, 5, 0.01)
iter = 100
bifurcation(r, iter)
plt.legend("AB")
plt.show()]

bifurcation plot




How should the sequence number in curand_init be chosen when repeating a set of multiple kernels

I am writing CUDA code for the simulation of spiking neural networks. Every time step, the same set of kernels are called which have different grid and block dimensions (and total number of threads) and of which all produce random numbers using the cuRAND device API. The cuRAND device API documentation says

For the highest quality parallel pseudorandom number generation, each experiment should be assigned a unique seed. Within an experiment, each thread of computation should be assigned a unique sequence number. If an experiment spans multiple kernel launches, it is recommended that threads between kernel launches be given the same seed, and sequence numbers be assigned in a monotonically increasing way. If the same configuration of threads is launched, random state can be preserved in global memory between launches to avoid state setup time.

Question: Can I create as many cuRAND states (with same seed and different sequence number) as the maximum number of threads used in any of my kernels and use the same states when kernels with less threads are called? Or do I need to generate one state per thread per kernel that is repeated?

Example: I have two kernels, which are called non-concurrently every simulation time step: kernal 1 uses 10 threads, kernel 2 uses 100 threads. Can I create 100 cuRAND states and use only 10 of them in kernel 1 and all of them in kernel 2? Or do I need to create 110 cuRAND states and use different states in kernel 1 and kernel 2?

Since random number sequences with same seed and different sequence number have statistically not correlated values (according to the documentation), I would assume it doesn't matter that one sequence is moving forward faster than the other (assuming I do not generate 2^67 numbers, which seems to be the period or random numbers for one sequence number?). But I don't know enough about random number generation to be sure.




Regular Expression C# Random Letter from specific List of Letters

I want the string (length 8) format to be one letter from a specific letter list A, B, C (neither of these letters should be repeated) the letters have a random position and the rest are numbers (0-9). For example:

1234A567  - Valid
277897C0  - Valid
A100299B  - Not valid
12C3879C  - Not valid

I tried something like this: (\d){7}(A|C|E|F|G|H|J|K|M|U|Z){1} but this does not work. Help?




show long random number one by one vb.net

I'm using Randomize() and Timer to generate random number

I want the timer to show number that includes (Units , Tens , Hundreds)

First show Hundreds Second show Tens then show Units

example:

123

first show 1 after two seconds show 2 after two seconds show 3

and then timer stop




Selecting a random amount of elements from array in javascript

I have 2 arrays with 4 x-coordinates in each. In total I want to select 3 random values from both arrays. So array1+array2 =3 elements. In the end i just done it a bad way to make it do what i wanted. Just wondering if anyone can see a more efficient way to produce nicer code. This is how i ended up getting it to work. I cant show what i have tried as it has been so modified i ended up just deleting it and doing this.

enemyCars = [100, 200, 300, 400];    //not actual values

newCarArray = [];    //global
newWallArray = [];    //global

function randomNumber(a, b){
    return Math.round(random(a,b));
}

function chooseCars(){
    let carAmount = randomNumber(0,3);
    let wallAmount = 3 - carAmount;
    print('carAmount ' + carAmount);

    if(carAmount == 0){
        newCarArray = [];
    }
    if(carAmount == 1){
        let a = randomNumber(0,3);
        newCarArray.push(enemyCars[a]);
    }
    if(carAmount == 2){
        let a = randomNumber(0,3);
        newCarArray.push(enemyCars[a]);
        let b = randomNumber(0,3);
        newCarArray.push(enemyCars[b]);
    }
    if(carAmount == 3){
        let a = randomNumber(0,3);
        newCarArray.push(enemyCars[a]);
        let b = randomNumber(0,3);
        newCarArray.push(enemyCars[b]);
        let c = randomNumber(0,3);
        newCarArray.push(enemyCars[c]);
    }

    if(wallAmount == 0){
        newWallArray = [];
    }
    if(wallAmount == 1){
        let a = randomNumber(0,3);
        newWallArray.push(enemyWalls[a]);
    }
    if(wallAmount == 2){
        let a = randomNumber(0,3);
        newWallArray.push(enemyWalls[a]);
        let b = randomNumber(0,3);
        newWallArray.push(enemyWalls[b]);
    }
    if(wallAmount == 3){
        let a = randomNumber(0,3);
        newWallArray.push(enemyWalls[a]);
        let b = randomNumber(0,3);
        newWallArray.push(enemyWalls[b]);
        let c = randomNumber(0,3);
        newWallArray.push(enemyWalls[c]);
    }
}

thanks for the help




lundi 16 décembre 2019

Weird result from random character generator in C

I am trying to write a program in C that spits out random characters. Following instructions I found here, I wrote this program.

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


int main(void) {
   srandom((unsigned) time(NULL));
   printf("Tests various aspects of random\n");
   char misc;
   int num, index;
   printf("Enter number of chars: ");
   scanf("%d", &num);
   printf("\n");

   for (int i = 0; i < num; i++) {
      index = random() % 26;
      misc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index];
      printf("%d:%s\n", index, &misc);
   }
}

However, it doesn't behave as I expect. When entering a small number of characters for it to generate, like 10, it makes the expected output.

My expected output is a set of

rand_int:char

pairs printed to the screen.

Here is an example of normal operation

Tests various aspects of random
Enter number of chars: 
7:H

4:E

23:X

2:C

4:E

17:R

22:W

11:L

9:J

4:E

However, if I input a large value such as 100, it outputs very strange things like:

Tests various aspects of random
Enter number of chars: 
18:Sd
3:Dd
21:Vd
10:Kd
19:Td
19:Td
14:Od
7:Hd
15:Pd
22:Wd
24:Yd
22:Wd
12:Md
[rest omitted for brevity...]

So the question is, why does it behave this way? What might be a better approach to avoid this?