vendredi 31 juillet 2020

Multiple outputs on on_message while using a random number generator

from discord.ext import commands
import discord
import random

class Ship(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    
    @commands.Cog.listener()
    async def on_message(self, message):
        if (message.guild.id == 464298877823221761) or (message.guild.id == 548945695034310697) or (message.guild.id == 712143774935154689):
            if message.content.find("!ship") != -1:
                line = message.content
                name = line.split(' ')[1]
                name2 = line.split(' ')[2]
                number = random.randint(0,100)
                if (number >= 0) or (number <= 10):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Awful :sob:')
                    number = random.randint(0,100)
                if (number >= 11) or (number <= 19):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Bad :cry:')
                    number = random.randint(0,100)
                if (number >= 20) or (number <= 29):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Pretty Low :frowning:')
                    number = random.randint(0,100)
                if (number >= 30) or (number <= 39):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Not Great :confused:')
                    number = random.randint(0,100)
                if (number >= 40) or (number <= 49):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Not Too Bad :confused:')
                    number = random.randint(0,100)
                if (number >= 50) or (number <= 59):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Barely :no_mouth:')
                    number = random.randint(0,100)
                if (number >= 60) or (number <= 69):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Not Bad :slight_smile:')
                    number = random.randint(0,100)
                if (number >= 70) or (number <= 79):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Pretty Good :smiley:')
                    number = random.randint(0,100)
                if (number >= 80) or (number <= 89):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Great :smile:')
                    number = random.randint(0,100)
                if (number >= 90) or (number <= 99):
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** Amazing :heart_eyes:')
                    number = random.randint(0,100)
                if number == 100:
                    await message.channel.send(':heartpulse:**MATCHMAKING**:heartpulse:\n:small_red_triangle_down:`' + name +'`'+ '\n:small_red_triangle:`' + name2 + '`' + '\n**' + str(number) + '%** **PERFECT** :heart_exclamation:')
                    number = random.randint(0,100)

def setup(bot):
    bot.add_cog(Ship(bot))

I think that title sums it up, when I type in !ship followed by 2 names the code spits out an answer many times all with different numbers, I think its better if I send a screenshot, if you have any questions I will be online for a few more hours to answer them

https://imgur.com/a/BO72pkv




How to properly seed a mersenne_twister RNG with the maximum entropy in C++

I want to fully seed a Mersenne twister with the maximum amount of entropy possible (not just 32 bits). Is this the correct way? Is there a better way to do this? Will this work for every kind of standard C++ random number generator or is there a simple way to make one that is?

#include <algorithm>
#include <array>
#include <bitset>
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>

int main() {
    using RNG = std::mt19937_64;
    auto constexpr state_size = RNG::state_size;

    std::array<std::seed_seq::result_type, state_size> entropy;
    std::random_device rdev;
    std::generate_n(entropy.begin(), state_size, std::ref(rdev));
    std::seed_seq seed(entropy.begin(), entropy.end());
    RNG rng(seed);

    auto constexpr n = 16U;
    using data_t = std::uint64_t;

    std::array<data_t, n> data;
    std::generate_n(data.begin(), n, std::ref(rng));

    for (auto d : data) {
        std::cout << std::bitset<8 * sizeof(data_t)>(d).to_string();
    }
}
}



How to generate random numbers on Windows that aren't all the same?

I was trying to generate two random integers with one greater than the other.

int lower = 1;
int upper = 10000;
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<std::mt19937::result_type> uni(lower, upper);
auto min = uni(rng);
auto max = min + uni(rng);
assert(("max not greater than min", max > min));
cout << "min: " << min << "max: " << max << endl;

I noticed I kept getting the exact same results. I compile with g++ TestRandomWorks.cpp -o TestRandomWorks.exe -pedantic -Wall and get no errors. I think this is the same bug from Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1? though it seems rather large to have been ignored. How can I upgrade MSYS2? I tried running the commands pacman -Syu and pacman -Su in its terminal but nothing changed. Is there any alternatives or work around? I just want to generate random numbers on Windows.




Generate Random Numbers in Angular 9

Good day community, Please how can i generate eight digit random numbers between 1 to 100000000 when a user opens a new page using angular 9.

Just like in a website when a customer opens the checkout page an eight digit order number is generated. How to i implement the .ts and html code.

Thank you in advance




PySpark/Spark Correlated scalar subqueries with order by

I'm trying to join a column value from a table, expl, to my main table, co, under an equality condition, in Spark SQL. The catch is that because there are many rows that join from expl, I want to only join one random row, and use its column value.

But I'm running into Correlated scalar subqueries errors either in the subquery select statement or in the order by. There aren't posts on SO that deal with the ORDER BY part of the subquery or with subquery random row retrieval in Spark.

In this case I tried to use a random number generator, which does not work as it seems like RAND() needs to be an aggregate, somehow.

cooccurrences = spark.sql("""
    SELECT C.word AS word, C.word2, (
            SELECT FIRST(e.word2) word2 FROM expl e
            WHERE e.word = C.word and e.word2 ORDER BY RAND() 
        ) word3
        FROM cu C
 """)

In this case, I built a column with a random value, which can be used to order the columns, so a random number generator isn't needed and instead just the row with the max value is returned. But I dislike this because it could return the same row for duplicate groups.

cooccurrences = spark.sql("""
                              SELECT 
                                e.word, 
                                e.word2,
                                (SELECT z.word2 from 
                                  (SELECT 
                                        FIRST(c.word2) word2, MAX(C.rand_n) rand_n
                                        FROM cu C
                                        WHERE e.word = C.word and MAX
                                    ) z
                                  ) word3
                                FROM expl AS e
                          """)

These queries all throw a variant of correlated scalar subqueries must be aggregated




How can I, in a if Statement ask for multiple possible numbers, Swift

Im new here. Also Im new in swift. I want to ask if the generated random Number is 1 or 13 or 25. I cut ask something like:

if randomNumber == (1) || if randomNumber == (13) || if randomNumber == (25)

and that's works but its way to much code. I try to minimize my code.

I did try something like this: if randomNumber == (1 || 13 || 25) but this didn't worked.




Random number simulation in R

I have been going through some random number simulation equations while i found out that as Pareto dosent have an inbuilt function. RPareto is found as

rpareto <- function(n,a,l){
rp <- l*((1-runif(n))^(-1/a)-1)
rp
}

can someone explain the intuitive meaning behind this.




Are there any ways i can take 1 letter from a word, and then mix that letter with another letters choosen from other words

Title is complicated yeah, but i will show an example what i want to achieve..

So i give a list of words

keywords = ['paper', 'car', 'plane', 'keys']

Then i take 1 or more letters from each of those words in the keywords list and mix them together in a 1 random word like this

word: pany
word: rpars
word: sprya

ofc i want to run this on a loop for like 100 times, but i need to get the general part done first

thanks!




Passing a same random number to all tests in Cypress

So I have two tests - Test1.spec.js and Test2.spec.js and I want that with every test run a random number should be generated and the same random number should be used in both the specs. I wrote a simple Math.random() function for this under support/index.js

Cypress.config('UniqueNumber', `${Math.floor(Math.random() * 10000000000000)}`)

And in the tests I am writing as:

cy.get('locator').type(Cypress.config('UniqueNumber'))

When I am trying to execute the tests using the cypress app npm cypress open and then Run All Specs, a random number is generated and the same is passed to both of the spec files correctly. But when I try to run the tests using the CLI npx cypress run for both of the spec files different random numbers are passed.

What am I doing wrong in case of executing the tests using CLI?




Problem to generate random unique numbers from fixed population length

I have a problem here which is: I need to generate random numbers given a fixed length, and every time I generate those numbers, I need to check if it was already seen or not.

Example: my fixed population size is 2.000.000. So, for example, in the first round of my algorithm, my sample size is 400.000. I need to generate 400.000 over 2.000.000. After generating those random numbers, I save them in a HashSet.

In a second rand of my algorithm, let's say I want to generate 20.000 random numbers, but I need to check with those 20.000 numbers was already seen or not by looking at the HashSet (which contains the 400.000 initial numbers from the 1 round).

This is what I got so far:

1 round: 
         population size: 2.000.000
         sample: 400.000
         List<Integer> result = new ArrayList<Integer>(sample);

         I save the numbers in a variable called perm[],so :
         int perm[] = new int[population]

  public List<Integer> generateRandomNumbers (int population, Set<Integer> setListStringSeen, int sample)
  {
   for (int i = 0; i < sample; i++)  
   {
      // random integer between i and population-i
      k = i + (int) (Math.random() * (population - i));
                    
     if(setListStringSeen.contains(k))
     {    
         // the problem here is: when I check here and if the newly generated number
         // was already see, I need to generate again a new number. But in this case,
         // the next number need to be checked again, because it could be seen too.
         // how can I end up this loop of checking?

        k = i + (int) (Math.random() * (population - i));
        
        if(setListStringSeen.contains(k))
        {
            System.out.println("we've choose this number once before");
        }
        
        setListStringSeen.add(k);           
        
      }
    
      int t = perm[k];
      perm[k] = perm[i];
      perm[i] = t;
    
   }

   for (int i = 0; i < sample; i++)
   {
      result.add(perm[i]);
   }

    at the end of 1 round, I add all the generated numbers in a HashSet:

   setListStringSeen.addAll(result);

   return result;

}

Now let's go to the 2 round: let's say we want to generate 20.000 new numbers: what I want is, check if those numbers the will be generated (in the second round) was already seen before by checking the Hashset variable. Any idea on how to do it?




List won't shuffle [duplicate]

I am attempting to make a mini-game in which the user must unshuffle a word. The word is taken at random from a list, saved as w, then shuffled as s. To achieve this I attempted to take the word from the list and turn it into a list itself so that the letters can be shuffled. Yet python only ever returns None.

from random import shuffle
import random

words = ["help"]

w = (random.choice(words))
print(w)

s = list(w)
print(s)
s = random.shuffle(s)

print(s)

The output ends up looking like this:

help
['h', 'e', 'l', 'p']
None

I can't see what I am doing wrong.




I am trying to display random image in GUI. But i get the error that my list is not defined, even i globalised it. Anybody knows what went wrong?

  1. def ALLFLAGS():
  2. global GERMANY
  3. global Germany
  4. Germany = ImageTk.PhotoImage(Image.open("Flags/Germany.png"))
  5. GERMANY = Label(game, image=Germany)
  6. GERMANY.photo = Germany
  7. GERMANY.pack()
  8. global FRANCE
  9. global France
  10. France = ImageTk.PhotoImage(Image.open("Flags/France.png"))
  11. FRANCE = Label(game, image=France)
  12. FRANCE.photo = France
  13. FRANCE.pack()
  14. global allflags
  15. allflags = [GERMANY, FRANCE]
  16. ...
  17. ...
  18. random.choice(allflags)

ERROR: NameError: name 'allflags' is not defined




jeudi 30 juillet 2020

Why does numpy.random.choice not use arithmetic coding?

If I evaluate something like:

