jeudi 30 avril 2020

can not return a variable of type "uniform_int_distribution

this is my code :

#include <iostream>
#include <random>

std::random_device rd;
std::mt19937 mt(rd());

std::uniform_int_distribution<int> RN(int min,int max)
{
std::uniform_int_distribution<int> dist(min,max);
return dist(mt);
}

int main()
{
std::cout << RN(1,100) << std::endl;
return 0;
}

so i have a problem that I get an error when trying to return dist my question is : why is it not working and how to fix it ?




uniform_int_distribution giving the same number even when seeded with random_device [duplicate]

Straight forward, this is my simple example:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(0,100);

    std::cout << dist(mt) << std::endl;
    return 0;
}

Every time I run the program, it gives the same answer: 56

This code should output a random number each time, but it doesn't... why?




Return five rows of random DNA instead of just one

This is the code I have to create a string of DNA:

prepare dna_length(int) as
  with t1 as (
    select chr(65) as s 
      union select chr(67) 
      union select chr(71) 
      union select chr(84) )
, t2 as ( select s, row_number() over() as rn from t1)
, t3 as ( select generate_series(1,$1) as i, round(random() * 4 + 0.5) as rn )
, t4 as ( select t2.s from t2 join t3 on (t2.rn=t3.rn))
select array_to_string(array(select s from t4),'') as dna;

execute dna_length(20);

I am trying to figure out how to re-write this to give a table of 5 rows of strings of DNA of length 20 each, instead of just one row. This is for PostgreSQL.

I tried:

CREATE TABLE dna_table(g int, dna text);
INSERT INTO dna_table (1, execute dna_length(20));

But this does not seem to work. I am an absolute beginner. How to do this properly?




np.random.choices when I have a list of lists

I have a list of lists and I have to randomly choose one of them with weights.

I thought I could simply use np.random.choice but it returns an error since the argument is not a 1-D array. Of course, one way to solve this issue is to randomly choose an integer number and then select the list in the following way:

import numpy as np
all_lists=[[1,2],[3,4]]
weights=np.array([1.,3.])
prob=weights/np.sum(weights)
index=np.random.choice(range(len(all_lists)),p=prob)
selected_list=all_lists[index]
print selected_list

but is there a more immediate way, without wasting time selecting the index first?




What is the best way to create a random fair hash function that can be replicated?

The title probably sounds weird, but I'll explain what I mean.

Given k values, I want to map those to m buckets (m < k by at least an order of magnitude), such that each bucket contains either floor(k/m) or floor(k/m)+1 of the initial values.

Writing code to do that is very simple. The issue is, I want to be able to replicate the same distribution, by including something that makes the distribution reproducible in my code (something along the lines of a "seed"). Does anyone have any ideas how this can be done?

For the record, what I'm doing now in my Python code is selecting a random non-full hashbucket for every one of the k values, until all buckets contain floor(k/m) values. After this is done, I assign each of the values that I have left to a random bucket.




select m random numbers from a list whom items have different probabilities in python

I want to select m random numbers from a list whom items have different probabilities. How can I do this? For example I have this list:

list = [0,1,2,3,4,5,6]

and its items have these probabilities to be selected (shown below), respectively:

prob = [0.3,0.1,0.2,0.05,0.15,0.1,0.1]

So, 0 is more likely to be selected and then 2 and so on.

I want something like this code to select m random numbers from list depend on p:

random.choices(list, p = prob , k = m)

which p is an argument for getting probabilities and k is number of selected number.




Python3 beginner - coding problems [closed]

i am doing school course python basics, and yes, running into problems in the codes. I can't seem to figure out, how to find my way in the code and get it running smoothly. So here's my questions: 1.) The task is to create a lottery machine, which generates rows of random numbers between 1 - 40 (7 lottery numbers/row). I am not allowed to use random.sample, lottery code should ask from the user: how many rows do you want to play...and code should print out the amount rows with randomly generated lottery numbers (each row can only contain unique numbers, as in 1,5,16,39....not like 1,5,16,5,39,1,39....). I have managed to create some sort of code for this, actually many variations from it. Some codes generate unique numbers 5 rows, until list containing 1-40 numbers run out. Other codes copy the same randomly generated row...

So, what kind of code do I need to write to this?




Random sampling and assigning values to each sample set in Tableau

I have a tableau dashboard that provides tasks for auditing based on the date filter we choose. The total number of tasks that we may get for a given date would be around 700. We have 5 team members to do a total of 120 tasks per day (5*25 tasks).

I am trying to assign tasks to the 5 members by doing a random sample of the tasks and then assign 25 tasks each to 5 members.

Trying to implement something similar to rownumber(over() order by random) as proxy select case when proxy >=25 then 'set 1' when proxy >=50 then 'set 2' and so on.

Is that possible in Tableau




Sets of random numbers with no duplicates

I want to write a program that can make random seats at my school in our diner.

I know this much

import Foundation

var randomNumbers: [Int] = []

for _ in 0...5 {
    let randomInt = Int.random(in: 0...160)
    randomNumbers.append(randomInt)
}

print(randomNumbers)

This prints 6 numbers between 1 and 160. I want to do this lets say 4 times. How would you make it so you can't sit together with people who you sat with before




Error in my Random Math GUI, answer.get() is not working properly

I am trying to do A Math Quiz game, for kids. This consists in a GUI that shows the random math question and the user needs to answer and press the button to enter. But, there is an error if you run it. In the part of getting the answer that the User has input, it doesn't work. So, I have tried every possible way to make it work, but nothing has worked for me. I hope someone can solve my problem. And a bonus if you are feeling extra generous would be if you could add and make work what I have in brackets for when the user has ran out of tries and mistakes.

from tkinter import *
import random
import time
import os


mathWindow = Tk()
mathWindow.title("RandomMath - SLSinfinity")

data=[]
print("----- RandomMath ----- \nBy SLSinfinity in 2020")

def file():

    file = open("RandomMathGUIScoreData.txt","a+")
    file.write(str(data))
    file.write("\n")
    file.close()
    f = open("RandomMathGUIScoreData.txt","r")
    print("\nCongratulations on your score!")


marks = 0
runs = 20
counter = 3  


def ifelse():

    if result == maths:
        string_to_display = "Well Done you got it Correct ✓"
        marks = marks + 1


    else:
        string_to_display = "Oh, you got it incorrect ✕"
        counter = counter - 1

    label2 = Label(mathWindow)
    label2["text"] = string_to_display
    label2.grid(row=1, column=1)

def something():
    result == answer.get()
    ifelse()


print("\nREMEMBER: (*) this is equal to this (x) multiply")
def Questions():
    operator = ["+","*"]
    operation = random.choice(operator)
    num1 = random.randint(0,10)
    num2 = random.randint(0,10)
    maths = str(num1) + operation + str(num2)
    question = Label(mathWindow, text=str(num1) + " " + operation + " " + str(num2) + " = ")

    answer = Entry(mathWindow)
    answer.grid(row=0, column=1)

    button1 = Button(mathWindow, text="Click here to submit answer", command = something)



    #.grid
    question.grid(row=0, column=0)

    button1.grid(row=1, column=0)


while runs > 0 and counter > 0:
    Questions()

    runs = runs - 1

#   elif counter == 0 or runs == 0:
#        repeat = input("You have zero chances or runs left. Do you want to continue? y/n : ")
#        if repeat == "y":
#            data.append(name)
#            data.append(marks)
#            file()
#            print(str(name) + " scored: " + str(marks))
#            marks = 0
#            counter = 3
#            runs=20
#            True
#        else:
#            False


 #  button2 = Button(mathWindow, text="Next", command = #)

   #button2.grid(row=1, column=2)

mathWindow.mainloop()



Ensure that all 2**N combinations are generated in M random outputs of N booleans

In this example below M = 10 and N = 2, and since M is considerably larger than N, the probability is that every possible combination of N booleans, (True, True), (True False), (False, True), (False, False) in this example, will be generated among the M outputs at least once, as has occurred below.

for _ in range(10):
...     choice1 = np.random.choice((True, False))
...     choice2 = np.random.choice((True, False))
...     print(choice1, choice2)
...     
False False
False False
True False
True False
True True
False True
True True
True True
True False
False False

But it isn't guaranteed. There is a low probability of getting 10 X (False, False) or alternatively 10 X (True, True), or perhaps a mix where one particular pair, say (False, True), never appears.

In 'real life' the print is replaced by a yield statement, and choice1 and choice2 are accompanied by several other randomly generated numeric variables.

How could I easily change the generation of choice1 and choice2 to make sure they always cover all of the 4 possibilities, while still keeping it (mostly) random, without just adding 4 extra non-random cases to force them to occur?

I feel as if the selection without replacement option could be exploited, but I can't think how to incorporate this.




Numpy random integer generator not covering full interval?

When generating random integers over (almost) the full interval allowed by int64, the generated integers seem to be generated on a smaller range. I'm using the following code:

import numpy
def randGenerationTest(n_gens=100000):
    min_int = 2**63
    max_int = 0
    for _ in range(n_gens) :
        randMatrix = numpy.random.randint(low=1, high = 2**63, size=(1000,1000))
        a = randMatrix.min()
        b = randMatrix.max()
        if a < min_int:
            min_int = a
        if b > max_int :
            max_int = b
    return min_int, max_int

Which is returning the following:

randomGenerationTest()
>>> (146746577, 9223372036832037133)

I agree that [1, 146746577] represents just a tiny fraction of the full range I'm trying to get, but in 1e11 random integers generated in the range of [1,2^63), I should have come just once near to my boundaries? Is this expected behavior when using too large intervals? Or is it cause as a human I can not grasp how enormous these intervals are and that I am already "near enough"?

By the way, this was just to know if the Seed can be randomly set from 1 to 1e63, as it is possible to set it manually to any of those values.




mercredi 29 avril 2020

I want to create Random Number System with Swift

I want to create a system in swift where with the following numbers: 19, 15, 12, 7 and 5 randomly choose only 2 numbers and are separated by a number and maximum by three numbers.




Generating Random Number of Characters

I have to create a program that reads in the number of character to be printed, and it will print random chars (a-z, A-Z, 0-9 and characters like !, &, $, etc). And the first character to be printed cannot be a number (0-9).

So an example output would be like:

Length of Variable? 20

a5fTnO$akP_a12BahsiO

This is what I have so far, but I'm stuck and don't know what else I can do to make it work. I'm not sure whether I'm on the right track either.