numpy.random.choice(2, size=100000, p=[0.01, 0.99])

using one uniformly-distributed random float, say r, and deciding if r < 0.01 will presumably waste many of the random bits (entropy) generated. I've heard (second-hand) that generating psuedo-random numbers is computationally expensive, so I assumed that numpy would not be doing that, and rather would use a scheme like arithmetic coding in this case.

However, at first glance it appears that choice does indeed generate a float for every sample it is asked for. Further, a quick timeit experiment shows that generating n uniform floats is actually quicker than n samples from p=[0.01, 0.99].

>>> timeit.timeit(lambda : numpy.random.choice(2, size=100000, p=[0.01, 0.99]), number=1000)
1.74494537999999
>>> timeit.timeit(lambda : numpy.random.random(size=100000), number=1000)
0.8165735180009506

Does choice really generate a float for each sample, as it would appear? Would it not significantly improve performance to use some compression algorithm in some cases (particularly if size is large and p is distributed unevenly)? If not, why not?




Which distribution behind Redshift `random()` function?

I'm using AWS Redshift's random() function to select a small portion of data from a giant dataset. But feel it's safer to understand how its random function works.

It's uniform distribution or normal distribution or any other method to randomly choose the items?




Two object keep getting the same random number in Unity [duplicate]

I have written code for four different cars, They all have the same code in C#. Their objective is to choose a lane (randomly) and then drive down that lane at a certain speed, however, whenever I execute the code, all the cars pile up on one another in one lane.

I've tried to look for explanations on the internet, but all of them are really outdated.

I am using Unity 2019.4, here is my code. Any help will be greatly appreciated.

    if (ypos < -7)
    { // n
        Random rnd = new Random();
        int ran = rnd.Next(1, 5);
        if (ran == 1)
        {
            if (isTouching)
            {
                transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
            }

            transform.localPosition = new Vector3(-2.4f, 9.0f, transform.localPosition.z);
        }
        else if (ran == 2)
        {
            if (isTouching)
            {
                transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
            }
            transform.localPosition = new Vector3(0.0f, 9.0f, transform.localPosition.z);
        }
        else if (ran == 3)
        {
            if (isTouching)
            {
                transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
            }
            transform.localPosition = new Vector3(2.5f, 9.0f, transform.localPosition.z);
        }
        else if (ran == 4)
        {
            if (isTouching)
            {
                transform.localPosition = new Vector3(-2.4f, -9.0f, transform.localPosition.z);
            }
            transform.localPosition = new Vector3(5.0f, 9.0f, transform.localPosition.z);
        }


    }
    else
    {
        transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y - speed, transform.localPosition.z);
    }


}

}




How to limit the occurrence of a randomly generated item in C++? [closed]

Suppose, an array can hold 10 elements and I want it to fill it with random integers ranging from 1 to 5. In C++, it can be easily done by using rand().

But I want to limit the number of occurrences of the digit 5 to a maximum of 2 times. [ At the end, the array must contain two 5s. ]

So, is there any function in C++ to set this constraint?

This is what I've done so far.

for(int i=0; i<10; i++)
{   num=rand()%5+1;
    if(num==5)
    {   if(count<2)
        {   count++;
            arr[i]=num;
        }
        else
        {   i--;
            continue;
        }
    }
    else
        arr[i]=num;
}

If you have any ideas, feel free to share it with me. Thanks.




How can I use randsample in Matlab without running out of memory?

I want to sample without replacement m integers between 1 and n in Matlab, where

m=10^6;
p=13^5;
n=p*(p-1)/2;

I have tried to use randsample as follows

random_indices_pairs=randsample(n,m);

However, I get a memory issue which is

    Error using zeros
    Requested 1x68929060278 (513.6GB) array exceeds maximum array size preference. Creation of arrays greater than this
    limit may take a long time and cause MATLAB to become unresponsive. See array size limit or preference panel for more
    information.

Error in randsample (line 149)
                x = zeros(1,n); % flags

Is there a way to avoid that? The issue here is due to the fact that n is huge.




Different results from sample with and without prob parameter

I noticed sample returns different results when the parameter prob is used to indicate uniform distribution and when prob is omitted, despite the fact that the function will still generate numbers from a uniform distribution.

This has been noticed before (see R sample probabilities: Default is equal weight; why does specifying equal weights cause different values to be returned?) and answers pointed out how that the c routines for sample are different when prob is NULL and when it's not.

Is there a reason why this is happening?
Wouldn't it be preferable to return the same results every time the distribution to generate data is the same?

Example:

set.seed(1)
sample(c(0,1), 10, replace = T, prob = c(0.5, 0.5))

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


set.seed(1)
sample(c(0,1), 10, replace = T)

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




Bootstrap Cards - Show random

I will try it in my best english and hope u will understand. We want to show 4 Bootstrap Cards in a row. This is easy and works already.

Our problem is, that we have more than 4 Cards and we want to show them randomly when the user loads the webpage.

For example we have 12 cards. When the user loads the webpage the first time they will see card number

1 - 4 - 7 - 12

When they reload they will see

2 - 5 - 6 - 11

and so on... how does this work? i just found the following example, that will show cards random but not just 4 of them:

[Google](http://jsfiddle.net/BwJHj/1/)



numpy.random.randint slower than random.randint

In [27]: import random as rnd

In [28]: from numpy import random as nrnd

In [29]: %timeit rnd.randint(0,5)
859 ns ± 22.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [30]: %timeit nrnd.randint(0,5)
4.53 µs ± 104 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [31]: %timeit nrnd.randint(0,10000000)
4.67 µs ± 116 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [32]: %timeit rnd.randint(0,10000000)
979 ns ± 25.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Python 3.7.3 (default, Mar 27 2019, 16:54:48)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.

In my 2nd test case, I have increased the random range to (0,10000000). As the range is larger, numpy should perform better at this test case.

Why is numpy.random.randint() taking more time than built in random.randint? What extra operations is numpy doing here?




mercredi 29 juillet 2020

Is there a best practice for using non-R RNGs in Rcpp code?

I am writing an Rcpp function wrapped by an R function. The Rcpp function does some parallel random sampling, necessitating that I not use R's RNG. (Note: this is not a question about random seeds for parallel processes; I've got that handled.) I would like users to be able to call set.seed() to maintain reproducibility, even though I'm using a different RNG. A pseudocode example of what I am doing is below. (I can edit to make working code if needed.)

My questions are: (a) Is there something obviously dangerous to the below approach? (It feels hacky.) (b) Is there a more well-established method?

FWIW: there is a similar question whose answer describes but does not show what I am trying to do, seeding a call to an RNG with R's RNG. But I can't find an explicit example of someone doing this.

R wrapper function

sample_wrapper <- function() {
  # get current state of RNG stream
  # first entry of .Random.seed is an integer representing the algorithm used 
  # second entry is current position in RNG stream
  # subsequent entries are pseudorandom numbers
  seed_pos <- .Random.seed[2]

  seed <- .Random.seed[seed_pos + 2]

  out <- sample_cpp(seed = seed)

  # move R's position in the RNG stream forward by 1 with a throw away sample
  runif(1)

  # return the output
  out
}

Rcpp sampling function

sample_cpp(const int seed){
  // seed my own rng
  MyRngClass my_rng = MyRng(seed);

  // do my own sample
  double result = MySampleFun(rng = my_rng);

  // return result
  return result;
}

Example usage

set.seed(123)

sample_wrapper()



How to create mirror URLs or unique identifiers linking to the URL within Go?

I'm a beginning Go programmer who is writing a web application---any help appreciated.

There are URLs for the webpages which are in the following format:

www.websitename.com/ucihvpl9yyl764p0g8szt9tutifxrf

My goal is to create a unique identifier on the webpage (of length N), which both links to this HTML, and creates a special URL of the format www.websitename.com/unique_identifer for users to easier access this HTML. This unique identifier should be created once, and not change.

It's clear to me how to generate a random string (see below), but it's not clear how to connect this to the HTML, or create a novel URL based on this unique token linking to the original URL.

I think I know how to generate a unique identifier with the following, using this link: https://blog.questionable.services/article/generating-secure-random-numbers-crypto-rand/

Here, the string is length 20

package main

import(
    "fmt"
    "crypto/rand"
    "encoding/base64"
)


// GenerateRandomBytes returns securely generated random bytes. 
func GenerateRandomBytes(n int) ([]byte, error) {
    b := make([]byte, n)
    _, err := rand.Read(b)
    // Note that err == nil only if we read len(b) bytes.
    if err != nil {
        return nil, err
    }

    return b, nil
}

// GenerateRandomString returns a URL-safe, base64 encoded securely generated random string.
func GenerateRandomString(s int) (string, error) {
    b, err := GenerateRandomBytes(s)
    return base64.URLEncoding.EncodeToString(b), err
}


func main() {
    token, err := GenerateRandomString(20)
    if err != nil {
        // Serve an appropriately vague error to the
        // user, but log the details internally.
    }
    fmt.Println(token)
}



Generate a 256 bit random number

I need to generate a 256 bits random unsigned number as a decimal string (with nearly zero probability of collision with anything generated earlier).

How to do this in JavaScript (in a browser)?




How to create a function to generate 15 random integers between 1 to 99 in python3? [duplicate]

Here's my code:

from random import randint as r_int

 def random_int_15():
    r_num = 0
    for i in range(0, 15):
        r_num = r_int(1, 99)
    return r_num

I want to use this function in some other function and I don't want any no. to be repeated. I know there is a way to do it, I don't find any. Help me.




dealing cards to players and updating dictionary with player:hand

I am trying to create a deck of cards, randomly shuffle it, and deal 3 cards to 3 players. I created a function buildDeck() that returns the 48 needed cards in deck as a list. I then tried to make a dictionary playerHands with key, value {playername: [3 random cards from deck]}. I then def pullCards() which shuffles the deck, checks that there are atleast 9 cards in the deck, and then draws 3 random cards from the deck and removing them using pop(). I would now like to assign the 3 randomly drawn cards as a value for each player key in the dict playerHand.

I am new to programming and don't really know if this was a good setup for this program nor do I know if this use of list in lists and dictionaries are appropriate for this.

I am not supposed to use classes for this program and I also don't even know how! Really would appreciate some help! Thanks

import random

def printMenu():
    #prints menu of options
    menu = "s: start new game\np: Pull cards for all players\no: output deck\nh: output players’ hand\ne: exchange one card\nd: declare winner\nq: quit\nSelect an option:\n"
    print(menu)
    return
printMenu()

def buildDeck():
    suits = ['Clubs', 'Golds', 'Cups', 'Swords']
    values = list(range(1, 13))
    deck = []
    #iterates through elements in suits and elements in values appending each respective element as a new element into deck
    for i in suits:
        for x in values:
            deck.append(list([i, x]))
    return deck


def startNewGame():
    #prompts user for player names
    player1 = input("Enter player 1's name:\n")
    player2 = input("Enter player 2's name:\n")
    player3 = input("Enter player 3's name:\n")
    
    #calls 48 card deck using buildDeck() function 
    buildDeck()
    
    #creates dictionary of each player's empty hand with values of None
    playerHand = {player: None for player in [player1, player2, player3]}
    return playerHand

    