Would it be easier for me to create a string of the characters and then just get random characters from the string (if that's possible)?


import java.util.Scanner;

public class VariableNameRandomGen{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        System.out.print("Length of the variable? ");
        int num = sc.nextInt();

        final int noOfChars = num;
        final int charsPerLine = num;

        for(int i = 0; i < noOfChars; i++){
            char ch = getRandomCharacter();

            if((i+i) % charsPerLine == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }

    public static char getRandomCharacter(char ch1, char 2){
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    public static char getRandomUpperCaseLetter(){
        return getRandomCharacter('A', 'Z');

    }

    public static char getRandomDigitCharacter(){
        return getRandomCharacter('0', '9');
    }
}



Adding (non-repeating) Random Numbers to Each Line of .txt File

I'm creating a .txt file that has four soldiers on a team ranking each other in order of merit. Soldiers do not rank themselves.

I have the following code:

import itertools

# create a list of 4 soldiers
numSoldiers=4
soldiers = []
for i in range(1,numSoldiers+1):
    soldiers.append('soldier'+str(i))

# create list of all permutations of 2 soldiers
perms = list(itertools.permutations(soldiers, 2))

# list of possible rankings (soldier does not rank himself/herself)
possRanks = list(range(1,len(soldiers)))

# create the edgelist .txt file with randomized rankings
open('peerRankingsEdgelist.txt', 'w').close() #delete contents of .txt file at the start

file = open('peerRankingsEdgelist.txt', 'w')

for i in perms:
    file.write(i[0] + ', ' + i[1] + '\n')

file.close() #close file

which produces the following output in a .txt file:

soldier1, soldier2
soldier1, soldier3
soldier1, soldier4
soldier2, soldier1
soldier2, soldier3
soldier2, soldier4
soldier3, soldier1
soldier3, soldier2
soldier3, soldier4
soldier4, soldier1
soldier4, soldier2
soldier4, soldier3

For each set of three lines (the sets of lines that start with the same soldier), I want to add a randomized ranking that comes from possRanks, where possRanks = [1, 2, 3]. The problem is that I can't completely randomize it because then the rankings might repeat. For example, soldier1 might rank both soldier2 and soldier3 with a ranking of 1, which I cannot have.

A correct example output would be the following:

soldier1, soldier2, 3
soldier1, soldier3, 1
soldier1, soldier4, 2
soldier2, soldier1, 1
soldier2, soldier3, 2
soldier2, soldier4, 3
soldier3, soldier1, 2
soldier3, soldier2, 1
soldier3, soldier4, 3
soldier4, soldier1, 1
soldier4, soldier2, 2
soldier4, soldier3, 3

Here, soldier1 ranks soldier2 with a value of 3, soldier3 with a value of 1, and soldier4 with a value of 2.




Irregular time-series analysis

I'm trying to find patterns in a game event that happens randomly over time. The data looks like this:

ind  start-time        end-time          starting-score     closing-score
1    2020-01-02-13:00  2020-01-02-13:50  10                 17
2    2020-01-04-07:00  2020-01-04-09:30  17                 15
3    2020-01-07-23:00  2020-01-08-01:10  15                 34
...

As you can see, the event (playing the game) happens randomly, its duration is random, and results in changing of the score.

Now, the answers I'm looking for to do my analysis include:

  • What is the best time of the day to play the game?
  • How long should you play to get the best results?
  • Are there any patterns? e.g. if you earn points twice in a row are you likely to lose points in the following round?
  • Is it better to play the game everyday? what is the optimal rest time between the sessions, etc.

There are so many interesting questions, but I'm still not sure how to target the problem.

I thought maybe a feature-based analysis could be a good start, i.e. binning the start/end times into different parts f the day (e.g. morning, evening), then I will have a categorical feature, same can be done for the length of the game (e.g. short, long). The first 2 questions might probably be answered using a regression (or logistic regression) model on the outcome points, but I guess I need some sort of time-series specific analysis to be able to provide better insight and I'm not sure what methods I need.

I'm looking for a solution in Python and I have seen packages like traces. I guess the main problem I have is that most of libraries are designed for regular time-series and those that support irregular ones are focused on how to deal with the missing data, while in this problem, nothing is missing, it's just the nature of the data that is irregular.




We need help to cache 60sec information in laravel

we need your help to cache information in laravel. I want cache random information 60 seconds and after 60 seconds when I click on the same value url again the url information would be new again.

Example:

url - domain.com/cats/2 <br>
It's take random from cats.txt file:<br>

Cats 1 - Richy,
Cats 2 - Tom,
Cats 3 - Luka <br>

And i want this information cache 60 seconds, after 60 second I again click url domain.com/cats/2 and information random from cats.txt new, exampe:

Cats 1 = Justin,
Cats 2 = Edvinas,
Cats 3 = Dzho.

Controller: https://pastebin.com/C4eLAYfw

Route: https://pastebin.com/3PuaL82L




Make a Psudo Random Number Generator Based on Many Inputs Javascript

The current project that I am working on involves a multidimensional world, which can have many more than just 3 dimensions, and need to get values for each position of that world. I already have a good Pseudo Random Number Generator (PRNG) that takes a seed and a single value. What I need is to have a function that can use as many inputs as are provided, and return a value based on those positions. The PRNG also should not have to rely on its previous values to determine it's next state, and should work (as close as possible to) the same on any browser or system.

My current PRNG, works very well for 1 input (xxHash):

function random(seed, x) {
    /* mix around the bits in x: */
    x = x * 3266489917 + 374761393;
    x = (x << 17) | (x >> 15);

    /* mix around the bits in y and mix those into x: */
    x += seed * 3266489917;

    /* Give x a good stir: */
    x *= 668265263;
    x ^= x >> 15;
    x *= 2246822519;
    x ^= x >> 13;
    x *= 3266489917;
    x ^= x >> 16;

    /* trim the result and scale it to a float in [0,1): */
    return (x & 0x00ffffff) * (1 / 0x1000000);
}

I tried adding more parameters and mixing them up, but that didn't go so well (Below):

function rand(seed, ...prams){
    let x = prams[0] + seed;

    x = x * 3266489917 + 374761393;
    x = (x << 17) | (x >> 15);

    /* mix around the bits in y and mix those into x: */
    for(let i =1; i< prams.length; i++){
        prams[i] *= seed;
        x *= prams[i] * 3266489917
    }

    /* Give x a good stir: */
    x *= 668265263;
    x ^= x >> 15;
    x *= 2246822519;
    x ^= x >> 13;
    x *= 3266489917;
    x ^= x >> 16;



    /* trim the result and scale it to a float in [0,1): */

    let val = ((x & 0x00ffffff) * (1.0 / 0x1000000))
     return val;
}

This one didn't return any errors, but if the inputs were in a different order, the value was the same, which means that rand(seed, 5, 1, 1) === rand(seed, 1, 5, 1) === rand(seed, 1, 1, 5) , Which is not great behavior.

I need a function random(seed, ...position) that will generate a pseudo random number between 0 and 1 that is affected by both the order and all the values in the position array.




PHP guesser game [duplicate]

Im trying to make a php guessing game where when you enter a number under 10 it will show a for loop of 100 random numbers 1 - 10 and then it will output the number of times it guesses the number.

I have the loop working but its not showing the amount of time it guesses the number.

<?php

$counter = 0;

$num = $_POST["num"];

for ($i=0; $i <=100;$i++) { 
    $randomNum = rand(1,10);

    if ($randomNum == $num) {
        echo "$randomNum ";
        $counter++;
    }

    else
    {
        echo"$randomNum ";

    }
}

echo"<h2> there are $counter</h2>";




?>
<!DOCTYPE html>
<html>
<head>
</head>

</body>
</html>
    <h1>Enter a Number and see if you can guess it</h1>
     <body>
    <form action="finalresults.php" method="post">
        <h2>Enter a number under ten</h2>
      <input type="text" name="num">  
         <input type="submit" value="Now I will guess">  
        
    </form>
    
    </body>
    
    
</html>
Below is what I want the output to be

I want the output to look like the image attached




password generation python with condition

I have the below password generator script based on characters, numbers and some special chars which are ultimately generating the combination of password based on length provided. This script works as intended.

Code outlined below:

$ cat passwd_gen.py
#!/usr/local/bin/python3.6
import random

def pass_Gen(length):
    passwd = str()
    chars = "!@#$%~" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789"
    for pas in range(length):
        passwd = passwd + random.choice(chars)
    print(passwd)

if __name__ == "__main__":
    pass_Gen(10)

Resulted Output:

$ ./passwd_gen.py
@1wUErxil#

Desired Outcome:

I am looking forward the Initial Character of password should be Starting with uppercase Char and Special Char rest all is good.

@E1UErxil#



C# Random generates different value with the same seed

I am writing a generator of maths problems for my coursework project and I encountered an issue that I can bypass in an ugly way, but I would like to understand why is it happening.

I have a constructor that takes an integer and assigns it to seed inside of the Random(seed). Then I go on to generate all of the values using that random.

There are two possible modes for generating. I either generate a block of 100 problems and then randomly pick a couple among those 100 and display them in an HTML document. It works fine. However right after generating a block, if I try to generate those problems using its number, my Random gives me different values for the same variables.

However, when I retry to handpick a problem with that number, it works fine on a second attempt giving me the problem that I wanted. Same thing when I run the program and go straight to hand picking a particular problem.

Here is the constructor

readonly Random rng = new Random(seed);
    public Level2(int seedVal)
    {
        seed = seedVal;
        Key = GenerateKey(seedVal)+"2";
        GenerateXval(seedVal);
        GenerateValuesGeneral();
        this.htmlFormula = GenerateProblem(seedVal % 4);
    }

Here is the part of the code that generates a block of problems

private void GenerateTasksLevel2(int n)
    {
        List<string> problems = new List<string>();
        for (int i = 0; i < n; i++)
        {
            Level2 task = new Level2(i);
            problems.Add(task.htmlFormula);
        }
        Problems = problems;
    }



How to solve OverflowError when generating same random numbers between R and Python using SyncRNG

I am trying to reproduce R codes in Python and I have to generate same random numbers in both languages. I know that using the same seed is not enough to get same random numbers and reading one of the answers on this platform regarding this topic I have discovered that there exists: SyncRNG library, which generates same random numbers between R and Python. Everything looks fine as long as I have discovered that on Python 3.7.3 I can generate via SyncRNG just one number because as soon as you iterate the procedure, for instance, with a for loop you get this error:

OverflowError: Python int too large to convert to C long.

As I was mentioning:

>>> from SyncRNG import SyncRNG
>>> s = SyncRNG(seed=123)
>>> r = s.rand()
>>> r
0.016173338983207965

and as we can see it works. The method ".rand()" generates random numbers between zero and one. But if I try to iterate:

>>> from SyncRNG import SyncRNG
>>> s = SyncRNG(seed=123)
>>> b = []
>>> for i in range(5):
        temp = s.rand()
        b.append(temp)

and I get this:

OverflowError: Python int too large to convert to C long

So, I humbly ask if someone is able to solve this problem. If I lost old answers about this topic I'm sorry, please link them in the answer section. Thank you!




How do I use input in def (Python)

I'm a newbie when it comes to coding. I would highly appreciate it if you can help me solving my problem regards to coding. I tried to use input in my def but doesn't work.

import random

def estimate_pi(n):
    num_point_circle = 0
    num_point_total = 0
    for _ in range(n):
        x = random.uniform(0,1)
        y = random.uniform(0,1)
        distance = x**2 + y**2
        if distance <= 1:
            num_point_circle += 1
        num_point_total += 1
    return 4 * num_point_circle/num_point_total
n = input("Enter A Random Number")
result = estimate_pi(n)
print (result)



I want to stop the loop each time it prints a value

I use this code to get distinct random value in colum A of worksheet but this code gives me all the values at a time. i want to get the value one by one each time after clicking a worksheet button / active x button.

for example on first click the cell A1 should be filled with first random value and then for each click A2, A3, A4 AND A5 Cells shoudl be filled. Once all the celles are filled, on click of the button nothing shoudl happen.

Option Explicit

Sub RAND1()
Dim myStart As Long
Dim myEnd As Long
Dim i As Long
Dim a()
Dim sh As Worksheet

    Set sh = Sheet1
    myStart = 1
    myEnd = 5

ReDim a(0 To myEnd - myStart)

    With CreateObject("System.Collections.SortedList")

        Randomize

            For i = myStart To myEnd
            .Item(Rnd) = i
            Next i

                For i = 0 To .Count - 1
                a(i) = .GetByIndex(i)
                Next

    End With

sh.Range("a1").Resize(UBound(a) + 1).Value = Application.Transpose(a)

End Sub



mardi 28 avril 2020

Numpy array with the given values and the sum equal 1

I want to create random np.array with values including only [0.05, 0.1, 0.15, ... 0.9, 0.95, 1] with the sum of the values = 1

I know how to create a random array, for example, of 5 elements, so that the sum is equal to 1:

array = np.random.random(5)
array /= np.sum(array)

But how can I make that the values in this array are only from [0.05, 0.1, 0.15, ... 0.9, 0.95, 1]?




Writing a XORshift128 pRNG with Signed Integers

In the programming language I'm using (GML) all numbers are confined to signed int64s (or float64s). How would I implement this XORshift128+ pRNG (currently coded in C) with that sort of limitation? I would also accept a higher bit count if the programming would be easier.

static uint32_t s[4] = { 0x8764000b, 0xf542d2d3, 0x6fa035c3, 0x77f2db5b };

static inline uint32_t rotl(const uint32_t x, int k) {
    return (x << k) | (x >> (32 - k));
}

uint32_t next(void) {
    const uint32_t result = s[0] + s[3];

    const uint32_t t = s[1] << 9;

    s[2] ^= s[0];
    s[3] ^= s[1];
    s[1] ^= s[2];
    s[0] ^= s[3];

    s[2] ^= t;

    s[3] = rotl(s[3], 11);

    return result;
}



I want to get the multiplication of two prime numbers of the N digits I have entered

I am python beginner.

I want to get the multiplication of two prime numbers of the N digits I have entered in python.

I even implemented two prime numbers and multiplying them.

For example, if I enter 2, the multiplication of the 2-digit prime number should be output.(If you enter 2, it consists of the product of two prime numbers, such as 3 * 11 or 5 * 2 and etc. The result of the product is two digits.

If you enter 3, it consists of the product of two prime numbers, 97 * 5 or 83 * 7 and etc. Here, the result of the product is three digits.)

And only one result of multiplication should be output at random.

I don't know what to do next.

My code is

import random
nums = []
for num in range(10,100):  
   if num > 1:  
       for i in range(2, num):  
           if (num % i) == 0:  
               break  
       else:
           nums.append(num)
prime = random.sample(nums, 2)
print(prime)
N = prime[0] * prime[1]
print('multiply with the two prime numbers:', N)

And 'range' is a randomly set range in "for num in range(10,100)"

for num in range(10,100)"




How to change this program to use random.shuffle instead of random.sample?

I was wondering if there was anyone who was willing to help me out, when it came to this program. Backstory is to create a card game that when you draw 6 random cards, if one card is an ace, the player wins a dollar if not they lose a dollar. This goes on till the player either doubles their money or loses it all. The game is ran 1000 times, and starts with an initial of 10 dollars. Here is my code:

import random

faceValues = ['ace', '2', '3', '4', '5', '6',
              '7', '8', '9', '10', 'jack',
              'queen', 'king']
suits = ['clubs', 'diamonds', 'hearts',
         'spades']
def shuffledDeck():
    deck = []
    for faceValue in faceValues:
        for suit in suits:
            deck.append(faceValue + ' of ' + suit)
    random.shuffle(deck)
    return deck

def faceValueOf(card):
    return card.split()[0]

def suitOf(card):
    return card.split()[2]

d = shuffledDeck()

def game(initial):
    counts = 0
    bankroll = initial
    while 0 < bankroll < 2*initial:
        ace = 0
        table = random.sample(shuffledDeck(),6)
        counts += 1
        for cards in table:
            if faceValueOf (cards) == 'ace':
                ace += 1
        if ace >= 1:
            bankroll += 1
        else:
            bankroll -= 1

    return counts


initial = float(input('Enter initials: '))
totalcounts = 0
for x in range(1000):
    totalcounts += game(initial)

print('Average number of rounds: ', totalcounts/1000)

I was wondering how I would be able to alter this program, so instead of using random.sample, I could use random.shuffle. I tried many ways in changing this program, but whenever I do, my end results are not the same. I'm just trying to change the section where I have to draw cards. When running this program starting at an initial 10, the answer is roundabout 45 to 50 in terms of rounds played. Edit: Trying to keep the program relatively the same, only want to change what I really need to.




Random Number guessing game with 2 option menu

I am writing a random number generator that prompts the user for a guess. I want the program to only terminate when option 2 is chosen. So far all of my outputs are correct but when they get the guess right, it just jumps straight into a new game. It will not give the desired output. I am sure I am just overlooking a small detail in the while loop but I have tried what I am familiar with. Any help would be great. Below is what I have so far:

'''

# Import the Random function.
import random

# Create variable to keep track of guesses
count = 0

# Define menu for ease of reference

menu = """
1. Play Game
2. Exit
"""

choice = None

# Set the Loop

while (choice != 2):
    print (menu)
    choice = int(input("Would you like to play a game?"))

    if (choice == 1):
        print ("Guess a number between 1 & 100:")
        x = random.randint (1, 100)
        guess = int(input())

        while (guess != x):
            if (guess < x):
                guess = int(input("Your guess is too low, try again:"))
                count = count+1

            elif (guess > x):
                guess = int(input("Your guess is too high, try again:"))
                count = count+1

            elif (guess == x):
                print ("Congratulations, you guessed the number in", count, "attempts!")



    else:
        exit

#Pseudocode for the above program

# Ask user if they want to play the guessing game
# Randomly generate a number
# Ask user to guess and give hints (too low, too high)
# Generate a new random number each game
# Only quit when user selects to exit

'''




eliminating repeated random numbers

I need to get the numbers 0-11 in a random order and make sure each number is only gotten once. It is still sending same numbers into my Line2 class though. How do I make sure that the int variable lineChoice is completely different every time? My problem is the if/else is not properly making sure that I don't send an already selected lineChoice to my Line2 class.

for(int i = 0; i < 12; i++){
        //get a random line choice 0-11
        lineChoice = (int)(Math.random() * 11); //0-11;
        //if that number was already chosen
        //get a new random number and add it to the array
        if(randomNumbers.contains(lineChoice)){
            lineChoice = (int)(Math.random() * 11); //0-11;
            randomNumbers.add(lineChoice);
        }else{
            //if not already in array, add to array
            randomNumbers.add(lineChoice);
        } 
        //make a Line based on the random lineChoice number
        line = new Line2(lineChoice);
        //add the line to the string poem
        poem += "\n" + line + "\n\n\n";                        
    } 



explanation of random motion of multiple pendulums

is there an explanation of random motion of multiple pendulums , it seems to be 'orderly chaos'. example : https://www.youtube.com/watch?v=1M8ciWSgc_k




C#: Index Outside the Bounds of the Array - using count

I have a series of names. I want to pick a random name, then capitalize the first character and use it as an initial, converted to a string.

For example, here is the list of names:

List<string> Name1 = new List<string>() {
    "Aaron","Aron","Ron","Ronnie","Ronny","Abel","Abe","Abie","Abner","Abbie","Abraham","Abram","Abe","Abie","Bram","Adam","Addie","Addy","Ade","Adelbert","Adalbert","Ade","Bert","Bertie","Del","Adrian","Ade","Alan","Allan","Allen","Albert","Bert","Bertie","Alexander","Alex","Alec","Aleck","Lex","Sandy","Sander","Alfred","Alf","Alfie","Fred","Freddie","Freddy","Algernon","Algie","Algy","Alger","Alister","Allister","Alistair","Alastair","Alaster","Alonso","Alonzo","Lon","Lonnie","Lonny","Alphonso","Alfonso","Alf","Alfie","Alonso","Lon","Alva","Alvah","Alvan","Alvin","Alwin","Alwyn","Vin","Vinny","Win","Ambrose","Ambie","Brose","Amos","Andrew","Andy","Drew","Angus","Gus","Anselm","Ansel","Anse","Anthony","Antony","Anton","Tony","Archibald","Arch","Archie","Baldie","Arnold","Arnie","Arthur","Art","Artie","Augustus","August","Augie","Gus","Gussy","Gust","Gustus","Augustine","Augustin","Augie","Austin","Gus","Gussy","Gust","Austin","Avery","Avy","Baldwin","Baldie","Win","Barrett","Barry","Barrie","Bartholomew","Bart","Barty","Bartlett","Bartley","Bat","Batty","Basil","Baz","Basie","Benedict","Ben","Bennie","Benny","Benjamin","Ben","Bennie","Benny","Benjy","Benjie","Bennet","Bennett","Ben","Bennie","Benny","Bernard","Barnard","Bernie","Berney","Barney","Barnie","Bert","Bertie","Berthold","Bert","Bertie","Bertram","Bertrand","Bert","Bertie","Bill","Billy","Billie","Blair","Blake","Boris","Bradford","Brad","Ford","Bradley","Brad","Brady","Brandon","Branden","Brand","Brandy","Brenton","Brent","Bret","Brett","Brian","Bryan","Bryant","Broderick","Brodie","Brody","Brady","Rick","Ricky","Bruce","Bruno","Burton","Burt","Byron","Ron","Ronnie","Ronny","Caleb","Cal","Calvin","Cal","Vin","Vinny","Cameron","Cam","Ron","Ronny","Carey","Cary","Carry","Carl","Karl","Carol","Carrol","Carroll","Casey","Kasey","Caspar","Casper","Cas","Cass","Cassius","Cas","Cass","Cecil","Cis","Cedric","Ced","Rick","Ricky","Charles","Charlie","Charley","Chuck","Chad","Chas","Chester","Chet","Christian","Chris","Christy","Kit","Christopher","Kristopher","Chris","Kris","Cris","Christy","Kit","Kester","Kristof","Toph","Topher","Clarence","Clare","Clair","Clare","Clair","Clark","Clarke","Claude","Claud","Clayton","Clay","Clement","Clem","Clifford","Cliff","Ford","Clinton","Clint","Clive","Clyde","Cody","Colin","Collin","Cole","Conrad","Con","Connie","Conny","Corey","Cory","Cornelius","Connie","Conny","Corny","Corney","Cory","Craig","Curtis","Curt","Cyril","Cyrus","Dale","Daniel","Dan","Danny","Darrell","Darrel","Darryl","Daryl","Darry","David","Dave","Davey","Davie","Davy","Dean","Deane","Delbert","Del","Bert","Bertie","Dennis","Denis","Den","Denny","Derek","Derrick","Derry","Rick","Ricky","Desmond","Des","Dexter","Dex","Dominic","Dominick","Domenic","Domenick","Dom","Nick","Nicky","Don","Donnie","Donny","Donald","Don","Donnie","Donny","Donovan","Don","Donnie","Donny","Dorian","Douglas","Douglass","Doug","Doyle","Drew","Duane","Dwayne","Dudley","Dud","Duddy","Duke","Duncan","Dunny","Dunk","Dustin","Dusty","Dwight","Dylan","Dillon","Earl","Earle","Edgar","Eddie","Eddy","Ned","Edmund","Edmond","Eddie","Eddy","Ned","Ted","Edward","Eddie","Eddy","Ned","Ted","Teddy","Edwin","Eddie","Eddy","Ned","Egbert","Bert","Bertie","Elbert","Bert","Bertie","Eldred","Elijah","Elias","Eli","Lige","Elliot","Elliott","Ellis","Elmer","Elton","Alton","","Elvin","Elwin","Elwyn","Vin","Vinny","Win","Elvis","Elwood","Woody","Emery","Emmery","Emory","Emil","Emile","Emmanuel","Emanuel","Immanuel","Manuel","Manny","Mannie","Emmet","Emmett","Eric","Erik","Erick","Rick","Ricky","Ernest","Earnest","Ernie","Errol","Ervin","Erwin","Irvin","Irvine","Irving","Irwin","Erv","Vin","Win","Ethan","Eugene","Gene","Eustace","Stacy","Stacey","Evan","Everard","Everett","Fabian","Fabe","Fab","Felix","Lix","Ferdinand","Ferdie","Fred","Freddie","Fergus","Ferguson","Fergie","Floyd","Floy","Ford","Francis","Frank","Frankie","Franky","Fran","Franklin","Franklyn","Frank","Frankie","Franky","Frederick","Frederic","Fredrick","Fredric","Fred","Freddie","Freddy","Rick","Ricky","Fred","Freddie","Gabriel","Gabe","Gabby","Garrett","Garret","Gary","GarryGeoffrey","Jeffrey","Jeffery","Jeff","George","Georgie","Geordie","Gerald","Gerard","Gerry","Jerry","Gilbert","Gil","Bert","Glenn","Glen","Gordon","Gordy","Don","Graham","Grant","Gregory","Gregor","Greg","Gregg","Griffith","Griffin","Griff","Guy","Harold","Hal","Harry","Harris","Harrison","Harry","Harvey","Harve","Hector","Henry","Harry","Hank","Hal","Herbert","Herb","Bert","Bertie","Herman","Manny","Mannie","Hilary","Hillary","Hill","Hillie","Hilly","Homer","Horace","Horatio","Howard","Howie","Hubert","Hugh","Bert","Bertie","Hube","Hugh","Hughie","Hugo","Humphrey","Humphry","Humph","Ian","Ignatius","Iggy","Nate","Immanuel","Manny","Mannie","Irvin","Irvine","Irving","Irwin","Isaac","Isaak","Ike","Isidore","Isidor","Isadore","Isador","Izzy","Ivor","Jack","Jackie","Jacky","Jacob","Jake","Jay","James","Jim","Jimmy","Jimmie","Jamie","Jem","Jared","Jerry","Jarvis","Jervis","Jerry","Jason","Jay","Jasper","Jay","Jefferson","Jeff","Jeffrey","Jeffery","Geoffrey","Jeff","Jeremy","Jeremiah","Jerry","Jerome","Jerry","Jesse","Jess","Jessie","Jessy","Joel","Joe","John","Jack","Jackie","Jacky","Johnny","Jonathan","Jon","Jonny","Joseph","Joe","Joey","Jos","Jody","Joshua","Josh","Judson","Jud","Sonny","Julian","Julius","Jule","Jules","Justin","Jus","Just","Karl","Carl","Keith","Kelly","Kelley","Kelvin","Kel","Kelly","Kendall","Ken","Kenny","Kendrick","Ken","Kenny","Rick","Ricky","Kenneth","Ken","Kenny","Kent","Ken","Kenny","Kevin","Kev","Kirk","Kristopher","Kristofer","Kris","Kit","Kester","Kurt","Curt","Kyle","Lambert","Bert","Lamont","Monty","Monte","Lancelot","Launcelot","Lance","Laurence","Lawrence","Lorence","Lorenzo","Larry","Lars","Laurie","Lawrie","Loren","Lauren","Lee","Leigh","Leo","Leon","Lee","Leonard","Leo","Leon","Len","Lenny","Lennie","Leopold","Leo","Poldie","Leroy","Leeroy","Lee","Roy","Leslie","Lesley","Les","Lester","Les","Lewis","Lew","Lewie","Lincoln","Lin","Linc","Lynn","Lindon","Lyndon","Lin","Lynn","Lindsay","Lindsey","Lin","Lynn","Linus","Lionel","Leo","Leon","Llewellyn","Llew","Lyn","Lloyd","Loyd","Loyde","Floyd","Loy","Floy","Logan","Lonnie","Lonny","Louis","Lou","Louie","Lowell","Lovell","Lucian","Lucius","Luke","Luke","Lucas","Luke","Luther","Loot","Luth","Lyle","Lyall","Lynn","Malcolm","Mal","Malc","Mac","Manuel","Manny","Mannie","Marion","Mark","Marc","Marcus","Mark","Marc","Marshall","Marshal","Martin","Mart","Marty","Marvin","Mervin","Marv","Merv","Matthew","Matt","Mat","Matty","Mattie","Matthias","Matt","Mat","Matty","Mattie","Maurice","Morris","Morry","Morey","Moe","Maximilian","Max","Maxwell","Max","Maynard","Melvin","Mel","Merlin","Merle","Merrill","Merril","Merill","Michael","Mike","Mikey","Mick","Mickey","Micky","Miles","Myles","Milo","Milo","Milton","Milt","Mitchell","Mitch","Monroe","Munroe","Montague","Monty","Monte","Montgomery","Monty","Monte","Morgan","Mortimer","Mort","Morty","Morton","Mort","Morty","Moses","Moe","Mose","Moss","Murray","Murry","Nathan","Nathaniel","Nat","Nate","Natty","Neal","Neil","Nelson","Nel","Nell","Nels","Nevill","Nevil","Nevile","Neville","Nev","Newton","Newt","Nicholas","Nicolas","Nick","Nicky","Nicol","Cole","Colin","Nigel","Nige","Noah","Noel","Nowell","Norbert","Bert","Norris","Nor","Norrie","Norman","Norm","Normie","Nor","Norrie","Norton","Nort","Oliver","Ollie","Noll","Nollie","Nolly","Orson","Orville","Orv","Ollie","Osbert","Ossy","Ozzie","Ozzy","Bert","Osborn","Osborne","Ossy","Ozzie","Ozzy","Oscar","Ossy","Osmond","Osmund","Ossy","Ozzie","Ozzy","Oswald","Oswold","Ossy","Ozzie","Ozzy","Otis","Owen","Patrick","Pat","Paddy","Patsy","Paul","Pauly","Percival","Perceval","Percy","Perce","Perry","Peter","Pete","Petie","Petey","Philip","Phillip","Phil","Pip","Preston","Quentin","Quintin","Quenton","Quinton","Quinn","Quincy","Quincey","Quinn","Ralph","Raff","Rafe","Ralphy","Randall","Randal","Rand","Randy","Randolph","Rand","Randy","Dolph","Raphael","Rafael","Raff","Rafe","Raymond","Raymund","Ray","Reginald","Reg","Reggie","Renny","Rex","Rene","Reuben","Ruben","Rubin","Rube","Ruby","Reynold","Ray","Richard","Dick","Rick","Ricky","Rich","Richie","Rick","Ricky","Robert","Bob","Bobbie","Bobby","Dob","Rob","Robbie","Robby","Robin","Bert","Roderic","Roderick","Rod","Roddy","Rick","Ricky","Rodney","Rod","Roddy","Roger","Rodger","Rod","Roddy","Rodge","Roge","Roland","Rowland","Rolly","Roly","Rowly","Orlando","Rolph","Rolf","Rolfe","Roman","Rom","Romy","Ronald","Ron","Ronnie","Ronny","Ron","Ronnie","Ronny","Roscoe","Ross","Ross","Roy","Rudolph","Rudolf","Rudy","Rolf","Rolph","Dolph","Dolf","Rufus","Rufe","Rupert","Russell","Russel","Russ","Ryan","Samson","Sampson","Sam","Sammy","Samuel","Sam","Sammy","Sanford","Sandy","Ford","Saul","Scott","Scotty","Sean","Shaun","Shawn","Shane","Sebastian","Seb","Bass","Serge","Seth","Seymour","Morey","Shannon","Shanon","Sheldon","Shelly","Shel","Don","Shelley","Shelly","Shellie","Shel","Sherman","Shelton","Shelly","Shel","Tony","Sidney","Sydney","Sid","Syd","Silas","","Silvester","Sylvester","Syl","Vester","Simeon","Sim","Simie","Simmy","Simon","","Sim","Simie","Simmy","Solomon","Sol","Solly","Sal","Sonny","Son","Spencer","Stacy","Stacey","Stanley","Stan","Stephen","Steven","Stephan","Steffan","Stefan","Steve","Stevie","Steph","Steff","Stef","Stuart","Stewart","Stu","Stew","Terence","Terrence","Terrance","Terry","Thaddeus","Thadeus","Tad","Thad","Theodore","Theodor","Ted","Teddy","Theo","Terry","Thomas","Tom","Tommy","Timothy","Tim","Timmy","Tobias","Toby","Tobi","Tobie","Todd","Tony","Tracy","Tracey","Travis","Trav","Trenton","Trent","Trevor","Trev","Tristram","Tristam","Tristan","Tris","Troy","Tyler","Tyrone","Tyron","Ulysses","Uly","Uli","Lyss","Uriah","Urias","Uri","Uria","Valentine","Valentin","Val","Valerian","Valerius","Val","Van","Vance","Van","Vaughan","Vaughn","Vernon","Vern","Verne","Victor","Vic","Vick","Vincent","Vince","Vin","Vinny","Virgil","Vergil","Virge","Wallace","Wallis","Wally","Wallie","Waldo","Walter","Walt","Wally","Wallie","Warren","Wayne","Wesley","Wes","Wendell","Dell","Del","Wilbert","Will","Willie","Willy","Bert","Wilbur","Wilber","Will","Willie","Willy","Wiley","Will","Willie","Willy","Wilfred","Wilfrid","Will","Willie","Willy","Fred","Freddie","Freddy","Willard","Will","Willie","Willy","William","Bill","Billy","Billie","Will","Willie","Willy","Liam","Willis","Bill","Billy","Billie","Will","Willie","Willy","Wilson","Will","Willie","Willy","Winfred","Winfrid","Win","Winnie","Winny","Fred","Freddie","Freddy","Winston","Win","Winnie","Winny","Woodrow","Wood","Woody","Xavier","Zave","Zachary","Zachariah","Zacharias","Zack","Zacky","Zach"
};

I want to pick a random name (e.g. Will), then just take the first character (W), and convert that from a char to a string.

My random function is:

static System.Random rnd = new System.Random();

And my code, put together, reads:

string Initial = Name1[rnd.Next(Name1.Count)][0].ToString();

However, when I run the above code, I see the following error in Unity's console, pointing to the above line:

IndexOutOfRangeException: Index was outside the bounds of the array.

How can this be possible, if I'm only using an index provided within the total count of the list object?


I have also tried using Substring:

string Initial = Name1[rnd.Next(Name1.Count)].Substring(0,1);

This throws the following error:

ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length

This is just as confusing, as it implies (from what I can understand) that the string I've found is less than one character long. How can this be possible?




postman - locking random value, same value for every test in same collection

Is there a way to 'lock' random value in postman? I would like to generate one random value and use same value for every test in same collection.

this code generate different random value for every test:

pm.environment.set("random", _.random(0,9999999));



Issues making a random number bubble sort in python

My friggin loser dad is trying to get me to learn how to code during quarantine so told me to make a random number bubble sort in python. The user is meant to input if they want to see the numbers from biggest to smallest and vice versa and then create a random number list and sort them. Im a bit stuck and don't know where to go. Thanks to those who might help. :)

Heres the code

import random


def bubble_sort(list):
    # We go through the list as many times as there are elements
    for i in range(len(list)):
        # We want the last pair of adjacent elements to be (n-2, n-1)
        for j in range(len(list) - 1):
            if list[j] > list[j+1]:
                # Swap
                list[j], list[j+1] = list[j+1], list[j]





correct=False
upordownuni=False

list = []

for i in range(0,100):
    x = random.randint(1,10)
    list.append(x)


while correct==False:
    print("Do you want the list to be sorted up or down?")
    upordown = input ("Type up or down for what you want\n")
    if upordown==("up"):
        upordownuni=True
        break
        bubble_sort()
    elif upordown==("down"):
            break
            bubble_sort()
    else:
        print("Invalid! Please input up or down.")



I want to get the multiplication of two prime numbers of the N digits I have entered

I am python beginner.

I want to get the multiplication of two prime numbers of the N digits I have entered in python.

I even implemented two prime numbers and multiplying them.

For example, if I enter 2 in N, the multiplication of the 2-digit prime number should be output.

I don't know what to do next.

My code is

import random
nums = []
for num in range(10,100):  
   if num > 1:  
       for i in range(2, num):  
           if (num % i) == 0:  
               break  
       else:
           nums.append(num)
prime = random.sample(nums, 2)
print(prime)
N = prime[0] * prime[1]
print('multiply with the two prime numbers:', N)

And 'range' is a randomly set range in "for num in range(10,100)"




2D version of numpy random choice with weighting

This relates to this earlier post: Numpy random choice of tuples

I have a 2D numpy array and want to choose from it using a 2D probability array. The only way I could think to do this was to flatten and then use the modulo and remainder to convert the result back to a 2D index

import numpy as np
# dummy data
x=np.arange(100).reshape(10,10)

# dummy probability array
p=np.zeros([10,10])
p[4:7,1:4]=1.0/9

xy=np.random.choice(x.flatten(),1,p=p.flatten())
index=[int(xy/10),(xy%10)[0]] # convert back to index
print(index)

which gives

[5, 2]

but is there a cleaner way that avoids flattening and the modulo? i.e. I could pass a list of coordinate tuples as x, but how can I then handle the weights?




Can I make a secure "pure function" based password generator using python's random module?

So I was looking for ways of managing my passwords without using a server-based password manager like LastPass and I came across https://lesspass.com. According to the website, this tool creates the same password for the given master password, username and website. I really liked the idea and decided to make my own proof of concept in python using the random module. I made this simple function:

    import random
    import string
    import os


    MASTER_PASS=os.environ.get('MASTER_PASS')


    def generate(platform, user, length):
        random.seed(platform+user+MASTER_PASS)
        letters=string.ascii_letters +string.digits + string.punctuation
        password=""
        for i in range(length):
            password+=random.choice(letters)
        print(password)



    generate("facebook", "xyz.abc", 32)

I think this should be secure enough as long as nobody knows my MASTER_PASSWORD but I cannot shake the feeling that this is somehow stupidly unsafe. Can anyone point out the glaring flaws in this approach and suggest some ways to improve the robustness?




I want to convert num to list type

I am learning Python. And I am a beginner to Python.

I want to receive two randomly extracted prime numbers as a list in python. And how can I make the number of digits multiplied by the randomly extracted prime number less than 11 digits? My code is

import random

lower = int(input("Enter lower range: "))  
upper = int(input("Enter upper range: "))  

for num in range(lower,upper + 1):  
   if num > 1:  
       for i in range(2, num):  
           if (num % i) == 0:  
               break  
       else:
         print(num)

I made only the prime number.

For example, if you enter 10, the product of two primes must be 10 digits. Two prime numbers are random.

If you enter 2, two prime numbers are randomly extracted. Assuming 11 and 3 here, the product of the two numbers is 33, so you get two digits. It is like this.




How to create a dataframe with different random numbers on each column?

I'm trying to make different random numbers but it keeps being the same on every column, how to fix it, using 1 line?

CODE:

yuju= pd.DataFrame()
column_price_x = [random.uniform(65.5,140.5) for i in range(20)]
for i in range(1990,2020):
    yuju[i] = column_price_x
yuju

RESULT

result

EXPECTED: Different numbers value for each column

How can I deal with it?




How can I generate a random order from form value in html?

I am asked to do this question for my assignment: Descriptions: 1. Create a HTML page and ask the user to input the number of groups 2. Press a button to generate random order for Group Presentation




G-suite Forms Quiz. Random answers

I'm looking at a script to make forms from a spreadsheet, I found some application that already does, but I wanted to make some modification.

https://scooltic.es/generador-de-examenes-aleatorios-con-google-forms/

I wish I could get multiple answers out randomly.

I have found that with:

  • setIsQuiz(true) converts a form into a questionnaire.

  • setShuffleQuestions(true) questions in a form are randomized.

  • setRequired(true) is obligated to answer the question.

But I don't see how to make the answers of MultipleChoiceItem random, for example.

I think it should be here:

https://developers.google.com/apps-script/reference/forms/multiple-choice-item

But I can't find the solution, does anyone know?

Thanks




lundi 27 avril 2020

Generate random value on new column, based on group value of other columns in Spark

We have following Dataframe:

------
G1|G2|
1 | 1|
1 | 1|
1 | 2|
2 | 1|
2 | 2|
2 | 3|

So based-on column G1 and G2 we have 5 groups: 1-1, 1-2, 2-1, 2-2, 2-3.

I would like to create new column isSelected with following rule: With N rows belonged to each group, I would like to randomize at least 50% rows will have value 1 and 0 for otherwise. Every group must have at least 1 row that isSelected = 1 and [number of 1 rows] - [number of 0 rows] should be less than 1

Following is one valid generation:

----------------
G1|G2|isSelected
1 | 1|1
1 | 1|0
1 | 2|1
2 | 1|1
2 | 2|1
2 | 3|1

Following is not valid:

----------------
G1|G2|isSelected
1 | 1|1
1 | 1|1 --> Not OK, this group has 2 1-row and 0 0-row.
1 | 2|1
2 | 1|1
2 | 2|1
2 | 3|0 --> Not OK, this group has 0 1-row.

How to do it directly in Spark?




Is it possible to supply the seed starting a random number sequence in flutter?

I'd like to produce a sequence of pseudo-random numbers, but be able to reproduce the sequence at will. In another language (Borland's Delphi, among others) you could supply the seed number starting a sequence rather than letting the compiler use something like the current time as the seed.




Dichotomy to find unkown number with success/fail instead of more or less

I'm trying to translate a program from Python to LSL (SecondLife scripting) to find a number I can't access from functions. This number is my linden balance (the money in game.) The only way I can determinate that amount from my script is by transferring amounts of money to myself and to check if the paiement was successful or not.

In order to do so, I found a dychotomy python script that works perfectly :

from random import randint

n = 100000000 # Maximum amount possible
amountToFind = randint(1,n)
a = 1
b = n
nbAnswers = 0

while b-a >=0: 
    answer= (a+b)//2
    nbAnswers += 1
    if answer== amountToFind:
        print("The correct answer is:", answer)
        break 
    elif answer> amountToFind:
        b = answer- 1
    else:
        a = answer+ 1

print("The number of steps to get the correct amount was :", nbAnswers)
print(amountToFind)

The problem is that I can't compare answerto the number i'm looking for. I only have fail and success :

llCheckLindenBalance()
{
        rep = (a+b)/2;
        transactionId = llTransferLindenDollars(owner, rep);
}

touch_start(integer total_number)
{
    llCheckLindenBalance();
}

transaction_result(key id, integer success, string data)
{
    if(id != transactionId)
        return;



    if(success) // rep < amount or rep == amount
    {

        a = rep+1;
        llOwnerSay("Last amount " +(string)rep);
        llCheckLindenBalance();

    }
    else // FAIL - rep < amount
    {
       b = rep-1;
       llCheckLindenBalance();
    }
}

That script works so far, but it will never stop as it nevers knows when to stop. I was thinking about comparing a and b but the space between them is variable as well (from 0 to 10). So i'm stuck at it. I thought about testing answer+1 and if it fail it means it's the highest amount but I can't now where to test it.

Do you guys have any idea ?




Random Walk in a 3D spherical coordinates system-Python

I am currently attempting to map and show the path of a photon from the center of the sun until it reaches the surface and is emitted. I also want to show the time taken for this to happen.

So far all I have done is set the parameters (density of sun, Thompson cross-section, mass of electron, mass of proton) and using these I was able find the mean free path in the sun for a photon. I know that I will have to set an array of some sorts, and create random numbers for each random walk. I do not know what to do to make the random walk so that the photon can go in any direction in the x, y or z values.

I also do not know what I should loop in order to create this random walk. I need it so that the random walk will stop when d is equal to or greater than the radius of the sun. I know that d=l*sqrt(N), where l is the average size of each step, or mean free path, and N is the number of steps taken.

Lastly, I would not know where to start with plotting the results. I would like to show an animation of the photon travelling through a sphere from the center, where the sphere would resemble the sun.

Below is the only code I have so far, any help would be much appreciated.

from random import random, seed, randint
import numpy as np
import matplotlib.pyplot as plt

N=100000
rho=1408.6 #the mass density of the sun
thompson=6.65*10**-29 #Thompson cross-section for an electro 
proton=1.67*10**-27 #mass of a proton
electron=9.11*10**-31 #mass of an electron
radius=6.9634*10**8 #radius of a sun
c=2.99*10**8

mfp=(electron+proton)/(rho*thompson*np.sqrt(2))
timestep=mfp/c



How can I efficiently sample random posts in Django, when each post uses UUIDs rather than sequential IDs?

I have some post models where the ID is a UUID. Now I want to display some random post proposals the user may also like to see at my post_detail template...

This is how I process the post proposals the user may also like to see at views.py:

def post_proposals():
    post_elements = sorted(
        chain(
            Model1.objects.all(),
            Model2.objects.all(),
            Model3.objects.all()
        )
    )
    post_elements_list = list(post_elements) # Conversion to list is requierd by random
    post_proposals = random.sample(post_elements_list)
    return post_proposals


def post_detail(request, pk):
    ...
  args = {
    'post': post,
    'post_proposals': post_proposals(),
  ...

template.html:

 

The problem now is that this would kill my database performance from my understanding... As soon as I have a lot of posts stored at my database the query will become massive. I first have to get all elements of 3 models and then get 10 random entries from the list each time a post gets displayed to the user.

I also found the following which seems to be quite useful:

https://elpenia.wordpress.com/2010/05/11/getting-random-objects-from-a-queryset-in-django/

Sadly I can't use that solution as I work with UUIDs which are non-sequential strings instead of int values I would have with IDs.




Simple way to shuffle deck of cards

I'm looking for a simple way to shuffle my deck of cards. I have finished the deck, what's a simple way to create a function that shuffles the 52 cards? I'm not looking for complex ways to shuffle my deck, I prefer code that I can read with ease. I've tried to put rand() on the cout part, but it just randomizes both suits and faces and I get the wrong cards.

struct Card 
    {
        int value;
        char suit;
    };
Card cards[52];   //global variables

int main()
{
    int play;

    shuffleDeck();
    cout << endl<<endl;
    cout << "---------------------------" << endl;
    cout << "|Welcome to The Game Of 31| " << endl;
    cout << "---------------------------" << endl;
    cout << "Would you like to play? (1 for 'YES', 0 for 'NO'): ";
    cin >> play;
    if (play == 1) { shuffleDeck(); }
    else { cout << "See yaa!"; exit(0); }



}


void shuffleDeck() {
    for (int i = 0; i < 52; i++)
    {
        cards[i].value = i % 13; // 13 values
        if (cards[i].value == 0) {
            cards[i].value = 1;
        }
        else if (cards[i].value == 1) {
            cards[i].value = 2;
        }
        else if (cards[i].value == 2) {
            cards[i].value = 3;
        }
        else if (cards[i].value == 3) {
            cards[i].value = 4;
        }
        else if (cards[i].value == 4) {
            cards[i].value = 5;
        }
        else if (cards[i].value == 5) {
            cards[i].value = 6;
        }
        else if (cards[i].value == 6) {
            cards[i].value = 7;
        }
        else if (cards[i].value == 7) {
            cards[i].value = 8;
        }
        else if (cards[i].value == 8) {
            cards[i].value = 9;
        }
        else if (cards[i].value == 9) {
            cards[i].value = 10;
        }
        else if (cards[i].value == 10) {
            cards[i].value = 10;

        }
        else if (cards[i].value == 11) {
            cards[i].value = 10;
        }
        else if (cards[i].value == 12) {
            cards[i].value = 10;
        }


        cards[i].suit = i / 13;// 4 suits
        if (cards[i].suit == 0) {
            cards[i].suit = 'D';
        }
        else if (cards[i].suit == 1) {
            cards[i].suit = 'H';
        }
        else if (cards[i].suit == 2) {
            cards[i].suit = 'C';
        }
        else if (cards[i].suit == 3) {
            cards[i].suit = 'S';
        }
    }

    for (int count = 0; count < 52; count++) {
        int count2 = 0;
        cout << " | " << cards[count].value;
        cout << cards[count].suit << " | ";

        if (count == 13) { cout << endl; }
        else if (count == 26) { cout << endl; }
        else if (count == 39) { cout << endl; }
        else if (count == 52) { cout << endl; }
    }
}



distrubuting people to groups evenly based on userinput

ReadFile randomGenerate = new ReadFile();
        Input userNum = new Input();
        String classnum = userNum.fileToSelect();
        int lineNumber = randomGenerate.lineCounter(classnum);

        //number of students in classnum.txt

        ArrayList<String> people = randomGenerate.readPeople();
        //a string of names(first word on each row)

        int userPut = userNum.numInput();
        int maxNum = lineNumber/userPut;

Right not, I am reading off a txt file - the first word of each row which is the name of a person. I want to distribute this ArrayList of people into even groups, with the number of groups based on userinput.

int[] numbers = RandomNumbersWithoutRepetition(0, lineNumber, lineNumber);       
//an array of numbers IN ORDER

int[] randomNumbers = RandomizeArray(numbers);
//shuffles the array

I generated a set of numbers in order, and then shuffled them, which works fine.

But, my method of grouping people has been based off ifelse conditions which don't work so well. So is there an efficient method to put this ArrayList of names into user-desired groups?




Shuffling groups of elements in an arraylist

I am working on a group generator and currently I am making an ArrayList from this txt file. enter image description here

So that, the ArrayList is in the form of [PedroA, Brazil, Male, 10G, Saadia...]

I want to shuffle 4 elements at a time, to randomize this arraylist.

I am storing the info in

ArrayList<String> studentInfo = info.readEachWord(className);



Is (y == 7) really the opposite of (y != 7)? Observing random variables

I wrote a program in C# that keeps generating random numbers between 0 and 10,000 until the number generated is equal to a predetermined value (in this case 4377). Then the program repeats the process for N number of times, then calculates the average number of guesses it takes the computer to get 4377.

I have done this the first time using an infinite while loop with an if statement inside it that breaks out of the loop when the number is equal to 4377, then I thought my code had a redundant line (the if statement), I could just write (y != 4377) as a while condition. .

Contrary to my expectations, I got different results for each case. The first code usually takes around 10,000 guesses on average (consistently) to get 4377, when the second code takes way fewer guesses on average, some times as few as 3! That’s a huge difference! (N = 1000).

Case 1 – infinite while loop with a conditional break inside:

using System;

namespace Codeac
{
    class Program
    {
        static void Main(string[] args)
        {
            Random x = new Random();
            int i, size;
            Console.Write("Enter sample size: ");
            size = Convert.ToInt32(Console.ReadLine());
            double[] k = new double[size];
            int y = 0;
            for (int p = 0; p < size; p++)
            {
                i = 0;
                while (true)
                {
                    y = x.Next(0, 10000);
                    i++;
                    if (y == 4377) { break; }
                }
                k[p] = i;
                Console.WriteLine(y);
            }
            Console.WriteLine("\n \n \n");
            Console.WriteLine("Mean of tries is: ");
            Console.WriteLine(Mean(k));

            Console.WriteLine("\n \n \n");
            Console.WriteLine("Stabdard deviation is: ");
            Console.WriteLine(Math.Round(StandardDeviation(k), 3));
        }
        public static double Mean(double[] samples)
        {
            double mean = 0;
            for (int r = 0; r < samples.Length; r++)
            {
                mean += samples[r];
            }
            mean /= samples.Length;
            return mean;
        }

        public static double StandardDeviation(double[] samples)
        {
            double mean = Mean(samples);
            double standardDeviation = 0;
            for (int r = 0; r < samples.Length; r++)
            {
                standardDeviation += Math.Pow(samples[r] - mean, 2);
            }
            standardDeviation = Math.Sqrt(standardDeviation / mean);
            return standardDeviation;
        }
    }
}

Case 2 – reversed condition as a while condition.

using System;

namespace Codeac
{
    class Program
    {
        static void Main(string[] args)
        {
            Random x = new Random();
            int i, size;
            Console.Write("Enter sample size: ");
            size = Convert.ToInt32(Console.ReadLine());
            double[] k = new double[size];
            int y = 0;
            for (int p = 0; p < size; p++)
            {
                i = 0;
                while (y != 4377)
                {
                    y = x.Next(0, 10000);
                    i++;
                }
                k[p] = i;
                Console.WriteLine(y);
            }
            Console.WriteLine("\n \n \n");
            Console.WriteLine("Mean of tries is: ");
            Console.WriteLine(Mean(k));

            Console.WriteLine("\n \n \n");
            Console.WriteLine("Stabdard deviation is: ");
            Console.WriteLine(Math.Round(StandardDeviation(k), 3));
        }
        public static double Mean(double[] samples)
        {
            double mean = 0;
            for (int r = 0; r < samples.Length; r++)
            {
                mean += samples[r];
            }
            mean /= samples.Length;
            return mean;
        }

        public static double StandardDeviation(double[] samples)
        {
            double mean = Mean(samples);
            double standardDeviation = 0;
            for (int r = 0; r < samples.Length; r++)
            {
                standardDeviation += Math.Pow(samples[r] - mean, 2);
            }
            standardDeviation = Math.Sqrt(standardDeviation / mean);
            return standardDeviation;
        }
    }
}

Please ignore the standard deviation for now. If anyone has any ideas on why this is happening, or any remarks or thoughts about this, please reply to this topic. I appreciate all responses.




dimanche 26 avril 2020

Create an Object based on Probability

I'm creating Objects in Java, So I have 4 classes and each has their respective probabilities eg 50%, 30%, 20% and the last object has 0%.

These probabilities will change over time and the last object won't stay at 0%.

They will always add up to 100% and never go over.

I need to be able to choose an object based on their probabilty.

The only way I could think of so far was to create a list of 100 elements and populate with 50 of one object, 30 of another, and 20 of another. Then get a random integer between 0 and 100. But this isn't very efficient especially since I will be calling this multiple times.

Can anyone advise on a method that doesn't use anything outside of Java's inbuilt packages and functionality.




Math.random() generates a number greater than 1 [duplicate]

I created a variable to display and then to display it

double randomNumber = Math.random(); System.out.print(randomNumber + "\t");

One of the results was 8.791603511049129E-5 Isn't Math.random() supposed to generate a number greater than or equal to 0.0 and less than 1.0? How come it was higher?




C++ Random string array If statement only outputs one answer

This is my first ever piece of code that ive developed independently and ive run into an issue. Ive Googled the issue and no prevail. I'm making a Rock Paper Scissors game and I have an input where you choose either Rock Paper or Scissors, after you choose, the program randomly outputs either Rock Paper or Scissors, now my issue is with the If statements after the random output, it only selects:

          {
                cout << ", you lose! Do you want to play again? (Yes / No)";
            }         

Whereas this is my code here:

    #include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
    // yn = yes / no
    string yn;
    cout << "Do you want to play Rock, Paper, Scissors? (Yes / No) ";
    cin >> yn;
    if (yn == "Yes")
    {
        // rps = rock paper scissors
        string rps;
        cout << "Choose, Rock, Paper, or Scissors\n";
        cin >> rps;

        if (rps == "Rock")
        {
            // Randomizer 
            srand(time(0));
            string rpslist[3] = { "Rock", "Paper", "Scissors " };
            int rpsnumber = rand() % 3;
            cout << "I choose: " << rpslist[rpsnumber];

            if (rpslist[1] == "Rock")
            {
                cout << ", we draw! Do you want to play again? (Yes / No)";
            }
            if (rpslist[2] == "Paper");
            {
                cout << ", you lose! Do you want to play again? (Yes / No)";
            }         
            if (rpslist[3] == "Scissors")
            {
                cout << ", you win! Do you want to play again? (Yes / No)";
            }
        }



Python histogram of Randomized Quicksort Comparisons per Run

I have to implement the Las Vegas Randomized Quicksort algorithm and count the number of comparisons for each run to sort a random list of integers and create a histogram for the obtained valus with the number of runs being 10^4.

I am having trouble with the histogram, as it shows somethig this:

enter image description here

Instead of a distribution similar to this:

enter image description here

Here is the code I imagined. The number of comparisons is correct.

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

def _inPlaceQuickSort(A, start, end):
    count = 0
    if start < end:
        pivot = randint(start, end)
        temp = A[end]
        A[end] = A[pivot]
        A[pivot] = temp

        p, count = _inPlacePartition(A, start, end)
        count += _inPlaceQuickSort(A, start, p - 1)
        count += _inPlaceQuickSort(A, p + 1, end)
    return count


def _inPlacePartition(A, start, end):

    count = 0
    pivot = randint(start, end)
    temp = A[end]
    A[end] = A[pivot]
    A[pivot] = temp
    newPivotIndex = start - 1
    for index in range(start, end):

        count += 1
        if A[index] < A[end]:  # check if current val is less than pivot value
            newPivotIndex = newPivotIndex + 1
            temp = A[newPivotIndex]
            A[newPivotIndex] = A[index]
            A[index] = temp

    temp = A[newPivotIndex + 1]
    A[newPivotIndex + 1] = A[end]
    A[end] = temp
    return newPivotIndex + 1, count 

if __name__ == "__main__": 
    for i in range(10):
        A={}
        for j in range(0, 10000):
            A[j] = random.randint(0, 10000)
        comp.append(_inPlaceQuickSort(A, 0, len(A) - 1)) 
    print(comp[i])

    plt.hist(comp, bins=50)
    plt.gca().set(title='|S|=10^4, Run=10^4', xlabel='Compares', ylabel='Frequency')



my random walk program outputs nothing (java)

So, my random walk program is supposed to start at coordinates 0,0 and then dependent on the value random, should + or - 1 from either x or y. If I print rand, I get a value, so it seems like its not executing the loop at all. I've tried moving rand into the loop and tried changing the for loop parameters to a few things that would ultimately result in the same goal and I cannot for the life of me seem to understand why it just doesn't output anything other than the starting coordinate (0, 0)

Any help will be greatly appreciated.


    public static void main(String[] args) {

        // create two variables representing x and y and set at 0
        int x = 0;
        int y = 0;

        // define dist
        int dist = Math.abs(x) + Math.abs(y);

        // create instance of Math.random
        double rand = Math.random();

        // print starting coordinates before executing loop
        System.out.print(x + ", " + y);

        // for loop to  count total steps taken and stop the nested loops running once absolute distance = 5
        for (int total = 0; dist == 5; ++total) {

            // decides if to change y or x value
            //works on x
            if (rand < 0.5) {

                // decides if to increment or decrement x
                // increments x
                if (rand < 0.25) {
                    x++;
                    System.out.println(x + ", " + y);
                }
                // decrements x
                else {
                    x--;
                    System.out.println(x + ", " + y);
                }
            }

            // works on y
            else {

                // decides if to increment or decrement y
                // increments y
                if (rand > 0.75) {
                    y++;
                    System.out.println(x + ", " + y);

                }
                //decrements y
                else {
                    y--;
                    System.out.println(x + ", " + y);
                }
            }

            System.out.println("steps = " + total);

        }

    }
}



How do you slightly randomise already set values in variables? (Difficult to explain)

What I'm trying to do here, is randomise 2 values slightly, by 1-2 or 2-4, something like that. so for example

list = [ -12, 6 ]
for x, y in list:
    MouseMov(x.randchange(1-3), y.randchange(1-3))
    print(x, y)
    # And then the values would be like x = -13,y =  5
    # Or then the next time they could be x = -12, y= 7
    # You get the point, each time it loops, the values change slightly. How do I do this?

How do we make it so each time it loops, the values randomly are changed by 1-3 or whatever range we choose? Hope my question was understandable.




BEGINNER: Removing items from Javascript Array

I am coding a random quote generator. I almost have it fully coded how I want. I am a beginner in HTML and I've never used Javascript before this weekend. I took from multiple tutorials to code this exactly how I want it and am very proud. I have one last thing I am trying to do. When a item from the array is called, I want it to be removed, stored in another array and when the original array reaches 0, I want it to reset. I know its possible but I am not sure what to add to this script to make it work. Thanks so much for any help.

This is my HTML:

<style type="text/css">
    body{
        font-family: "Poppins", sans-serif;
        background-color: #3F6BFF;
    }

    .maincontainer{
        position:relative;
        width: 500px;
        height: 300px;
        animation:flip 1s;
        text-align: center;
        margin: 0 auto;
        border-radius: 25px;
    }

    .thecard{
        position:relative;
        width: 100%;
        height: 100%;
        transform-style: preserve-3d;
        transition: all 0.5s ease;
        border-radius: 25px;
    }

    .thecard:active{
        transform:rotateY(360deg);
    }

    .thefront{
        position: absolute;
        width: 100%;
        height: 100%;
        padding-right:30px;
        padding-left:30px;
        backface-visibility: hidden;
        background-color: #fff;
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
        border-radius: 25px;
    }

    .theback{
        position: absolute;
        width: 100%;
        height: 100%;
        padding-right:30px;
        padding-left:30px;
        backface-visibility: hidden;
        transform: rotateY(180deg);
        background: #000;
        border-radius: 25px;
    }

    .gameTitleStyle{
        font-weight: 800;
        font-size:32px;
        text-transform: uppercase;
}

.ruleStyle{
        position:relative;
        top:-20px;
        font-style: italic;
}

    .questionStyle{
     position: relative;
     top: 20px;
     font-size:18px;
}


</style>

<body>

<div class="maincontainer" id="quoteBtn">

    <div class="thecard">

        <div class="thefront">
            <h1 class="gameTitleStyle" id="gameTitle">Business Name</h1>
            <p class="ruleStyle" id="ruleTxt">Rules</p>
            <p class="questionStyle" id="quote">Card Description</p>
        </div>

        <div class="theback"></div>

    </div>


</div>

    <script src="javascript.js"></script>

</body>

This is my Javascript

const quotes =[
{
    game: 'CARD TYPE 1',
    quote: "This is the card description for Card Type 1",
    rule: "Card Type 1 Rules"
},
{
    game: 'CARD TYPE 2',
    quote: "This is the card description for Card Type 2",
    rule: "Card Type 2 Rules"
},
{
    game: 'CARD TYPE 3',
    quote: "This is the card description for Card Type 3",
    rule: "Card Type 3 Rules"
}   
];

const maincontainer = document.querySelector("#quoteBtn");
const questionStyle = document.querySelector("#quote");
const gameTitleStyle = document.querySelector("#gameTitle");
const ruleStyle = document.querySelector("#ruleTxt");

quoteBtn.addEventListener("click", displayQuote);

function displayQuote(){
    let number = Math.floor(Math.random() * quotes.length);

    gameTitle.innerHTML = quotes[number].game;
    quote.innerHTML = quotes[number].quote;
    ruleTxt.innerHTML = quotes[number].rule;
}



R - Randomly sample from a matrix using a distribution to denote the number of zeros in each column

I am trying to randomly sample from a matrix (b below) but I want the resulting matrix of samples to have a proportion of zeros in each column equal to that of another matrix (a below). I am trying to use sample() function to do this but I'm not having much joy. Some reproducible code is below which will hopefully explain my problem:

set.seed(1234)
# matrix a is the matrix that holds the distribution of zeros I want to match
a <- matrix(as.integer(rexp(200, rate=.1)), ncol=20)
# matrix b is the matrix to be sampled from 
b <- matrix(as.integer(rexp(2000, rate=.1)), ncol=20)

a looks like:

     [,1] [,2] [,3] [,4] [,5]
[1,]    6    0    6    1   22
[2,]   19    6    0   23   19
[3,]    8   22    8    5    0
[4,]   24   17   28    3    0

b looks like:

      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    1   10    5    9
 [2,]   26    1    3    2    2
 [3,]    4    8    3    0    0
 [4,]    2   10   35    3   11
 [5,]    1    3   16    0    6
 [6,]    2    4    2   16    2
 [7,]    3   18   13    6   17
 [8,]    0    2    9    0   13
 [9,]    2   15    6   27   30
[10,]    1    2    7    9   15
[11,]   13    0    5    1    2
[12,]   18   12    9   27   33
[13,]    0   20    3   18    1
[14,]    5    7    7   16    4
[15,]    5    6    4    5    2
[16,]    0    7    5   10    7
[17,]    3   20    5   14   34
[18,]   28    0   10    5    8
[19,]   33    0    2    6   13
[20,]    7   28    0   11    8

I extract the distribution of zeros in each column of a to use in the sampling

dist<-apply(a,2, function(x) sum(x!=0)/length(x)) 
dist
[1] 1.00 0.75 0.75 1.00 0.50

I then go on to try and sample from b to hold the same number of rows as a

b_sample<-b[sample(x=nrow(b),
                   size=4,
                   replace=F
                   )
            ,]

This will work but I want the b_sample to to have the same proportion of zeros in each column as a. I have tried to do this

b_sample<-b[sample(x=nrow(b),
                   size=4,
                   replace=F,
                   prob=dist
                   )
            ,]

but I get an error:

Error in sample.int(x, size, replace, prob) : 
  incorrect number of probabilities

I am not sure if I have the format wrong to do this or is the sample() function not the correction function at all to use. Any help would be greatly appreciated!




How to print numbers 1-10 in random order with no repeats in C

I need to be able to print numbers 1-10 in random order in C. Thank you.




Python 3.x | How to use random.choice() or .sample() to make sure it doesn't pick the same value in a dictionary

I am a beginner in python and making an english/norwegian dictionary.
I am trying not to have the same english word come more than once when I run the program.
I know that this has been answered many times already, but I just can't get the right code for that implemented in the program.
I would appreciate very much if someone could implement the right code for that problem.
Here is the code so far:

import random
eng_nor = {'one':'en', 'two': 'to', 'three': 'tre', 'four': 'fire', 'five': 'fem', 'six': 'seks', 'seven': 'syv',
           'eight': 'åtte', 'nine': 'ni', 'ten': 'ti'}
print()
print('Number of words in the dictionary: ',len(eng_nor))
print()

eng = list(eng_nor.keys())
print('If you want to exit, type 0')
antall_gloser=int(input('How many words do you want to practice?\n '))
if antall_gloser>len(eng_nor):
    x=len(eng_nor)
    antall_gloser=x
    print('We have just ', x, ' words in the dictionary.')
point = 0

for i in range(antall_gloser):
    eng_ord = random.choice(eng)
    norsk_ord = eng_nor[eng_ord]
    user_guess = input('What is the norwegian word of %s?\n' % eng_ord)
    if user_guess == 0:
        break
    elif user_guess == norsk_ord:
        point += 1
        print('Correct! Your score is %d' % point)
    else:
        print('Wrong. The norwegian word of {} is {}.'.format(eng_ord, norsk_ord))
print('We are done. Your final score is %d, Thank you.' % point)

An example of an output I get could be like this:

D:\Users\heva\PycharmProjects\test\virtual\Scripts\python.exe D:/Users/heva/PycharmProjects/test/test10.py

Number of words in the dictionary:  10

If you want to exit, type 0
How many words do you want to practice?
 3
What is the norwegian word of two?
to
Correct! Your score is 1
What is the norwegian word of two?
to
Correct! Your score is 2
What is the norwegian word of seven?
syv
Correct! Your score is 3
We are done. Your final score is 3, Thank you.

Process finished with exit code 0

As you see in this example, two of the english words are the same....
Any help would be highly appreciated..
Thanks in advance!




why it is showing " TypeError: Invalid shape (20,) for image data "

    import numpy as np
    import matplotlib.pyplot as plt  
    m1=np.random.randint(0,20,4*5)
    m1.reshape(4,5)
    plt.imshow(m1)

**when I have executed above code in python 3 on jupyter notebook, I got Type error anyone please answer to this error in simplest way ** like TypeError Traceback (most recent call last) in ----> 1 plt.imshow(m1)

c:\users\jaiprakash\appdata\local\programs\python\python37-32\lib\site-packages\matplotlib\pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs)
   2649         filternorm=filternorm, filterrad=filterrad, imlim=imlim,
   2650         resample=resample, url=url, **({"data": data} if data is not
-> 2651         None else {}), **kwargs)
   2652     sci(__ret)
   2653     return __ret

c:\users\jaiprakash\appdata\local\programs\python\python37-32\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
   1563     def inner(ax, *args, data=None, **kwargs):
   1564         if data is None:
-> 1565             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1566 
   1567         bound = new_sig.bind(ax, *args, **kwargs)

c:\users\jaiprakash\appdata\local\programs\python\python37-32\lib\site-packages\matplotlib\cbook\deprecation.py in wrapper(*args, **kwargs)
    356                 f"%(removal)s.  If any parameter follows {name!r}, they "
    357                 f"should be pass as keyword, not positionally.")