def pullCards():
    playerHand = startNewGame()
    deck = buildDeck()
    #randomly shuffles deck
    random.shuffle(deck)
    #iterates through cards in the deck and checks if at least 9 cards
    for cards in deck:
        if deck.count(cards) >= 9:
            #draws 3 random cards and pop() removes cards from the deck
            for i in range(3):
                randomCard = deck.pop(random.randint(0, len(deck) - 1))
                for keys in playerHand.keys():
                    playerHand[keys] = randomCard



Generate a number within a range and considering a mean val

I want to generate a random number within a range while considering a mean value.

I have a solution for generating the range:

turtles-own [age]

to setup
  crt 2 [
   get-age 
  ]     
end

to get-age
  let min-age 65
  let max-age 105
  set age ( min-age + random ( max-age - min-age ) )
end

However, if I use this approach every number can be created with the same probability, which doesn't make much sense in this case as way more people are 65 than 105 years old. Therefore, I want to include a mean value. I found random-normal but as I don't have a standard deviation and my values are not normally distributed, I can't use this approach.




monty hall %50 - %50

i am trying to simulate monty hall problem. i didn't realized any problem but i recieve approximately %50 %50 output. i know that there are explanations but i couldnt understand these please help me

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

#define win 1
#define lose 0

#define yes 1
#define no 0

int main(){
    //i assume that prize is behind the first door

    srand(time(NULL));
    
    int lose_counter = 0;
    int win_counter = 0;

    for(int i = 1;i <= 10000;i++){
        int game_status;
        int chosen_door = rand() % 3 + 1;
        int choice;

        //first step that i chose a door
        if(chosen_door == 1){
            game_status = win;
        }
        else if(chosen_door == 2){
            game_status = lose;
        }
        else if(chosen_door == 3){
            game_status = lose;
        }
        
        //host says "do you want to change your door"
        choice = rand() % 2;

        if(choice == yes){
            if(chosen_door == 1 ){//this is the case i have chosen 
                                  //first door and change it after question
                game_status = lose;
            }
            
            if(chosen_door == 2 ){
                game_status = win;
            }
            
            if(chosen_door == 3 ){
                game_status = win;
            }
        }

        if(game_status == win){
            win_counter++;
        }
        else if(game_status == lose){
            lose_counter++;
        }
    }

    printf("win: %d\nlose: %d\n",win_counter,lose_counter);
    
    return 0;
}



Restart JS variable data when generating random audio file

I have this really bugging problem with my JS and it relates to audio.
I am retrieving data from an API source with multiple audio files within... an example of one of those files would look like this... cool_audio_file/1, cool_audio_file/2, cool_audio_file/3, etc. So I made it generate a random number and insert at the end of the file name. 'cool_audio_file/'+randomnum I also have an option to generate a random "album" which based on randomnum generates the corresponding title.

<h1>Album</h1>
<button>Click to play</button><br>
<button>Generate Another!</button>

When a user clicks generate another, it generates another random number and assigns it to randomnum and plays it's audio, both audio play at the same time, In other words, all history of randomnum is played. So I guess my question is, how do you restart the variable info when you click again...




How to generate the same random numbers in one language as in another?

I am translating codes from Stata to R. The same random seed does not generate the same outputs. I am not sure if this is also the case in other languages (Python, Java etc.). How to generate identical random numbers in different languages?




What makes randint different from randbelow?

From 'import secrets' and 'import random' in Python, what makes those two methods different from each other? I know that randbelow from secrets offer better security, but what makes it so? If I were just making a simple program for myself and I want to generate a random number, would it be unusual to use 'secrets.randbelow()'?




mardi 28 juillet 2020

computer generating random number

I have been coding with the 'random' library in python3 and generated a random list with the values (0,1), and printed the list. I am not sure if did it wrong or this is the function behavior but with every execution of the program, I could notice that an ordered list with random values has been generated, which could imply that there isn't any randomness? (I know that there isn't really random function, but I wouldn't expect to that kind of order)

    list = []
    for i in range(100):
        if (random.randint(0, 1)) == 1:
            list.append(0)
        else:
            list.append(1)
    for i in range(10):               #
        for j in range(10):           # printing the list
            print(list[j],end=' ')    #
        print('')                     #

print of the list

Any help will be apriciated.

Blockquote




What is the difference between time(NULL) and time(0) in random number generation

When we set a seed to generate a random number in C/C++, we used to give the argument as time(NULL) or time(0) as srand(time(NULL)). What is the exact difference between these two? are they internally different or is there any other difference?




Random objects assigned true or false in C++

I have to assign a certain amount of objects (based on percentage) that have been randomly assigned a true value for a paid subscription attribute, which then get sorted by priority and arrival time in a priority queue. Currently what I have would assign only the first arriving callers a subscribed (true) status and can't seem to think of an easy way to randomize which callers are paid and which are not since each call object is generated sequentially in a for loop.

For example: If there is an average of 25 callers per hr, 25% of them are subscribed and the simulation is for 24 hrs, I would generate 600 callers, 150 subscribed and 450 unsubscribed and randomly assign the 150 subscribed = true

I think I would need to change my for loop range limit to n, then randomly generate a true or false value for bool subscribed within the for loop, but also keep track of how many are iterations are true and false for bool subscribed, which I tried to implement below and still get a random amount of true/false.

Main

    CallCenter dRus; 
    Rep r1;
    bool subscribed = false;
    int percentSubscribed = 0;
    int numSubscribed;
    int numNotSubscribed;
    int countSubbed;
    int countNotSubbed;
    int n;


    n = 24;
    numSubscribed = (percentSubscribed / 100) * n;
    numNotSubscribed = n - numSubscribed;

    for (int i = 0; i <n; i++) //start sim by creating subscribed and unsubscribed callers 
    {
        subscribed = rand() % 2;
        if (subscribed == true) { countSubbed++; }
        else { countNotSubbed++; };
        
        if ((countSubbed > numSubscribed) )
        {
            subscribed = false;
            dRus.generateCalls(subscribed);
        }
        else {dRus.generateCalls(subscribed);};

        
    }

    subscribed = false;
    for (int i = 0; i < numNotSubscribed; i++) //create not subscribed callers
    {
        dRus.generateCalls(subscribed);
    }

Call Center

void CallCenter::generateCalls(bool subbed) //create a call object
{   
    Caller cust(subbed); 
    cust.generateInterArrivalTime();                //generate an inter-arrival time for the the call
    cust.setArrivalTime(cust.getInterArrivalTime()+ clock);    //set the arrival time 
    clock += cust.getInterArrivalTime();                      // update the clock variable 
    callQ.push(cust); //put the call in the queue
}



How can I use the Random.Range's answer to set as the max value into the same Random.Range until it reaches 1

I want to create a script that generates a random number (between 1(min) and 9999(max)) and then I want the random number to become the new max for the same exact script.

Is there a way to create an equation or some sort of way to do this infinitely (until 1).

The only solution I have come up with is this:

private IEnumerator MyCoroutine()
{
    var a  = Random.Range(1, 9999 + 1);
    largeText.text = a.ToString();
    yield return new WaitForSeconds(2);
    if (a > 1)
    {
        var b  = Random.Range(1, a + 1);
        largeText.text = b.ToString();
        yield return new WaitForSeconds(2);
        if (b > 1)
        {
            //Then continues 'infinitely'
        }
    }
}

This is a solution, but I eventually run into the problem of having an extremely unwanted script.

Ofcourse I have the rest that I need with this script, and it does work, however I would like to know if there is an easier work around that doesn't involve me writing 1m lines of code.

Thank you!




Fair algorithm to convert random bytes into digit sequence

Most (if not all) CSPRNG functions available out there provide us byte sequences as result (eg. getrandom, CryptGenRandom, BCryptGenRandom, RNGCryptoServiceProvider, SecureRandom, CRYPT_GEN_RANDOM etc).

However, depending where we are supposed to use this random sequence our charset may be different (suppose you need only digits), and we may need to convert the byte sequence to fit our constraint.