--> 358         return func(*args, **kwargs)
    359 
    360     return wrapper

c:\users\jaiprakash\appdata\local\programs\python\python37-32\lib\site-packages\matplotlib\cbook\deprecation.py in wrapper(*args, **kwargs)
    356                 f"%(removal)s.  If any parameter follows {name!r}, they "
    357                 f"should be pass as keyword, not positionally.")
--> 358         return func(*args, **kwargs)
    359 
    360     return wrapper

c:\users\jaiprakash\appdata\local\programs\python\python37-32\lib\site-packages\matplotlib\axes\_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
   5613                               resample=resample, **kwargs)
   5614 
-> 5615         im.set_data(X)
   5616         im.set_alpha(alpha)
   5617         if im.get_clip_path() is None:

c:\users\jaiprakash\appdata\local\programs\python\python37-32\lib\site-packages\matplotlib\image.py in set_data(self, A)
    697                 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
    698             raise TypeError("Invalid shape {} for image data"
--> 699                             .format(self._A.shape))
    700 
    701         if self._A.ndim == 3:

TypeError: Invalid shape (20,) for image data



How to best diplay a random string, with some strings weighted heavier than others

I am trying to display a random string but would like some strings to occur more often than others. My current strategy is with nested dictionaries for ease of updating and the 'choices' function.

msg_list = {

    'msg_1': {
        'msg': 'Hi',
        'weight': 40,
        'size': 15,
        },

    'msg_2': {
        'msg': 'hello',
        'weight': 50,
        'size': 12,
        },

    'msg_3': {
        'msg': "What's up",
        'weight': 10,
        'size': 50,
        },
    }

message = choices(msg_list['msg'], msg_list['weight'])
string = message['msg']

This obviously doesn't work, and I imagine I could build the lists with a loop, but I am curious if there is a faster way of doing this. Thanks!




Shuffling part of a list in-place

I have a list and I want to shuffle a portion of it in-place.

I am aware of random.shuffle() and that working in-place, but if I slice it, it shuffles the sliced-copy of the original input, leaving the original list untouched:

import random


l = list(range(20))
print(l)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

random.shuffle(l[:10])  # I wish it was shuffling the first half
print(l)  # but does nothing to `l`
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

What options do I have?




How to generate high dimensional Gaussian vectors via quasi-mont carlo (QCM) techniques in numpy

i would like to generate a set of gaussian vectors of mean m and covariance C in bumpy, the standard approach is

samplings_set = np.zeros((n,m.size))
for i in range(n):
    vect = np.random.multivariate_normal(m,C)
    vect.shape = (1,m.size)
    samplings_set[i,:] = vect