A naive way to solve the problem is to convert each byte to its decimal representation and concatenate all numbers (the programming language doesn't matter):

randbytes = AnyRandomGenerator()
sequence = ""
for byte in randbytes:
  sequence = sequence + byte.ToInt().ToStr()
return sequence

This way, the random sequence 0xFE501000 would become the sequence 25480100.

It works, however, there is a big mistake in this approach: the probability of the first number to be "1" or "2" is significantly bigger than any other number (because bytes ranges from 0 to 255 and not from 0 to 999).

To solve this, an improvement would be to MOD 10 each digit:

randbytes = AnyRandomGenerator()
sequence = ""
for byte in randbytes:
  sequence = sequence + (byte.ToInt() MOD 10).ToStr()
return sequence

However, since MAX_BYTE = 255 is not a multiple of 10, this leads to small unfair distribution for numbers greather than five.

In an example made by Microsoft for .NET, they avoid this problem considering some random numbers "unfair". When an unfair number is generated, it is discarded and a new one is generated. This solves the problem, but I must say it isn't very elegant (it "waste" numbers :P).

Is there a best/fast way to achieve this conversion keeping the numbers normally distributed? Or the method used by Microsoft is the only way to go?

(PS: Although my examples uses a 10-digit charset = [0-9], I'm asking about charsets of any size, like the Dice Roll charset = [0-5] in the Microsoft example)




Dice game between 2 players up to a score of 50

I am creating a game where two players are rolling dice against each other.

Two people (player A, player B) play a dice game. they roll a dice each round and the higher number wins the game and the winner earn 5 points.If two people roll the same value of dice, they both earn 3 points. The game ends if one player reaches 50 points or higher. If both players reach 50 at the same round, that becomes deuce and one more round of game to go until higher value player wins the game (if the 11th round still tie, play next round. Here is my code so far, but I am not getting any of the scores to go to 50 to end the game.

public static void main(String[] args) {
    
    int playerA[] = new int[10];
    int playerB[] = new int[10];
    int playerAScore = 0;
    int playerBScore = 0;
    int round = 1;
    
    for (int i =0; i < playerA.length; i++) {
        System.out.println("Roll the die for round " + round++);
        playerA[i] = (int) ((Math.random() * 6) + 1);
        playerB[i] = (int) ((Math.random() * 6) + 1);
    
        System.out.println("player A has " + playerA[i] + " and player B has " + playerB[i]);
    
        if(playerA[i] == playerB[i]) {
            playerAScore = playerAScore + 3;
            playerBScore = playerBScore + 3;
        }
        else if (playerA[i] > playerB[i]) {
            playerAScore = playerAScore + 5;
        }
        else if (playerB[i] > playerB[i]) {
            playerBScore = playerBScore + 5;
        }
        if(playerAScore >= 50 || playerBScore >= 50) {
            break;
        }
    }
    
    System.out.println("The game is over.");
    
    if(playerAScore >= playerBScore)
        System.out.println("The winner is player A");
    else
        System.out.println("The winner is player B");
    
    System.out.println("How many rounds of game played?");
    System.out.println("Rounds played: " + round);
    
    System.out.println("Total Score per player:");
    System.out.println("Player A score: " + playerAScore);
    System.out.println("Player B score: " + playerBScore);
    
}

}




How is the std::shuffle_order_engine table managed?

When I call operator() on a std::shuffle_order_engine will a new number immediately be generated to refill the lookup table? Or, will numbers be used up from the table and only when a missing number is required the table refilled?




Javascript random generator with no repeats till all items have been displayed

I've read many other posts regarding this common issue, and I encourage anyone who sees this to read this entire post through. None of the other solutions that I've found have worked for me (I include a failed attempt below).

I have a functioning random generator that uses HTML and JavaScript. Each time a button is pushed, the function chooses a single item from an array and displays it using: 'document.getElementById'. Please see the below snippet for the working function. My problem is that I dislike the way it displays the same array items back to back or before some of the others have been see; the function is TOO RANDOM. I've been working on finding a way to change my random function so that it only displays repeat items once the entire array has been looped through.

var oddnumber = [
  '111',
  '222',
  '333',
  '444',
  '555',
]
var oddletter = [
  'AAA',
  'BBB',
  'CCC',
  'DDD',
  'EEE',
]
function newThing() {
  if(numberCheck.checked) {
    var randomY = oddnumber;
    }
  if(letterCheck.checked) {
    var randomY = oddletter;
  }
  var randomX = Math.floor(Math.random() * (randomY.length));
  var y = randomY;
  var x = randomX;
  document.getElementById("thingDisplay").innerHTML = y[x];
}
<body>
  <div id='thingDisplay'></div>
  <div>
    <button class="box" id="button01" onclick="newThing()">New Thing</button>
  </div>
  <div>
    <form>
      Number<label>&nbsp;<input type="radio" name="thing" id="numberCheck"/></label>
      <br/>Letter<label>&nbsp;<input type="radio" name="thing" id="letterCheck"/></label>
    </form>
  </div>
</body>

Many answers detail different ways to slice the array and push the slice to the bottom, but I'm unsure if this is what I'm looking for. Placing displayed items in a separate array is something I'd like to avoid since I will probably have thousands of array items in real world use, so it probably wouldn't be efficient.

Failed Attempt 1:

var oddnumber = [
  '111',
  '222',
  '333',
  '444',
  '555',
]
var oddletter = [
  'AAA',
  'BBB',
  'CCC',
  'DDD',
  'EEE',
]
function newThing() {
  if(numberCheck.checked) {
    var randomY = oddnumber;
    }
  if(letterCheck.checked) {
    var randomY = oddletter;
  }
  
  var res = randomY.sort(function() {
    return 0.5 - Math.random();
  });
  console.log(res.slice(randomY,1))
  document.getElementById("thingDisplay").innerHTML = [console.log];
}
<body>
  <div id='thingDisplay'></div>
  <div>
    <button class="box" id="button01" onclick="newThing()">New Thing</button>
  </div>
  <div>
    <form>
      Number<label>&nbsp;<input type="radio" name="thing" id="numberCheck"/></label>
      <br/>Letter<label>&nbsp;<input type="radio" name="thing" id="letterCheck"/></label>
    </form>
  </div>
</body>

Failed Attempt 2:

var oddnumber = [
  '111',
  '222',
  '333',
  '444',
  '555',
]
var oddletter = [
  'AAA',
  'BBB',
  'CCC',
  'DDD',
  'EEE',
]
function newThing() {
    if(numberCheck.checked) {
        var randomY = oddnumber;
    }
    if(letterCheck.checked) {
        var randomY = oddletter;
    }
    var selected;
    var temp;
    var str = "";
    var stub = "";

    for(var i = 0; i < randomY.length; i++){
        temp = randomY[i][Math.floor(Math.random() * randomY[i].length)];
        while(selected.contains(temp)){
            temp = randomY[i][Math.floor(Math.random() * randomY[i].length)];
        }
    selected.push(temp);
    str += temp;
    if(i < randomY.length - 1){str += stub;}
    }

    var x = i;
    document.getElementById("thingDisplay").innerHTML = y[x];
}
<body>
  <div id='thingDisplay'></div>
  <div>
    <button class="box" id="button01" onclick="newThing()">New Thing</button>
  </div>
  <div>
    <form>
      Number<label>&nbsp;<input type="radio" name="thing" id="numberCheck"/></label>
      <br/>Letter<label>&nbsp;<input type="radio" name="thing" id="letterCheck"/></label>
    </form>
  </div>
</body>

Edit: Preserving the 'document.getElementById' and the 'if' statements that determine the value of randomY is crucial.




Why would a mod return zero when it's restricted to <=1?

Card* createCard()
{

  /*This function dynamically allocates a new Card struct object and returns a 
  pointer to that struct object which will later be used to insert into a 
  linked list. There are three types of cards ATTACK, DEFEND, and RUN. 
  ATTACK and DEFEND cards also have a value. 
  You will assign a card type based on these random chances:
    40% - ATTACK: the value is a random number between 1 and 5 inclusive.
    50% - DEFEND: the value is a random number between 3 and 8 inclusive.
    10% - RUN: the value is a random number between 1 and 8 inclusive. 
    The value of a RUN card is only used for sorting purposes.*/
    
    Card* createdCard;
    int n;
    int v; 
    createdCard = (Card*) malloc(sizeof(Card));
    
    n = (rand()%10)+1;
    
    
    if(n == 1)
    {
        createdCard->cardType = RUN;
        v = (rand() % 8)+1;
        createdCard->value = v;
    }
    else if(n>1 && n<7)
    {
        createdCard->cardType = DEFEND;
        v = (rand() % 6)+3;
        createdCard->value = v;
    }
    else if(n>6 && n<10)
    {
        createdCard->cardType = ATTACK;
        v = ( rand() %5)+1;
        createdCard->value = v;
    }
    
    
    
     createdCard->next = NULL;
    
    return createdCard;

}

Output with A0 and should be 1 through 5




How come I can’t get a specific name? [closed]

What I am trying to do is get one specific name.

When it prints out and keep getting different random last names for the name that I choose from the first_class but don’t know how I can do that I thought by using the re module I could make it into a group and print it out the name that I wanted to choose but it hasn’t been working so far

EDIT

It is looked for a solution to get a pair of names out of the raw string and the list (first_class, second_class). The First attempt was to use regex library but this does not work.

import random
import re


first_class = (r"(Mary), (Sara) ,(Violet), Rob, joey, Jorge, Manny, Patty")

second_class = [" Perez" , " Valdiva", " Reys", " Diaz", " Walker", " Cortez", " Lopez", " Gonzalez", " Johnson"]


First_attendanc = (random.choice(first_class))
Second_attendanc = (random.choice(second_class))


names = (First_attendanc)
names_two = (Second_attendanc)

Here is where I feel like everything is in order for me to choose the name I want yet my code is not working?

print(re.match(first_class ,"Mary , Sara ,Violet, Rob, joey, Jorge, Manny, Patty")(raw_input("Choose name: " + names + names_two))).group(1)



lundi 27 juillet 2020

Randomly select n elements from Array in Scala

I want to select n unique elements from array where size of my array is normally 1000 and value of n is 3. I want to implement this in iterative algorithm where iterations are around 3000000 and I have to get n unique elements in each iteration. Here are some available solutions I fond but I can not use them due to their draw backs as discussed below.

import scala.util.Random
val l = Seq("a", "b", "c", "d", "e")
val ran = l.map(x => (Random.nextFloat(), x)).sortBy(_._1).map(_._2).take(3)

This method is slower as have to create three arrays and Sorting the array too.

 val list = List(1,2,3,4,5,1,2,3,4,5)
 val uniq = list.distinct
 val shuffled = scala.util.Random.shuffle(uniq)
 val sampled = shuffled.take(n)

Two arrays are generated and Shuffling the large array is slower process.

 val arr = Array.fill(1000)(math.random )
 for (i <- 1 to n; r = (Math.random * xs.size).toInt) yield arr(r)

This is faster tecnique but some times returns same element more than one time. Here is an output.

val xs = List(60, 95, 24, 85, 50, 62, 41, 68, 34, 57)
for (i <- 1 to n; r = (Math.random * xs.size).toInt) yield xs(r)

res: scala.collection.immutable.IndexedSeq[Int] = Vector( 24 , 24 , 41)

It can be observed that 24 is returned 2 times.

How can I change last method to get unique elements? Is there any other more optimal way to perform same task?




Randomly grab string from array, use as placeholder text, and equate to answer string in swift

I have two UITextFields that get the placeHolder.text randomly from an array. The part I am stuck on, is having an element in an array of answers, correspond to the placeHolder text.

Meaning: placeHolder.text is a question, user text input is the answer, and we check that the user answer is the same as the hard coded value.

sample code:

   let questionArray = ["name of your cat?", "name of your other cat?"]
   let questionArray2 = { more stupid questions ]
 
    let answerArray = ["cat damen", "diabetes"]
    let answerArray2 = [ more stupid answers ]

    var answerContainer: String()
    var answerContainer2: String()

    uitextField1.placeHolder = questionArray.randomElement()
    uitextField2.placeHolder = questionArray2.randomElement()
    
    Heres where I get stupid :
    
    func answerGenerator {
       if UItextField1.placeHolder == questionArray[0] {
          answerContainer = answerArray[0]
      }
    }

func submit(_ sender: UIButton) {
       if uitextField.text == answerContainer && uitextField2.text == answerContainer2 { 
   do good stuff 
    }
  }

I tried using a dictionary, but got stuck. I also thought about an Enum / Switch Case, but also got stuck as I have two textFields that need the placeHolder generated randomly.

so what happens is the actual answer that's supposed to be allocated to its question, maybe it happens, but I'm not grabbing it correctly to compare what the user will type in the textfield.

Its so easy, but I'm overthinking this.




How can I display an image from a URL with a random number in it?

I am trying to make a chemical compound generator of some sort, using PubChem. I have successfully generated a link to the website with a random number (e.g. https://pubchem.ncbi.nlm.nih.gov/compound/123456), as well as a link to the image (e.g. https://pubchem.ncbi.nlm.nih.gov/image/imgsrv.fcgi?cid=123456&t=l). However, when I try to embed the random image link into the document, it doesn't show up. I am only a starter when it comes to programming.

var lower = 0;
var upper = 100000000;
var rand = (Math.floor(Math.random() * (upper - lower)) + lower)
var url = "https://pubchem.ncbi.nlm.nih.gov/compound/" + rand
var img = "https://pubchem.ncbi.nlm.nih.gov/image/imgsrv.fcgi?cid=" + rand + "&t=l"
document.write("<a href=" + url + ">" + url + "</a>");
document.write("</br><a href=" + img + ">" + rand + "</a>");
document.write("</br><img src=" + img + "alt=" + rand + ">")



How to use std::uniform_int_distribution

I would like to be able to reset the lower and upper bounds of a std::uniform_int_distribution<T> object after it has been created, and it seems the param function in the class allows this functionality. See https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution/param (2).

But it's not clear to me how to construct this param_type object that it takes in. Could someone provide an example?




How do you convert crypto.randomBytes to custom alphabet? [duplicate]

I would like to generate a 40-character long string using only 0-9, how can I do that while also using crypto.randomBytes(x)? And what should x be, I'm not sure the relation between the bytes and the alphabet (which is only 10 characters, not 256). Is there a general formula for this?




Linear mixed effect model that differs by variable factor level

I have below dataset

student_id  school_id   non_verbal  quantitative    spatial   verbal    subject score_level valuation
69044       198        117.0         116.0          112.000000   105.0  26        1          77.0
57589       119        104.0         96.0            101.554674  89.0   16        1           62.0
65452       195        83.0          111.0           84.000000   97.0   15        1           62.0
26203       107        98.0          109.0           107.000000  102.0  11        1             47.0
25501       17         111.0         90.0            113.000000  118.0  27        1              62.0

My dependent variable is valuation and I want to build a linear mixed effect model where school_id is my random effect. But I want this model to differ by subject and score level. I want to build this in python.

Can anyone please suggest how should I do this in python also if any better model than linear mixed effect?

Any help will be appreciated.




Random Integer Array from positive integer array

I have an array of positive integers, what are some tricks to turn that array into one with negative numbers too? For example one could be r * (b-a) + a with b = -1 and a = 1. Do you know any other tricks like this?




Java: Can No Longer Use System.out.println() In My Application

I made a little "guess the random number" game that takes the user's input and checks if it is equal to the number generated using a for loop. If yes, the application prints a congrats statement and then breaks out of the loop. If no (and failed 5 times), the application is supposed to print out a game over-type statement

For some reason, my game over statement System.out.println("Sorry " + answer+ ". the answer was " + rand + ". Game Over."); does not print, even though all the other println() statements do. Why isn't it working?? Any help would be much appreciated!

Below is my code:

import java.util.Random;
import java.util.Scanner;

public class randgame_draft {
    public static void main(String[] args) {
        System.out.println("Welcome to RandGame. What's your name?");
        Scanner scanner = new Scanner(System.in);
        String answer = scanner.next();
        System.out.println("Hello, " + answer + ". Shall we begin?");
        Scanner ask = new Scanner(System.in);
        String response = ask.next();
        if (response.equals("yes")) {
            System.out.println("Alright!");
        } else {
            System.out.println("Oh, okay. Later!");
            return;
        }

        Random random = new Random();
        int rand = random.nextInt(20) + 1;
        for (int i = 0; i < 5; i++) {

            System.out.println(answer + ", please provide a random number between 1 and 20.");
            Scanner begin = new Scanner(System.in);
            int end = begin.nextInt();
            System.out.println("you chose " + end);

            if (end != rand && end > rand) {
                System.out.println("Hint: guess lower");
            } else if (end != rand && end < rand) {
                System.out.println("Hint: guess higher");
            } else if (end == rand){
                System.out.println("congratulations, you are correct!");
                System.out.println("answer was " + rand);
                System.out.println("thanks for playing, " + answer + "!");
                return;
            } else {
                System.out.println("Sorry " + answer+ ". the answer was " + rand + ". Game Over.");
            }

        }

    }
}



How to generate 3 random numbers with a sum between 30-50

So far I figured out how to generate 3 random numbers with a specific sum. But how would it work if I wanted the sum of the numbers to be anywhere from 30-50? So for example the numbers could be 10, 15, 8.




How to display methods from a random element in Arraylist?

I know how to get a random element from ArrayList, but what I don't know is how to also display only 1 element's methods. For example, I have two subclasses with a few methods that are very basic (they basically just print some stuff), and the ArrayList is in the superclass.

This is my code with the Cat and Dog being subclasses. Now the code prints one of them but methods from both classes are displayed. If the program picks Dog for example, then I want only the results from Dog's noise() and furr() to be displayed. How could I do this?

ArrayList<Animal> an = new ArrayList<>();
        an.add(new Cat());
        an.add(new Dog());

       for (Animal a : an) { 
        a.noise();
        a.furr();
    }
   
    int randomIndex = (int) (Math.random() * an.size());
    System.out.println( "The animal: " +  an.get( randomIndex ));



displaying random numbers starting with zero in JavaScript

I'm working on a random pin generating project with javascript. I want to generate random pins like 0351, 0947, 0268 etc. using Math.random() where the pin will start with 0 & the zero will be displayed in the output. how can I do that?




Get random item based on multiple weights

I'm trying to work out how to choose an item at random, based on a couple of weights. Let me explain.

  • I have a person object which has an age group assigned, young, middle or old. This age group is a known variable.
  • I have 3 groups, each with their own chance of being selected, but also weighted towards an age group.

For example:

  • Group 1 has a 50% chance of being chosen, but more if they are young.
  • Group 2 has a 30% chance of being chosen by any age group.
  • Group 3 has a 20% chance of being chosen, but more if they are middle aged.

I'm not looking for a code hand out, but more theory to push me towards the correct answer. I know how to pick a group based on it's percentage alone, but I'm not quite sure how to weight it based on age group..

Thanks in advance. :)




dimanche 26 juillet 2020

Sampling without replacement with unequal, dependent probabilities

So from answers to the question, Randomly Generating Combinations From Variable Weights, I've managed to sample without replacement given unequal probabilities. I've implemented this in my particular context and it works great.

Now I have access to additional information about my distribution. Specifically, I've been using a neural network to generate these probabilities so far, and I've now trained my neural network to output a probability for each pair of unique objects, in addition to probabilities for individual objects.

So if the population is [A, B, C, D, E, F] and I'll be sampling groups of size 3, then I have access to the probability that the resulting sample will contain both A and B, or the probability that the resulting sample will contain both C and E, etc. I also still have access to the probabilities that the sample contains any of the individual elements.

The question above has made me realize that sampling is a much harder problem than I had initially expected it to be. Still, I'm wondering if there's any way this information about the probability of these pairs could be used to make my sample better match my actual target distribution.

Using the method discussed in the first answer of the question above, where gradient descent is used to find probabilities that result in the correct conditional probabilities, when supplied the following probabilities:

[0.349003, 0.56702, 0.384279, 0.627456, 0.585684, 0.486558] (for the respective elements of the population from above)

a sample of 3,000,000 groups follows the following distribution, where intersections of the matrix represent the probability that a sampled group contains both the elements that are intersected:

   A          B          C          D          E          F
A [0.34860067 0.15068367 0.09183067 0.17385267 0.15775267 0.12308167]
B [0.15068367 0.567596   0.168863   0.309292   0.28285467 0.22349867]
C [0.09183067 0.168863   0.384101   0.19396467 0.175895   0.13764867]
D [0.17385267 0.309292   0.19396467 0.62724833 0.32153967 0.25584767]
E [0.15775267 0.28285467 0.175895   0.32153967 0.58571833 0.23339467]
F [0.12308167 0.22349867 0.13764867 0.25584767 0.23339467 0.48673567]

I want to, for example, be able to provide my sampling algorithm with the following matrix:

   A        B        C        D        E        F
A [0.349003 0.148131 0.15166  0.098827 0.151485 0.147903]
B [0.148131 0.56702  0.140829 0.327032 0.331278 0.18677 ]
C [0.15166  0.140829 0.384279 0.190329 0.09551  0.19023 ]
D [0.098827 0.327032 0.190329 0.627456 0.391803 0.246921]
E [0.151485 0.331278 0.09551  0.391803 0.585684 0.201292]
F [0.147903 0.18677  0.19023  0.246921 0.201292 0.486558]

and have its sample's distribution closer to matching this supplied matrix than if only individual probabilities were used as was done above.

I'm okay with the sampling algorithm not perfectly matching the probabilities, though it would be nice if that was possible. Based on my own attempts at this problem, I realize that things are more difficult because though P(A and B) is supplied, it is impossible to derive P(A and B and C) from just the information in the matrix. Basically my question is, is there any way for me to use this additional information I have (probabilities for pairs) in order to produce samples with distributions that better model my intended distribution than if I used only the probabilities for each individual object.




PHP's str_shuffle function internals

Basically I'm looking for the internals of the str_shuffle function, I want to know how does PHP randomizes the string. Does it use rand() , mt_rand() and how it is seeded, I'm pretty sure it uses the Fisher-Yates algorithm.

The best I would hope for is its complete C equivalent. (PHP is written in C), but I can't find anything on the matter, the documentation is pretty light and superficial.

What I ultimately what to know is, suppose I have something like str_shuffle('whatever'), how could I predict its output? since str_shuffle is said to not be cryptographically secure, but I couldn't find any security issues or complaints against str_shuffle. Thanks




Socket listen for random time, then stop listening and continue other code

My end goal is to have a program start-up, and then stay in a 'listening for connections' mode for a random amount of time (between 0 and 10 seconds) and then continue on to a different block of code.

This is what I have so far, but the time.sleep would mean that it is going to block the code from accepting connections. Not what I want. I want it alive and able to connect throughout the random amount of time.

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sReceive:

                sReceive.bind(('0.0.0.0', port))
                sReceive.listen()
                print('Listening on ', port)

                time.sleep(random.uniform(0.0, 10.0))
                #Here, after the random time has elapsed, the socket should close and jump to "otherCode()" if
#no connection has been received in that time.
                conn, addr = sReceive.accept()

otherCode()

Is there something with time.perf_counter that I am missing? Or do I just need a new thread?

Thank you!




I'm trying to create a battleship game but I'm using lists instead of a normal grid

row1 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row2 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row3 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row4 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row5 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row6 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row7 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row8 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row9 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row10 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]

This is the code that the A.I would use for it's own grid. It would work so that a string that would repesent a ship would be inserted into the lists e.g.

row1 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row2 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row3 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row4 = [['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]
row5 = [['-'], ['-'], ['-'], ['-'], ['A'], ['-'], ['-'], ['-'], ['-'], ['-']]
row6 = [['-'], ['-'], ['-'], ['-'], ['A'], ['-'], ['-'], ['-'], ['-'], ['-']]
row7 = [['-'], ['-'], ['-'], ['-'], ['A'], ['-'], ['-'], ['-'], ['-'], ['-']]
row8 = [['-'], ['-'], ['-'], ['-'], ['A'], ['-'], ['-'], ['-'], ['-'], ['-']]
row9 = [['-'], ['-'], ['-'], ['-'], ['A'], ['-'], ['-'], ['-'], ['-'], ['-']]
row10 = [['-'],['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-'], ['-']]

How do I make the inserting random and with multiple other ships.




How to make a function with random numbers

Hi I am trying to create a function that will select 5 random numbers which will equal a total amount already given and put the 5 numbers in a list. When I pass a number through the function I get an error. I cant seem to get what Im doing wrong.

def num_lottery(total_num):
    the_set =[]
    n1 = random.randint(1, total_num)
    n2 = random.randint(1, total_num - n1)
    n4 = random.randint(1, total_num - (n1 + n2 + n3))
    n5 = total_num - (n1 + n2 + n3 + n4)
    the_set.append(n1, n2, n3, n4, n5)
    return the_set

It works when I pass through the total_num = 50000, but not when total_num = 5000. Any help is appreciated. Thanks




Random numbers with for loop

JS function that uses a for loop, random numbers, and strong functions to:

  • Show ten transactions with subtotals between $50 and $150
  • Show random free gift
  • Show discounted total
  • All numbers has exactly two decimal places



The compiler reported some strange error, what does this mean? [closed]

Guess_number.c:44:1: error: expected declaration or statement at end of input C language , Code below: My code

Error message: Error




What is the code behind the built-in function ' random() '? [closed]

I have been curious to know what lies behind the builtin functions like printf, random etc..

printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"



I need to shuffle/randomize a string that was created by a join method, but returns a random array instead [closed]

Function I used to join the array elements and randomize the joined string.

function passwordJoin() { 
   let finalPassword = final.join('');
   console.log(finalPassword); 

Randomize the String (Returning the array randomized) let random = final.sort(() => Math.random() - 0.5); console.log(random); }




samedi 25 juillet 2020

Sampling without replacement given probabilities of objects being in sample

I've seen algorithms for weighted sampling without replacement such as the Efraimidis & Spirakis algorithm explained in the second answer to this question: Faster weighted sampling without replacement. My problem is that I don't have access to weights, and rather have access to the probabilities of each element being in the sample.

For example, given that the Efraimidis & Spirakis algorithm is trying to choose 3 integers from the integers 1 to 6, and is given the weights [0.995, 0.001, 0.001, 0.001, 0.001, 0.001] for the respective 6 integers, the algorithm's samples contain each of the integers with the following probabilities:

1: 1.00000
2: 0.39996
3: 0.39969
4: 0.39973
5: 0.40180
6: 0.39882

(This data is taken from the same question discussed above).

The problem is that I only have access to those resulting probabilities. Is there any way to convert these probabilities to weights, or is there another algorithm or a modification to this algorithm that can perform sampling without replacement using probabilities rather than weights.




Problem with continue instruction after rand() function

I just wanted to solve an exercise that asks me to write a routine to generate a set of even random numbers between 2 to 10.

The problem is when printing, because I want that only the last number not to be followed by a comma. This is my code and these two execution

The problem is when printing, because I want the last number not to be followed by a comma.

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

int main()
{
    int i, a, b, c;

    i = a = b = c = 0;

    srand(time(NULL));

    for (i = 2; i <= 10; i++)
    {
        a = rand() % 8 + 2;

        if ((i <= 10) && (a % 2) != 0)
        {   
            continue;
        }
        printf((i < 10) ? "%d, " : "%d\n", a);
    }
    return 0;
}

and these two execution examples.

In one the comma does not appear at the end but in another it does. When debugging I see that the error happens when the last number is odd, because the continue statement causes it to go to the next iteration.

I appreciate any suggestion.




Is This The Right Way of using OOP in Python? [closed]

I Have Been Learning Python For Last 2 month and i am very confused with OOP. I Have Created A Simple Blackjack Game using tkinter Module using Classes. Is This The Right Way of Using Classes in Python. I'm mostly interested in improving my OOP, so I would appreciate your feedback.

Cards Images : https://drive.google.com/uc?export=download&id=1U3rgUNa8F93VQz-B39I7-V0w_RaLDQ5M

import random
import tkinter


class Deck(object):
    """Basic Class For Cards

    args:
        card_type (list[Card_Types]) = A list Containing All Cards Types diamond, spade, heart, club
        high_cards (list[high_cards]) = a List Containing high_cards jack, king, queen
        card_no (range) = card no from 1 to 10 for each card_type total 52 card
        cards list(card_image, card_value) = an Empty List To Store All Cards images and its value inside a Tuple
    methods:
        load_cards() : A Method To Load Cards images and its Value in Cards list
        shuffle() : A Method To Shuffle Cards"""

    def __init__(self):
        self.card_types = ["club", "diamond", "heart", "spade"]
        self.high_cards = ["jack", "king", "queen"]
        self.card_no = [i for i in range(1, 11)]
        self.cards = []

    def load_cards(self):
        extension = ".png"
        for card_type in self.card_types:
            for card_no in self.card_no:
                # Creating Card Directory Location
                card_dir = "cards/{0}_{1}{2}".format(card_no, card_type, extension)
                image = tkinter.PhotoImage(file=card_dir)
                self.cards.append((image, card_no))

            for card in self.high_cards:
                card_dir = "cards/{0}_{1}{2}".format(card, card_type, extension)
                image = tkinter.PhotoImage(file=card_dir)
                self.cards.append((image, 10))
        return self.cards

    def shuffle_cards(self):
        random.shuffle(self.cards)

    def __len__(self):
        return len(self.cards)

    def __getitem__(self, i):
        return self.cards[i]


class Dealer(object):
    def __init__(self):
        self.hand = []
        self.score = 0


class Player(Dealer):
    def __init__(self, name="unnamed"):
        super().__init__()
        self.name = name


class BlackJack(object):

    def __init__(self):
        self.main_window = tkinter.Tk()
        self.deck = Deck()
        self.player = Player("Afzal")
        self.dealer = Dealer()
        self.main_frame = tkinter.Frame(self.main_window, background="green")
        self.dealer_frame = tkinter.Frame(self.main_frame, background="green")
        self.player_frame = tkinter.Frame(self.main_frame, background="green")
        self.result_var = tkinter.StringVar()
        self.player_score_var = tkinter.IntVar()
        self.dealer_score_var = tkinter.IntVar()

    def start_game(self):
        self.main_window.title("BlackJack")
        self.main_window.geometry("640x480")
        self.main_window["padx"] = 7
        self.main_window["pady"] = 7
        # Adding Result Label To Display Who Wins
        result_label = tkinter.Label(self.main_window, textvariable=self.result_var)
        result_label.grid(row=0, column=0, columnspan=3, sticky="ew")
        result_label.config(background="green", fg="black")
        # Adding Card Frames For Player And Dealer
        # main_frame = tkinter.Frame(self.main_window, background="green")
        self.main_frame.grid(row=1, column=0, columnspan=3, rowspan=3, sticky="ew")
        self.main_frame["padx"] = 5
        self.main_frame["pady"] = 5

        # Adding Dealer_name and Score
        dealer_name = tkinter.Label(self.main_frame, text="Dealer")
        dealer_name.grid(row=0, column=0)
        dealer_name.config(background="green", fg="black")
        dealer_score = tkinter.Label(self.main_frame, textvariable=self.dealer_score_var)
        dealer_score.grid(row=1, column=0)
        dealer_score.config(background="green", fg="black")

        # Adding playername and Score
        player_name = tkinter.Label(self.main_frame, text=self.player.name)
        player_name.grid(row=2, column=0)
        player_name.config(background="green", fg="black")
        player_score = tkinter.Label(self.main_frame, textvariable=self.player_score_var)
        player_score.grid(row=3, column=0)
        player_score.config(background="green", fg="black")

        # Adding Frame For Dealers Cards
        self.dealer_frame.grid(row=0, column=1, rowspan=1, sticky="ew")
        self.dealer_frame["padx"] = 3
        self.dealer_frame["pady"] = 3

        # Adding Frame For Player Cards
        self.player_frame.grid(row=2, column=1, rowspan=1, sticky="ew")

        # Adding Buttons For Player , dealer and Newgame
        dealer_button = tkinter.Button(self.main_window, text="Dealer", command=self.dealer_card)
        player_button = tkinter.Button(self.main_window, text=self.player.name, command=self.player_card)
        new_game = tkinter.Button(self.main_window, text="New Game", command=self.new_game)
        dealer_button.grid(row=4, column=0)
        player_button.grid(row=4, column=1)
        new_game.grid(row=4, column=2)

        # Load Cards in Deck
        self.deck.load_cards()

        # Distribute Starting Cards 2 For Player And 1 For Dealer
        self.start_cards()

        self.main_window.mainloop()

    def deal_cards(self, frame):
        self.deck.shuffle_cards()
        next_card = self.deck.cards.pop()
        tkinter.Label(frame, image=next_card[0]).pack(side="left")
        # print(len(self.deck))
        self.deck.cards.append(next_card)
        print(self.deck.cards)
        return next_card

    def player_card(self):
        self.player.hand.append(self.deal_cards(self.player_frame))
        print("Player Hand", self.player.hand)
        self.player.score = self.calculate_hand(self.player.hand)
        self.player_score_var.set(self.player.score)
        if self.player.score > 21:
            self.result_var.set("Dealer Wins")
        elif self.player.score > 21 and self.player.score == self.dealer.score:
            self.result_var.set("Draw")

    def dealer_card(self):
        self.dealer.hand.append(self.deal_cards(self.dealer_frame))
        print("Dealer Hand", self.dealer.hand)
        self.dealer.score = self.calculate_hand(self.dealer.hand)
        self.dealer_score_var.set(self.dealer.score)
        if self.dealer.score > 21:
            self.result_var.set(self.player.name + " Wins")
        elif self.dealer.score > 21 and self.dealer.score == self.player.score:
            self.result_var.set("Draw")

    @staticmethod
    def calculate_hand(hand):
        ace = False
        score = 0
        for i in hand:
            card_value = i[1]
            if card_value == 1 and not ace:
                card_value = 11
                ace = True
            score += card_value
            if score >= 21 and ace:
                score -= 10
                ace = False
        return score

    def new_game(self):
        self.dealer.hand.clear()
        self.player.hand.clear()
        self.dealer_frame.destroy()
        self.player_frame.destroy()
        self.player.score = 0
        self.dealer.score = 0
        self.result_var.set("")
        self.dealer_frame = tkinter.Frame(self.main_frame, background="green")
        self.player_frame = tkinter.Frame(self.main_frame, background="green")
        self.dealer_frame.grid(row=0, column=1, rowspan=1, sticky="ew")
        self.player_frame.grid(row=2, column=1, rowspan=1, sticky="ew")
        self.deck.shuffle_cards()
        self.start_cards()

    def start_cards(self):
        self.player_card()
        self.dealer.hand.append(self.deal_cards(self.dealer_frame))
        self.dealer.score = self.calculate_hand(self.dealer.hand)
        self.dealer_score_var.set(self.dealer.score)
        self.player_card()


blackjack = BlackJack()
blackjack.start_game()



Random number such that, in [a, b, c], a is 2x likely b, b is 2x likely c. (2x or any abitrary number)

Is there something already built-in .NET (Core v3.1 if that matters) Library to do this? Is there a helpful 3rd party library? Or do I have to do it manually using discrete distribution?

In any case, please advise me the best / cleanest method. Thanks




Tweet with a random generated number

I'm a newbie to Python actually i want a script to tweet automatically with some random numbers but unfortunately the script always generate a same random number everytime so it leads to a duplicated tweet after some time

Here is my code :

 # importing the module 
import tweepy
from time import sleep
import random


# personal information 
api_key = "xxx"
api_secret_key = "xxx"
access_token = "yyy"
access_token_secret ="zzz"


# authentication 
auth = tweepy.OAuthHandler(api_key, api_secret_key) 
auth.set_access_token(access_token, access_token_secret) 


# authentication of access token and secret 
api = tweepy.API(auth) 

randomlist = random.sample(range(0, 99), 99)
int = random.choice(randomlist)
string = f"{int}"
print(int)
print("Attempting to Comment.", flush=True)

#put your tweets here 
list=["t.co/DVI9mPqtu",
"t.co/mkPzaqXge",
"t.co/ql9UxICTy",
"t.co/dDkDiqj92",
"t.co/LeT4rJRQP",
"t.co/zQsMcPCeY",
"t.co/vrQYUS5ci",
"t.co/QPzpLeH7s",
"t.co/711O1d44J",
"t.co/xxMZiIaer",
"t.co/UPrtKk459",
"t.co/7lDJFRfnm",
"t.co/MoBnbLa5r",
"t.co/LafFjnGcl",
"t.co/QA9VkfaUN",
"t.co/0gWFpbSXZ",
"t.co/tlJLpaUR3",
"t.co/TXFvnG7a1",
"t.co/BixvJkFh2",
"t.co/ceHLkEUgR",
"t.co/ZFFbu3hHu",
"t.co/muGfyIg40",
"t.co/uW2XAA6zF",
"t.co/pTbJbljMA",
"t.co/yYIUmLljV",
"t.co/T1kGm1JeC",
"t.co/4sYk7EWWD"
]

# Posting of tweets 
for i in range(len(list)):
    try:
        #insert more hashtags if you want to here
        api.update_status(status =list[i]+" "+ string+" #twitter") 
        print("successfully tweeted")
        sleep(360)
    except KeyboardInterrupt:
        exit()     

I don't know what's wrong in this script but I faced a same random number genrated every time instead of different one. Thanks in advance.




Probability distribution in np.random.choice

The numpy function np.random.choice takes in an optional parameter called 'p' that denotes the probability distribution of the values it is sampling . So , my question is , even though the function generates random values , do values that have higher probability more likely to be sampled ? Meaning , does it randomly choose a value from a subset of " Most probable values " ?

Am I right in perceiving it that way ? Or can someone please correct my assumption ?




Random number generator with corresponding letter

I have 2 circuits, both made up of a dual seven segment display and A pic16f684 (As shown below) the first circuit uses the code supplied to generate a random number 1-26. The letter portion is the same circuit, but with one of the transistor removed, to disable one side. circuit

/*
 * File:   main.c
 * Target: PIC16F684
 * Compiler: XC8 v2.20
 * IDE: MPLABX v5.25
 * 
 * Description:
 *
 * Created on July 21, 2020, 3:45 PM
 * 
 *                            PIC16F684
 *                  +------------:_:------------+
 *         GND -> 1 : VDD                   VSS : 14 <- 5v0
 * SEG_a_DRIVE <> 2 : RA5/T1CKI     PGD/AN0/RA0 : 13 <> DIGIT_DRIVE_2
 *         SW2 <> 3 : RA4/AN3       PGC/AN1/RA1 : 12 <> DIGIT_DRIVE_1
 *         SW1 -> 4 : RA3/VPP           AN2/RA2 : 11 <> 
 * SEG_b_DRIVE <> 5 : RC5/CPP1          AN4/RC0 : 10 <> SEG_g_DRIVE
 * SEG_c_DRIVE <> 6 : RC4/C2OUT         AN5/RC1 : 9  <> SEG_f_DRIVE
 * SEG_d_DRIVE <> 7 : RC3/AN7           AN6 RC2 : 8  <> SEG_e_DRIVE
 *                  +---------------------------:
 *                             DIP-14
 */

// CONFIG --- Configuration Word --- START
#pragma config FOSC = INTOSCIO
#pragma config WDTE = OFF
#pragma config PWRTE = OFF
#pragma config MCLRE = OFF
#pragma config CP = OFF
#pragma config CPD = OFF
#pragma config BOREN = OFF
#pragma config IESO = OFF
#pragma config FCMEN = OFF
// CONFIG --- Configuration Word --- END

#include <xc.h>
#include <stdlib.h>

/* Oscillator frequency we will select with the OSCCON register */
#define _XTAL_FREQ (4000000ul)
/*
 * Segment locations
 * of an LED display
 *      ---a---
 *     :       :
 *     f       b
 *     :       :
 *      ---g---
 *     :       :
 *     e       c
 *     :       :
 *      ---d---
 */
const unsigned char LEDDigit[] = {
//     abcdefg, Segment on = 0
    0b00000001, // "0"
    0b01001111, // "1"
    0b00010010, // "2"
    0b00000110, // "3"
    0b01001100, // "4"
    0b00100100, // "5"
    0b00100000, // "6"
    0b00001111, // "7"
    0b00000000, // "8"
    0b00001100, // "9"
    0b00001000, // "A"
    0b01100000, // "b"
    0b00110001, // "C"
    0b01000010, // "d"
    0b00110000, // "E"
    0b00111000  // "F"  
}; 



void main(void) 
{
    unsigned char DisplayValue, DisplayLED, DigitSegments;
    unsigned char LoopCount;
    unsigned int  Temp;
    
    PORTA = 0;
    PORTC = 0;
    CMCON0 = 7;                 // Turn off Comparators 
    ANSEL = 0;                  // Turn off ADC 
    
    __delay_ms(500);            // wait for ICD before making PGC and PGD outputs;
    TRISA = 0b011100;           // RA5, RA1, RA0 are outputs
    TRISC = 0b000000; 
    OPTION_REGbits.nRAPU = 0;   // Enable weak pull-up on PORTA
    WPUA = 0;                   // Turn off all pull-ups
    WPUAbits.WPUA4 = 1;         // Turn on RA4 pull-up
    
         
    DisplayValue = 0;           // Start Displaying at 0x00 
    DisplayLED = 0;             // Display the 1s first
    LoopCount = 0;
    srand(0x1234);
    
    for(;;)
    {
        PORTC = 0xFF;   // turn off all segment drivers
        PORTA = 0xFF;   // and digit drivers
        if (1 == (DisplayLED & 1))
        {
            DigitSegments = LEDDigit[(DisplayValue >> 4) & 0x0F];
            if(DigitSegments & 0b1000000)
                          {
                PORTA = 0b111110;   // turn on Digit driver 2
            } 
            else 
            {
                PORTA = 0b011110;   // turn on Digit driver 2 and SEG_a_DRIVER
            }
        }
        else
        {
            DigitSegments = LEDDigit[DisplayValue & 0x0F];
            if(DigitSegments & 0b1000000)
            {
                PORTA = 0b111101;   // turn on Digit driver 1
            } 
            else 
            {
                PORTA = 0b011101;   // turn on Digit driver 1 and SEG_a_DRIVER
            }
        }
        PORTC = DigitSegments;      // turn on segment drivers b to g
        DisplayLED++;               // select next digit

        __delay_ms(10);             // Show digit for 10 milliseconds
        
        if(0 == PORTAbits.RA3)      // is SW1 pressed?
        {
            LoopCount++;
            if(LoopCount == 1)
            {
                 // Display a new random value every 500 milliseconds
                Temp = rand() & 0xFFu;      // put random value in range of 0 to 255 and treat is as a fraction in range (0/256) <= value < (255/256)
                Temp = (Temp * 26u + 0x100u) >> 8; // Use tricky math to make a random number in the range from 1 to 56
                DisplayValue = (Temp / 10u) << 4;  // Extract the ten's digit
                DisplayValue = DisplayValue | (Temp % 10); // Extract the one's digit
            }
            if(LoopCount >= 50)
            {
                LoopCount = 0;
            }
        }
        else
        {
            LoopCount = 0;
        }

        if(0 == PORTAbits.RA4)      // is SW2 pressed?
        {
            DisplayValue = 0;       // Reset display value to zero
            LoopCount = 0;
        }
    }
}

My goal to is generate the corresponding letter on the second seven segment display using a modified alphabet. however, I cant figure out how to do this. My original thought was to output the temp value to the second pic16f684 with modified LEDDigits[];

const unsigned char LEDDigit[] = {
//     abcdefg, Segment on = 0
    0b01111110, //"-"
    0b00001000, // "A"
    0b01100000, // "b"
    0b00110001, // "C"
    0b01000010, // "d"
    0b00110000, // "E"
    0b00111000, // "F"  
    0b00100001, // "G"
    0b01001000, // "H"
    0b01111001, // "I"
    0b01000011, // "J"
    0b00101000, // "Modified K"
    0b01110001, // "L"
    0b00010101, // "Modified M"
    0b01101010, // "n"
    0b01100010, // "o"
    0b00011000, // "P"
    0b00001100, // "q"
    0b01111010, // "r"
    0b00100100, // "S"
    0b01110000, // "t"
    0b01100011, // "u"
    0b01010101, // "Modified V"
    0b01000000, // "Modified W"
    0b00110110, // "Modified X"
    0b01000100, // "y"
    0b00010010 // "Z"
        
}; 

But I dont believe I can just output that number. How can I display the number (1-26) on one dual display, and the corresponding letter on another display.

Could I potentially add the second seven segment display into the number circuit, set its transistor on RA2, and have it display the letter at the same time? how would this work?




Select a part of a float value and randomize the missing part in Python

If i have a float number like float = 51.31876543.

How can I create a new float value selecting the first seven numbers and generating randomly the remain numbers? To obtain something like this:

float = 51.31876 + 3 random numbers
like 51.31876411 or 51.31876739 ...



Raspberry Pi update new random list "on the fly" wav files

I have a program that is working great. Basically I'm having some fun and wrote a program to mess with my roommates. Anytime someone walks down the hall the motion detector plays a random sound from a list of funny movie clips and whatnot. It's basically a proof of concept with an older Pi. I have since purchased a newer raspberry pi with 7" monitor that I would like to put in the hall and have a program that can record sounds through a mic and add them to the list (by pushing a button on the screen). Though the program below works great, anytime I upload a new sound clip while the program is running it crashes. I forsee this being an issue, as recording any new sounds via pushing a button on the 7" touchscreen will cause the same thing to happen. LONG STORY SHORT: can this code below be modified so that adding new sounds while the program is running wont cause it to crash? OR, is there another workaround that my super rookie coding brain hasn't thought of? Much thanks to the internet community, after being a web designer for years I'm finally finding something in coding that interests me.

import pygame.mixer
from tkinter import *
import glob
import random
import time
from gpiozero import LED
from gpiozero import MotionSensor

green_led = LED(17)
pir = MotionSensor(4)
sound_list = glob.glob("sounds/*.wav")


green_led.off()
pygame.mixer.init()


while True:
   
    pir.wait_for_motion()
    print("Motion Detected")
    green_led.on()    


    pygame.mixer.Sound(random.choice(sound_list)).play()
    print("Playing Sound")

    pir.wait_for_no_motion()
    green_led.off()
    print("No Motion")



vendredi 24 juillet 2020

Why won't my code display when I use Local Storage and JSON?

I am working on a project in which a user selects 1 choice from 3 random options. There are twenty total rounds of this. I set the "draft" or selection up on one file, where the rounds are separated into divs and when the user picks an option from the first round, then that round disappears and a new round appears using "display:none." I recently added localStorage commands to the file, and ever since I did this, the code no longer successfully switches from round to round. When a selection is made, it stays on the same round and the "display:none" command does nothing. What should I do differently?

Here is the JS file:

var qbData = [{name: 'Patrick Mahomes', team: 'KC', overall: 99},{name: 'Lamar Jackson', team: 'BAL', overall: 97},{name: 'Russell Wilson', team: 'SEA', overall: 98},{name: 'Deshaun Watson', team: 'HOU', overall: 95},{name: 'Drew Brees', team: 'NO', overall: 95},{name: 'Aaron Rodgers', team: 'GB', overall: 92},{name: 'Ryan Tannehill', team: 'TEN', overall: 92},{name: 'Kyler Murray', team: 'ARI', overall: 90},{name: 'Carson Wentz', team: 'PHI', overall: 88},{name: 'Matt Ryan', team: 'ATL', overall: 86},{name: 'Dak Prescott', team: 'DAL', overall: 86},{name: 'Philip Rivers', team: 'IND', overall: 86},{name: 'Tom Brady', team: 'TB', overall: 86},{name: 'Ben Roethlisberger', team: 'PIT', overall: 86},{name: 'Josh Allen', team: 'BUF', overall: 85},{name: 'Matthew Stafford', team: 'DET', overall: 84},{name: 'Kirk Cousins', team: 'MIN', overall: 84},{name: 'Cam Newton', team: 'FA', overall: 83},{name: 'Jared Goff', team: 'LAR', overall: 82},{name: 'Sam Darnold', team: 'NYJ', overall: 82},{name: 'Derek Carr', team: 'LV', overall: 82},{name: 'Jimmy Garoppolo', team: 'SF', overall: 82},{name: 'Ryan Fitzpatrick', team: 'MIA', overall: 81},{name: 'Daniel Jones', team: 'NYG', overall: 80},{name: 'Drew Lock', team: 'DEN', overall: 80},{name: 'Gardner MINSHEW', team: 'JAC', overall: 80},{name: 'Dwayne Haskins', team: 'WAS', overall: 80},{name: 'Baker Mayfield', team: 'CLE', overall: 79},{name: 'Jameis Winston', team: 'NO', overall: 79},{name: 'Jarrett Stidham', team: 'NE', overall: 79},{name: 'Justin Herbert', team: 'LAC', overall: 78},{name: 'Mitch Trubisky', team: 'CHI', overall: 77},{name: 'Nick Foles', team: 'CHI', overall: 76},{name: 'Andy Dalton', team: 'DAL', overall: 76},{name: 'Mason Rudolph', team: 'PIT', overall: 74},{name: 'David Blough', team: 'DET', overall: 73},{name: 'Devlin Hodges', team: 'PIT', overall: 73},{name: 'Will Grier', team: 'CAR', overall: 72}];

}
let qbshuffled = shuffle([...qbData]);
let hbshuffled = shuffle([...hbData]);

const btn = document.querySelector('#btn');
// handle click button
btn.onclick = function () {
    const rbs = document.querySelectorAll('input[name="teamName"]');
    let selectedValue;
    for (const rb of rbs) {
        if (rb.checked) {
            selectedValue = rb.value;
            break;
        }
    }
    document.getElementById("teamSelection").style.display = "none";
    document.getElementById("qbRound").style.display = "block";
    document.getElementById("showTeam").style.display = "block";
    localStorage.setItem('teamName', JSON.stringify(selectedValue));
};

for (let display of document.querySelectorAll(".qbdisplay")) {
    let {name, team, overall} = qbshuffled.pop();
    display.innerHTML = name + ' ' + team + ' ' + overall;
}
for (let display of document.querySelectorAll(".hbdisplay")) {
    let {name, team, overall} = hbshuffled.pop();
    display.innerHTML = name + ' ' + team + ' ' + overall;
}

This is the function that I think the issue lies in:

function qbSelect1 () {
  var qbValue = document.getElementById("qb1").innerHTML;
  var qbSplit = qbValue.split(" ");
  var qbName = qbSplit[0] + " " + qbSplit[1];
  document.getElementById("overall").style.display = "block";
  document.getElementById("overall").innerHTML = qbSplit[3];
  document.getElementById("cumovr").innerHTML = qbSplit[3];
  alert("You have selected " + qbName);
  document.getElementById("qbTeam").innerHTML = qbName;
  document.getElementById("qbRound").style.display = "none";
  localStorage.setItem('qbName', JSON.stringify(qbName));
  localStorage.setItem('qbTeam', JSON.stringify(qbSplit[2]));
  localStorage.setItem('qbOverall', JSON.stringify(qbSplit[3]));
  document.getElementById("hbRound").style.display = "block";
  }

And this is the HTML File:

<div id="teamSelection" style = "display:none;">
  <h1> Select a Team </h1>
  <form id="teamPick" onsubmit="submitTeamName()">
    <input type="radio" name="teamName" id="NYG" value="New York Giants">
    <label for="NYG">New York Giants </label><br>
    <input type="radio" name="teamName" id="ARI" value="Arizona Cardinals">
    <label for="ARI">Arizona Cardinals </label><br>
    <input type="radio" name="teamName" id="ATL" value="Atlanta Falcons">
    <label for="ATL">Atlanta Falcons </label><br>
    <input type="radio" name="teamName" id="BAL" value="Baltimore Ravens">
    <label for="BAL">Baltimore Ravens </label><br>
    <input type="radio" name="teamName" id="BUF" value="Buffalo Bills">
    <label for="BUF">Buffalo Bills </label><br>
    <input type="radio" name="teamName" id="CAR" value="Carolina Panthers">
    <label for="CAR">Carolina Panthers </label><br>
    <input type="radio" name="teamName" id="CIN" value="Cincinnati Bengals">
    <label for="CIN">Cincinnati Bengals </label><br>
    <input type="radio" name="teamName" id="CHI" value="Chicago Bears">
    <label for="CHI">Chicago Bears </label><br>
    <input type="radio" name="teamName" id="CLE" value="Cleveland Browns">
    <label for="CLE">Cleveland Browns </label><br>
    <input type="radio" name="teamName" id="DAL" value="Dallas Cowboys">
    <label for="DAL">Dallas Cowboys </label><br>
    <input type="radio" name="teamName" id="DEN" value="Denver Broncos">
    <label for="DEN">Denver Broncos </label><br>
    <input type="radio" name="teamName" id="DET" value="Detroit Lions">
    <label for="DET">Detroit Lions </label><br>
    <input type="radio" name="teamName" id="GB" value="Green Bay Packers">
    <label for="GB">Green Bay Packers </label><br>
    <input type="radio" name="teamName" id="HOU" value="Houston Texans">
    <label for="HOU">Houston Texans </label><br>
    <input type="radio" name="teamName" id="IND" value="Indianapolis Colts">
    <label for="IND">Indianapolis Colts </label><br>
    <input type="radio" name="teamName" id="JAG" value="Jacksonville Jaguars">
    <label for="JAG">Jacksonville Jaguars </label><br>
    <input type="radio" name="teamName" id="KC" value="Kansas City Chiefs">
    <label for="KC">Kansas City Chiefs </label><br>
    <input type="radio" name="teamName" id="LAC" value="Los Angeles Chargers">
    <label for="LAC">Los Angeles Chargers </label><br>
    <input type="radio" name="teamName" id="LAR" value="Los Angeles Rams">
    <label for="LAR">Los Angeles Rams </label><br>
    <input type="radio" name="teamName" id="MIA" value="Miami Dolphins">
    <label for="MIA">Miami Dolphins </label><br>
    <input type="radio" name="teamName" id="MIN" value="Minnesota Vikings">
    <label for="MIN">Minnesota Vikings </label><br>
    <input type="radio" name="teamName" id="NE" value="New England Patriots">
    <label for="NE">New England Patriots </label><br>
    <input type="radio" name="teamName" id="NO" value="New Orleans Saints">
    <label for="NO">New Orleans Saints </label><br>
    <input type="radio" name="teamName" id="NYJ" value="New York Jets">
    <label for="NYJ">New York Jets </label><br>
    <input type="radio" name="teamName" id="OAK" value="Las Vegas Raiders">
    <label for="OAK">Las Vegas Raiders </label><br>
    <input type="radio" name="teamName" id="PHI" value="Phladelphia Eagles">
    <label for="PHI">Phladelphia Eagles </label><br>
    <input type="radio" name="teamName" id="PIT" value="Pittsburgh Steelers">
    <label for="PIT">Pittsburgh Steelers </label><br>
    <input type="radio" name="teamName" id="SF" value="San Fransisco 49ers">
    <label for="SF">San Fransisco 49ers </label><br>
    <input type="radio" name="teamName" id="SEA" value="San Fransisco 49ers">
    <label for="SEA">Seattle Seahawks</label><br>
    <input type="radio" name="teamName" id="TB" value="Tampa Bay Buccanneers">
    <label for="TB">Tampa Bay Buccanneers</label><br>
    <input type="radio" name="teamName" id="TEN" value="Tennessee Titans">
    <label for="TEN">Tennessee Titans</label><br>
    <input type="radio" name="teamName" id="WAS" value="Washington Redskins">
    <label for="WAS">Washington Redskins</label><br>
    <input type="button" id="btn" value="Show Selected Value">
  </form>
</div>



<div id = "qbRound" style = "display:none">
    <h4> Quarterback Round </h4> <br>
<input type = "radio"  name = "qb" value = "qb1" onclick = "qbSelect1()"></input>
<label id = "qb1" class = "qbdisplay"></label><br>
<input type = "radio"  name = "qb" value = "qb2" onclick = "qbSelect2()"></input>
<label id = "qb2" class = "qbdisplay"></label><br>
<input type = "radio"  name = "qb" value = "qb3" onclick = "qbSelect3()"></input>
<label id = "qb3" class = "qbdisplay"></label><br>
</div>

<div id = "hbRound" style = "display:none">
<h4> Runningback Round </h4> <br>
<input type = "radio"  name = "hb" value = "hb1" onclick = "hbSelect1()"></input>
<label id = "hb1" class = "hbdisplay"></label><br>
<input type = "radio"  name = "hb" value = "hb2" onclick = "hbSelect2()"></input>
<label id = "hb2" class = "hbdisplay"></label><br>
<input type = "radio"  name = "hb" value = "hb3" onclick = "hbSelect3()"></input>
<label id = "hb3" class = "hbdisplay"></label><br>
</div>

Let me know what is wrong. Again, the problem originated after I added in localStorage commands, so I wonder if that is the problem.

Thanks!