can i generate the ensemble via quasi-mont carlo (QCM) techniques in numpy? (in order to get a more representative samplings set)




a + b mod n vs. a xor b mod n

I'm procedurally generating a World in a Game and therefore use 2 equivalent pseudo-random generators (linear congruential) for x and y axis (giving both a different seed of course).

Now to be able to create different worlds I want to combine both pseudo-random values (e.g. both between 0 and 10) for each position (x,y).

I first thought of hashing (to generally equally hit each number from 0 to 10), but then found that XORing both ints might be more performant (o.c. you might call that hashing too) Now I still want to generate values between 0 and 10. So I would do:

(1) (r1 ^ r2) % 11. ( ^ beeing bitwise XOR)

And here I was wondering if that is equivalent to

(2) (r1 + r2) % 11

And which of both would be more performant. I'd say (1) because it does not carry bits?




Random number generator global to a class

I would like to generate uniformly distributed numbers on [0,1] in C++. I know that the following code would to the job

     std::random_device  rand_dev;
     std::mt19937  generator(rand_dev());
     std::uniform_real_distribution<double>  uni(0,1);
     std::cout << uni(generator);

But my issue is that I want to generate these numbers inside a class scope. And I don't want to initalize a new random number generator everytime I call a function of this class as I will need to call this function very often. Can I somehow use the same number generator for the entire class? I tried

class test{
      private: 
        std::random_device  rand_dev;
        std::mt19937  generator(rand_dev());
        std::uniform_real_distribution<double>  uni(0,1);

      public:
        void somefunction();
  };
test::somefunction(){std::cout << uni(generator);}

But this doesn't seem to work.




samedi 25 avril 2020

C# WPF 3D cubes with different colors

I need your help with this one. Tried everything I thought about.

I want to generate a bunch of cubes in some exact position based on my algorithm. Everything is done but it seems that I can't generate each cube in one color.

private double generatebox(double l, double h, double L, double orgx, double orgy, double orgz, int color)
        {
            Brush brush = new SolidColorBrush(Colors.Blue);
            switch (color)
            {
                case 1: 
                    brush = new SolidColorBrush(Colors.Blue);
                    break;
                case 2:
                    brush = new SolidColorBrush(Colors.Green);
                    break;
                case 3:
                    brush = new SolidColorBrush(Colors.Red);
                    break;
                default:
                    brush = new SolidColorBrush(Colors.Yellow);
                    break;
            }
            Model3DGroup cube = new Model3DGroup();

            //
            Material mat = new DiffuseMaterial(brush);
            //
            Point3D p0 = new Point3D(orgx, orgz, orgy);
            Point3D p1 = new Point3D(orgx + l, orgz, orgy);
            Point3D p2 = new Point3D(orgx + l, orgz + h, orgy);
            Point3D p3 = new Point3D(orgx, orgz + h, orgy);
            Point3D p4 = new Point3D(orgx, orgz + h, orgy + L);
            Point3D p5 = new Point3D(orgx + l, orgz + h, orgy + L);
            Point3D p6 = new Point3D(orgx + l, orgz, orgy + L);
            Point3D p7 = new Point3D(orgx, orgz, orgy + L);
            //
            cube.Children.Add(createTriangleModel(p0, p2, p1, mat));
            cube.Children.Add(createTriangleModel(p0, p3, p2, mat));
            cube.Children.Add(createTriangleModel(p2, p3, p4, mat));
            cube.Children.Add(createTriangleModel(p2, p4, p5, mat));
            cube.Children.Add(createTriangleModel(p1, p2, p5, mat));
            cube.Children.Add(createTriangleModel(p1, p5, p6, mat));
            cube.Children.Add(createTriangleModel(p0, p7, p4, mat));
            cube.Children.Add(createTriangleModel(p0, p4, p3, mat));
            cube.Children.Add(createTriangleModel(p5, p4, p7, mat));
            cube.Children.Add(createTriangleModel(p5, p7, p6, mat));
            cube.Children.Add(createTriangleModel(p0, p6, p7, mat));
            cube.Children.Add(createTriangleModel(p0, p1, p6, mat));
            //
            ModelVisual3D model = new ModelVisual3D();
            model.Content = cube;
            this.viewport3D.Children.Add(model);

            double prod = l * h * L;
            return prod;
        }

This is what I have know. When I call the generatebox function I call it with rnd digit 1...4. The cubes changes the color each time I run the code but all cubes have the same color. I want each cube to have its random color.

Any help will be appreaciate it. Thank you!




How could I make a limite numbres in an input and making them numbers only, I dont want symbols

I have a little game, which it let you to choose a random game, but I have three problrems:

1- I want to make my input accept only numbers, and there is no symbols.

2- I want to limit the input to be from number 0 to number 20.

3- I want to make a loop that if a the user insert a number and weither he win loose, I want to let him play again.....(it could be by asking him or directly)

Here is my code, if there is any problem(s) or reccommend(s) please tell me, and I hope that you could write it all in one letter so I could understand it, thank you very much for your help.

Here is the code:

import random
rn = int(random.randint(0, 20))
gn = int(input("write a number from 0-20: "))


while True:
  if rn < gn:
    print("You were too close, try again")
    break
  elif rn == gn:
    print("Oh, I lost, you win, good game (GG)")
    break
  if rn > gn:
    print("You are not close, try again")
    break

while False:
  rn = int(random.randint(0, 20))
gn = int(input("write a number from 0-20: "))



Not sure how to animate my random quote generator. Help-Beginner

I am trying to get my random quote generator to animate. I would like the animation to look like another card, in the same style is being flipped on top of this one, similar to a deck of cards. I don't know much about animation and have minimal coding knowledge, so I built this with a tutorial and then some edits to get it to function exactly how I wanted. Below is my code. Does any one know how I could add to this to complete that function? It is the last thing, I need to have the card function exactly how I want it.

    <!DOCTYPE html>
<html>
<head>
    <title>Quote Gen</title>
</head>
<style type="text/css">
    .cardbutton{
    width: 540px;
    height: 300px;
    border-width: 12px;
    border-style: solid;
    border-color: #02fad1;
    background-color: #fff;
    border-radius: 25px;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
<body>
    <h1>Simple Quote Generator</h1>

    <!--
        <button onclick="newQuote()" id="quoteDisplay" class="button">Drinking Game</button>
    -->
<div class="wrapper">
<button onclick="newQuote()" class="cardbutton" style="padding-right:15px; padding-left:15px;">
            <h1 style="font-family:poppins; position: absolute; top:100px; left:50%; margin-left:-83px;">MOST LIKELY TO</h1>
            <p id="quoteDisplay" style="position: relative; top:20px;">Whoever is most likely to, drinks!</p>
        </button>
</div>
    <script src="javascript.js"></script>
</body>
</html>

This is my Javascript.


var quotes = [
'Who do you want to make out with the most?',
'If you had to flash just one person in this room, who would it be?',
'If you haven\'t had your first kiss yet, who in this room do you want to have your first kiss with?',
'Of the people in this room, who would you go out with?',
'Describe the most attractive thing about each person in this room.',
'Who here do you think is the best flirt?',
'Who has the best smile?',
'Who has the cutest nose?',
'How about prettiest eyes?',
'Who\'s the funniest in this room?'
]

function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}




R function to simulate ranked votes

Hi all you cool cats and kittens,

I'm creating a shiny app for a blog post to illustrate the benefits of ranked-choice voting (RCV). In part of that post, I want to let the user define the choices and number of voters to show results of first past the post voting vs. ranked-choice voting. I've developed a full solution but the sampling makes it unrealistic (all choices get approximately choice/n_choices of the votes). And, usually the outcome is the same as the initial plurality since the runoff data is just noise. I need a way to create uneven sampling that doesn't always result in the candidate with plurality winning. My initial solution was to break the population in half and give arbitrary weights to options for the two different groups... this really didn't help.

Any ideas to create a sample of choices with initial plurality candidate not always becoming favorite?

Here is code as is

# ---- Input Parameters
n_voters     <- 10000                        # number of voters
choice_names <- c("A", "B", "C", "D", "E")   # choice names
n_choices <- length(choice_names)            # number of choices


candidate_df <- matrix(NA,                      # Creating null matrix of choices x voters
                       nrow = n_voters,
                       ncol = n_choices,
                       dimnames = list(paste("Voter", 1:n_voters), choice_names))


# ---- Filling in Data Frame with simulated choices from a given voter base
for(i in 1:nrow(candidate_df)){

  if(i < 0.5*nrow(candidate_df)){ #trying to create uneven distributions with two "different" populations
    choices <- sample(1:n_choices, n_choices, replace = FALSE, prob = c(0.01, 0.04, 0.4, 0.05, 0.5)) 
  } else {
    choices <- sample(1:n_choices, n_choices, replace = FALSE, prob = c(0.4, 0.08, 0.12, 0.3, 0.1)) 
  }
  candidate_df[i,] <- choices     # filling in rows with sampled ranked voting from each voter
}

# -------------------------------------------------------------------------------------------------------------------- #
# ----------------------------------------- #
#
# run of simulation;
#   Rules:
#       1. After 1st choices are tallied, if no one has majority (>= 50%), 
#          then lowest polling candidate is eliminated and their second choice is distributed to that candidaate
#       2. This continues until a given candidate has >=50% rating
#
# ----------------------------------------- #
# -------------------------------------------------------------------------------------------------------------------- #

# store df into new one (so I don't have to run above code not really necessary)
new_df <- candidate_df
polling_check <- prop.table(colSums(new_df == 1))    # begin the simulation by creating a "poll check," which will see if any candidate has >= 50% polling
while(any(polling_check < 0.5)){                     # loop until someone has majority vote

  rank <- colSums(new_df == 1)         # Identify column with least number of "1" rankings
  p_rank <- prop.table(rank)           # finding proportion favoring each candidate as #1
  if(any(p_rank >= 0.5)){              # if there is a cadidate polling above >= 50%, break and print winner
    print(paste("Candidate ", names(p_rank[p_rank >= 0.5]), " is the winner!"))
    break
  } else {                                     # if not... then...
    elim_candidate_index <- which.min(p_rank)  # find candidate polling lowest to delete from df
    new_df <- new_df[,-elim_candidate_index]   # delete that candidate  from above index

    new_df <- t(apply(new_df, 1, rank))        # rank the choices left for everyone (so that if a voters first choice is eliminated, their second choice becomes 1)

    polling_check <- prop.table(colSums(new_df == 1))   # new polling check

    print(paste(polling_check))
    print(paste(names(polling_check)))

  }

}


Notably, this works, but the candidate with plurality ends up winning every time (thus the ranked choice isn't useful to this population). Any suggestion helps!!

-Brennan