mercredi 30 juin 2021

how to get random rows from mysql table without using RAND()?

i have a huge table with more then 350k records (products). I want to pick random 8 products from it but when try to use RAND() function with SQL, query got very slow. The RAND() function is too slow and consumes too much CPU.

SELECT name,deg_id,cat_image from products where status=1 order by rand() LIMIT 8

So I need alternate of RAND() function. Can someone else me to find an alternate?




how to reduce number of variables and make the code efficient

this is first time i am posting to stackoverflow

what will be the efficient way to create and use such variables

lower_chars_enabled = True
upper_chars_enabled = True
digit_chars_enabled = True
special_chars_enabled = True

this function does the job but according to me its not the most efficient way of doing this

def used_chars():
global final_chars

if lower_chars_enabled == True:
    final_chars = lower_chars

if upper_chars_enabled == True:
    final_chars = final_chars + upper_chars

if digit_chars_enabled == True:
    final_chars = final_chars + digit_chars

if special_chars_enabled == True:
    final_chars = final_chars + special_chars

looking forward for suggestions any help would be appreciated

full program code for reference

import string
import secrets

lower_chars = string.ascii_lowercase
upper_chars = string.ascii_uppercase
digit_chars = string.digits
special_chars = string.punctuation

lower_chars_enabled = True
upper_chars_enabled = True
digit_chars_enabled = True
special_chars_enabled = True
final_chars = ""

passLen = 8

def used_chars():
    global final_chars

    if lower_chars_enabled == True:
        final_chars = lower_chars

    if upper_chars_enabled == True:
        final_chars = final_chars + upper_chars

    if digit_chars_enabled == True:
        final_chars = final_chars + digit_chars

    if special_chars_enabled == True:
        final_chars = final_chars + special_chars



def generate_pass():
        password = "".join(secrets.choice(final_chars) for x in range(passLen))
        return password

used_chars()
generate_pass()

input("Waiting...")



Codechef showing wrong submission even for correct output

You are given a number N and find the sum of the first N odd and even numbers in a line separated by space. All even and odd numbers should be greater than 0.

Input: First-line will contain the number N.

Output: Print the sum of the first N odd and even numbers in a line separated by space.

Constraints 1≤N≤106 Sample Input 1: 4 Sample Output 1: 16 20 Sample Input 2: 1 Sample Output 2: 1 2

EXPLANATION: In the first example, (1 + 3 + 5 + 7) = 16 and (2 + 4 + 6 + 8) = 20. In the second example, only one odd that is 1 and only one even that is 2.

Code:

#include <iostream>
using namespace std;

int main() {
    // your code goes here
int n,ctr=0,odd=0,even=0,i=1,j=2;
cin>>n;
while(ctr<n){
    odd+=i;
    even+=j;
    i=i+2;
    j=j+2;
    ctr++;
}
cout<<odd<<" "<<even;
    return 0;
}

But it's showing wrong answer in submission.




golang rand.Int(). Why every time same values?

I have a code:

package main

import ("fmt"
    "math/rand"
    "strconv"
)

func main() {
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
    fmt.Println(strconv.Itoa(rand.Int()))
}

When I run it (go run code.go), I get every time same values:

5577006791947779410
8674665223082153551
6129484611666145821
4037200794235010051
3916589616287113937
6334824724549167320
605394647632969758
1443635317331776148
894385949183117216
2775422040480279449
4751997750760398084
7504504064263669287
1976235410884491574
3510942875414458836

Second try:

package main

import ("fmt"
        "math/rand"
        "strconv"
)

func main() {
    fmt.Println(strconv.Itoa(rand.Intn(100)))
    fmt.Println(strconv.Itoa(rand.Intn(100)))
    fmt.Println(strconv.Itoa(rand.Intn(100)))
    fmt.Println(strconv.Itoa(rand.Intn(100)))
    fmt.Println(strconv.Itoa(rand.Intn(100)))
    fmt.Println(strconv.Itoa(rand.Intn(100)))
    fmt.Println(strconv.Itoa(rand.Intn(100)))
}

Same behaviour. Every time's

81
87
47
59
81
18
25

Is this a joke? Why it happens? Here is no description about non-random same result. I can see only pseudo-random term without explanation what that means.

Looks like even bash is more logical and stable...

random




Take random samples based on two groups in r

I have data with two columns; ID and specialty. Each ID has two occurrences with unique occurrences of specialty. I would like to take random sample of data with 400 from each specialty group with 2 occurrences of ID. I have tried dplyr group with sample_n, but it turns ID with different occurrences.

data example

specialty <- c("obs", "obs", "ped", "ped", "im", "im")
ID <- c("M", "M", "K", "K", "l", "l")

My desired output if I would sample 2 per specialty is

specialty <- c("obs", "obs", "im", "im")
ID <- c("M", "M", "l", "l")

What I get is

specialty <- c("obs", "obs", "im", "im")
ID <- c("M", "M", "l", "k")



I have a working luck game console application but I need some do changes to it

in this luck game I have to write numbers at the app with console readline. So basicaly game works like this:

you can select 5 numbers from 1-34 and seperatly 1 number from 1-14. if you guess every number it will show like this 5+1, 5, 4+1, 4, 3+1,3 etc.

here is the code

int[] sayilar = new int[5] { 0, 0, 0, 0, 0 };
            int sayi;
            bool durum = false;
            Random r = new Random();
            int i = 0;
            while (i < 5)
            {
                sayi = r.Next(1, 35);
                int j = 0;
                do
                {
                    if (sayi == sayilar[j]) { durum = true; break; }
                    j++;
                }
                while (j < 5);
                if (durum == true)
                {
                    durum = false; continue;
                }
                else
                {
                    sayilar[i] = sayi; i++;
                }
            }
            Array.Sort(sayilar); 
            foreach (int a in sayilar)
                Console.Write("{0} ", a);
            Console.WriteLine("+ {0}", r.Next(1, 15));

            Console.ReadKey();

so what I want is write the numbers in application and when the winning numbers came it should show me which one is correct and correct rate like 5+1. Thank you




How do I take a random element in an array? [duplicate]

I want to take a random element from an array, is there any special function or how can I do it??? Is for a personal project, is javascript.




Should this number be subtracted by 1 when implementing the Mersenne Twister?

I found this snippet online along with this Stackoverflow post which converts it into a TypeScript class.

I basically copy and pasted it verbatim (because I am not qualified to modify this sort of cryptographic code), but I noticed that VS Code has a little underline in the very last function:

/**
 * generates a random number on [0,1) with 53-bit resolution
 */
nextNumber53(): number {
  let a = this._nextInt32() >>> 5;
  let b = this._nextInt32() >>> 6;
  
  return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}

Specifically the 9007199254740992.0

VS Code says Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers.ts(80008)

I notice that if I subtract that number by one and instead make it 9007199254740991.0, then the warning goes away. But I don't necessarily want to modify the code and break it if this is indeed a significant difference.

Basically, I am unsure, because while my intuition says that having a numerical overflow is bad, my intuition also says that I shouldn't try to fix cryptographic code that was posted in several places, as it is probably correct.

But is it? Or should this number be subtracted by one?




Vectorize sampling from a multidimensional array

I have a numpy array of shape D x N x K.

I need a resulting D x N array of random elements out of K classes, where for each index [d, n] there is a different probability vector for the classes, indicated by the third axis.

The numpy documentation for np.random.choice only allows 1D array for probabilities.

Can I vectorize this type of sampling, or do I have to use a for loop as follows:

# input_array of shape (D, N, K)
# output_array of shape (D, N)

for d in range(input_array.shape[0]):
    for n in range(input_array.shape[1]):
        probabilities = input_array[d, n]
        element = np.random.choice(K, p=probabilities)
        output_array[d, n] = element

I would have loved if there is a function such as

output_array = np.random.choice(input_array, probability_axis=-1)



Why is my random function not working? How would I look at the file the error is referring to? [closed]

I was wondering why I am getting this error message as I am unable to figure it out due to it being from a file separate from my own.

      range1 = input("Please enter the start of your random number range")
      range2 = input("Please enter the end of your random number range")
      num2Int = random.randint(range1,range2)

Error Message




How can I shuffle multiple independent data list with Excel VBA

Good afternoon!

I have multiple data set (numeric) in the same number of rows (data set per row). Those data set have equal size.
I'd like to rearrange randomly and independently the values in my different lines (=keeping the values if a same set on its original row but changing its column). I would like to keep shuffling the different lines until the sum value of each column meet some conditions. I'm used to code simple loops in VBA, but I'm blocked with my shuffling problem. Here is an example of datasets I'd like to shuffle: Example of datasets

I hope I could describe clearly what I'm trying to do.

Thank you in advance.




Counting sticks that touch red lines in Julia

I want to randomly "scatter" sticks of length 1 like shown in the diagram.
I also want to count the sticks that touched the red lines.

enter image description here

My approach was to create normalized vectors that are oriented randomly in space.
The problem is that they are all at the origin and I am also not sure how to identify and count those who touch the red lines

a = [randn(), randn()]; 
line = a/norm(a) # Normalized vector in random direction



How do I prevent negative values in my script?

Background Info

  • I have a maximum of 15 hours available for work Monday – Friday.

  • Each day, from Monday – Thursday, I will work a random amount of hours between 0 – 8.

  • I do not need to work at least 1 hour Monday – Thursday.

  • On Friday, I will work whatever hours are left from the maximum of 15 hours available.

  • I must work at least 1 hour on Friday.

Formulas Used

  • Monday: RANDBETWEEN(0-8)

  • Tuesday: RANDBETWEEN(0-8)

  • Wednesday: RANDBETWEEN(0-8)

  • Thursday: RANDBETWEEN(0-8)

  • Friday: 15 – SUM(Monday:Thursday) <- Will use A1 notation

  • Total Hours: SUM(Monday:Friday) <- Will use A1 notation

Issues

  • The Friday cell will occasionally receive a negative number of hours worked.

Example Output of Issue

Output

Current Workaround

  • Update the values generated by RANDBETWEEN by pressing ‘DEL’ on an empty cell. This forces all the values to change.

    Repeat until a positive value is received in the cell for Friday

Google Sheet Settings

Goal

Have the cells update themselves automatically IF a negative value is received in the cell for Friday

Possible Solution/Thoughts

Is there a way to force RANDBETWEEN numbers to update via a formula?

If yes, is there a way to setup a WHILE loop that will update the RANDBETWEEN values UNTIL the cell for Friday has a positive number?

Tried a script but wasn’t able to get the cells to update at all.

function randomTotal() 
{
  var Monday = SpreadsheetApp.getActiveSheet().getRange('C4');
  var Tuesday = SpreadsheetApp.getActiveSheet().getRange('D4');
  var Wednesday = SpreadsheetApp.getActiveSheet().getRange('E4');
  var Thursday = SpreadsheetApp.getActiveSheet().getRange('F4');
  var Friday = SpreadsheetApp.getActiveSheet().getRange('G4');
  
  while(Friday < 0)
  {
    newTotal(Monday,Tuesday,Wednesday,Thursday);
    Monday.getValue();
    Tuesday.getValue();
    Wednesday.getValue();
    Thursday.getValue();
    Friday.getValue();
  }
}
function newTotal( Monday,Tuesday,Wednesday,Thursday)
{
  Monday.setFormula('=RANDBETWEEN(0,8)');
  Tuesday.setFormula('=RANDBETWEEN(0,8)');
  Wednesday.setFormula('=RANDBETWEEN(0,8)');
  Thursday.setFormula('=RANDBETWEEN(0,8)');
  Friday.setFormula('15-SUM(C4:G4)');
}



multiplication game program for kids

I want to create a python programme which gives random multiplication questions to do. After each answer from the user, the programme should tell them whether they got it right or wrong and what the correct answer is. Example: Question 1: 1×3 = 3 Right! Question 2: 8×5 = 54 Wrong. The answer is 48.

What I wrote only prints the answers without the question.




why Mysql Rand() has a different behaviour while using left join

I'm trying to implement some fuzziness thing in a mysql (v5.7 on Mac & Linux) query but realized mysql Rand() has a weird behaviour while using/not using a left join with an empty table!

To reproduce this I made 2 tables, t1 with 1000 records and t2 with no record.
Then I tried to run these 2 queries:

SELECT count(*) FROM t1 LEFT JOIN t2 ON t1.id = t2.id WHERE RAND() < 0.5;
SELECT count(*) FROM t1 WHERE RAND() < 0.5;

The first query returns ~250 records but the second one returns ~500.

Couldn't find any explanation about this.
Any idea would be helpful




How to create a unique url of a wordpress page with each visit?

I have a WordPress website and I want to secure some pages from direct access. I will add the link link for example: There is a page that I wanna secure from direct access. I'll call it pageX and its URL example.com/pagex

I want to redirect visitors from pageA to pageX but the address bar the URL should not be visible as example.com/pagex, instead, it should be some random characters after example.com/. and that URL with random numbers should be accessible only once, and with every visit, there should be unique numbers in the address bar for that pageX.

just link, if you have a WooCommerce website for digital downloads, when you complete the checkout process, WooCommerce generates a unique URL for the order completion page.

Is there any WordPress plugin to get this done??




How can I add two lists having different dimensions in python?

I have a sorted list of points of intersections (x, y) as shown in the list below, named as coordinates

coordinates =[(66, 66), (132, 66), (199, 66), (266, 66), (333, 66), (399, 66), (466, 66), (533, 66)]

I have also an array with errors defined as Error = [10, 32, 12, 43, 56, 23, 21,11]

Is it possible to add every element from the Error array such that the output for the coordinates should be as follows

new_coordinates = [(66+10, 66+32), (132+32, 66+32), (199+12, 66+12), ..., (533+11, 66+11)]

Thanks for your extended help




In Netlogo, how to randomly choose an element from a list, and let this element plus one, and then create a new list?

For example, now I have a list: [0 0 0]

I want to randomly choose an element from this list, for example, randomly I choose the first element.

Then I plus it by 1.

So now the new list is [1 0 0].

My question is how to create this new list [1 0 0] in Netlogo?




Python command repeats same number in command(im learning python)

I tried to make a twitter bot to print random number but it print the same number while testing the command

import tweepy
import random
import time
import threading
import schedule



start = time.perf_counter()
while time.perf_counter() - start < 2:
    random_number = random.randint(0,10000)
    time.sleep(1.0)



def job():  
    print(random_number)  

# run the function job() every 2 seconds  
schedule.every(2).seconds.do(job)  

while True:  
    schedule.run_pending() 

What should I do in order to have random numbers?




Split string cutting off.. no idea what's going on

before I ask this question, I'd like to thank you for taking the time to review and answer it! I'm a beginner in Python and I used .split to make every word in an unorganized list into an organized list. But it seems to be cutting off some words or something, making it an incomplete list.


So the words I initially copied and pasted were formatted like so (with the line break after every word):

adorable

adventurous

aggressive

agreeable

and so on...


After typing the code:

import random
a = open("AdjList.txt.txt")
split = a.read().split()
print(split)

I get a result of :

E:\Python\Projects\TheSillyNameGenerator\Scripts\python.exe E:/Python/Projects/TheSillyNameGenerator/TheSillyNameGenerator.py ["['adorable',", "'adventurous',", "'aggressive',", "'agreeable',", "'alert',", "'alive',", "'amused',", "'angry',", "'annoyed',", "'annoying',", "'anxious',", "'arrogant',", "'ashamed',", "'attractive',", "'average',", "'awful',", "'bad'," , "'beautiful',", "'better',", "'bewildered',", "'blac", "k',", "'bloody',", "'b lue',", "'blue-eyed',", "'blushing',", "'bored',", "'brainy',", "'brave',", "'br eakable',", "'bright',", "'busy',", "'calm',", "'careful',", "'cautious',", "'ch arming',", "'cheerful',", "'clean',", "'clear',", "'clever',", "'cloudy',", "'cl umsy',", "'colorful',", "'combative'", ',', "'comfortable',", "'concerned',", "' condemned',", "'confused',", "'cooperative',", "'courageous',", "'crazy',", "'cr eepy',", "'crowded',", "'cruel',", "'curious',", "'cute',", "'dangerous',", "'da rk',", "'dead',", "'defeated',", "'defiant',", "'delightful',", "'depressed',", "'determined", "',", "'different',", "'difficult',", "'disgusted',", "'distinct' ,", "'disturbed',", "'dizzy',", "'doubtful',", "'drab',", "'dull',", "'eager',", "'easy',", "'elated',", "'elegant',", "'embarrassed',", "'enchanting',", "'enco uraging',", "'energetic',", "'enthusiastic',", "'envious',", "'evil'", ',', "'ex cited',", "'expensive',", "'exuberant',", "'fair',", "'faithful',", "'famous',", "'fancy',", "'fantastic',", "'fierce',", "'filthy',", "'fine',", "'foolish',", "'fragile',", "'frail',", "'frantic',", "'friendly',", "'frightened',", "'funny' ,", "'gentle',", "'gifted',", "'glamorous',", "'gl", "eaming',", "'glorious',", "'good',", "'gorgeous',", "'graceful',", "'grieving',", "'grotesque',", "'grumpy ',", "'handsome',", "'happy',", "'healthy',", "'helpful',", "'helpless',", "'hil arious',", "'homeless',", "'homely',", "'horrible',", "'hungry',", "'hurt',", "' ill',", "'important',", "'imp", "ossible',", "'inexpensive',", "'innocent',", "' inquisitive',", "'itchy',", "'jealous',", "'jittery',", "'jolly',", "'joyous',", "'kind',", "'lazy',", "'light',", "'lively',", "'lonely',", "'long',", "'lovely ',", "'lucky',", "'magnificent',", "'misty',", "'modern',", "'motionless',", "'m uddy',", "'", "mushy',", "'mysterious',", "'nasty',", "'naughty',", "'nervous'," , "'nice',", "'nutty',", "'obedient',", "'obnoxious',", "'odd',", "'old-fashione d',", "'open',", "'outrageous',", "'outstanding',", "'panicky',", "'perfect',", "'plain',", "'pleasant',", "'poised',", "'poor',", "'powerful',", "'pr", "ecious ',", "'prickly',", "'proud',", "'putrid',", "'puzzled',", "'quaint',", "'real'," , "'relieved',", "'repulsive',", "'rich',", "'scary',", "'selfish',", "'shiny'," , "'shy',", "'silly',", "'sleepy',", "'smiling',", "'smoggy',", "'sore',", "'spa rkling',", "'splendid',", "'spotless',", "'stormy',", "'strange',", "'stupid',", "'successful',", "'super',", "'talented',", "'tame',", "'tasty',", "'tender',", "'tense',", "'terrible',", "'thankful',", "'thoughtful',", "'thoughtless',", "' tired',", "'tough',", "'troubled',", "'ugliest',", "'ugly',", "'uninterested',", "'unsightly',", "'unusual'", ',', "'upset',", "'uptight',", "'vast',", "'victor ious',", "'vivacious',", "'wandering',", "'weary',", "'wicked',", "'wide-eyed'," , "'wild',", "'witty',", "'worried',", "'worrisome',", "'wrong',", "'zany',", "' zealous']", 'adorable', 'adventurous', 'aggressive', 'agreeable', 'alert', 'aliv e', 'amused', 'angry', 'annoyed', 'annoying', 'anxious', 'arrogant', 'ashamed', 'attractive', 'average', 'awful', 'bad', 'beautiful', 'better', 'bewildered', 'b lack', 'bloody', 'blue', 'blue-eyed', 'blushing', 'bored', 'brainy', 'brave', 'b reakable', 'bright', 'busy', 'calm', 'careful', 'cautious', 'charming', 'cheerfu l', 'clean', 'clear', 'clever', 'cloudy', 'clumsy', 'colorful', 'combative', 'co mfortable', 'concerned', 'condemned', 'confused', 'cooperative', 'courageous', ' crazy', 'creepy', 'crowded', 'cruel', 'curious', 'cute', 'dangerous', 'dark', 'd ead', 'defeated', 'defiant', 'delightful', 'depressed', 'determined', 'different ', 'difficult', 'disgusted', 'distinct', 'disturbed', 'dizzy', 'doubtful', 'drab ', 'dull', 'eager', 'easy', 'elated', 'elegant', 'embarrassed', 'enchanting', 'e ncouraging', 'energetic', 'enthusiastic', 'envious', 'evil', 'excited', 'expensi ve', 'exuberant', 'fair', 'faithful', 'famous', 'fancy', 'fantastic', 'fierce', 'filthy', 'fine', 'foolish', 'fragile', 'frail', 'frantic', 'friendly', 'frighte ned', 'funny', 'gentle', 'gifted', 'glamorous', 'gleaming', 'glorious', 'good', 'gorgeous', 'graceful', 'grieving', 'grotesque', 'grumpy', 'handsome', 'happy', 'healthy', 'helpful', 'helpless', 'hilarious', 'homeless', 'homely', 'horrible', 'hungry', 'hurt', 'ill', 'important', 'impossible', 'inexpensive', 'innocent', 'inquisitive', 'itchy', 'jealous', 'jittery', 'jolly', 'joyous', 'kind', 'lazy', 'light', 'lively', 'lonely', 'long', 'lovely', 'lucky', 'magnificent', 'misty', 'modern', 'motionless', 'muddy', 'mushy', 'mysterious', 'nasty', 'naughty', 'ne rvous', 'nice', 'nutty', 'obedient', 'obnoxious', 'odd', 'old-fashioned', 'open' , 'outrageous', 'outstanding', 'panicky', 'perfect', 'plain', 'pleasant', 'poise d', 'poor', 'powerful', 'precious', 'prickly', 'proud', 'putrid', 'puzzled', 'qu aint', 'real', 'relieved', 'repulsive', 'rich', 'scary', 'selfish', 'shiny', 'sh y', 'silly', 'sleepy', 'smiling', 'smoggy', 'sore', 'sparkling', 'splendid', 'sp otless', 'stormy', 'strange', 'stupid', 'successful', 'super', 'talented', 'tame ', 'tasty', 'tender', 'tense', 'terrible', 'thankful', 'thoughtful', 'thoughtles s', 'tired', 'tough', 'troubled', 'ugliest', 'ugly', 'uninterested', 'unsightly' , 'unusual', 'upset', 'uptight', 'vast', 'victorious', 'vivacious', 'wandering', 'weary', 'wicked', 'wide-eyed', 'wild', 'witty', 'worried', 'worrisome', 'wrong ', 'zany', 'zealous']

Process finished with exit code 0


Now if you put this into Pycharm it comes out with like half the words successfully made into complete strings and then the other half are not complete strings. * Scratching my head * Any hints?

THE FULL LIST OF THE ORIGINAL WORDS IS LINKED HERE IF YOU NEED IT FOR WHATEVER REASON https://justpaste.it/68ekf




mardi 29 juin 2021

How can I generate a random integer in RecyclerView Adapter?

I need random number in recyclerView adapter but I am unable to get any. I am trying to generate the number in the Activity.java and pass it in the constructor but I am getting same number on every item. I have tried this :

                Random random = new Random();
                randInt = random.nextInt(6);
                adapterPost = new AdapterPost(QuestionsActivity.this, postList, randInt);

//Adapter

public class AdapterPost extends RecyclerView.Adapter<AdapterPost.ViewHolder> {

Context context;
ArrayList<ModelPost> postList;
String myUid;
DatabaseReference likesRef;
DatabaseReference postRef;
boolean hasLiked = false;

int randInt;

public AdapterPost(Context context, ArrayList<ModelPost> postList, int randInt) {
    this.context = context;
    this.postList = postList;
    this.randInt = randInt;
    myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();

    likesRef = FirebaseDatabase.getInstance().getReference("Likes");
    postRef = FirebaseDatabase.getInstance().getReference("Posts");

}

Please let me know how can I get a different random number on evey item. Thanks!




How can I code a Gacha System in C# (With RNG)? [closed]

For my first actual game, I want to code a gacha system based off of RNG. For example:

  • 5 rolls have 1 silver character
  • 50 rolls guarantee a gold character
  • There will be a pity system

I wanted to get the basics in, i feel like going into detail will make it less understandable. How can I code a whole gacha system with RNG that won't drain players. I use Unity and Visual Studio.




Can This Be Done

I have an app on my Android phone that lets me put in a list of board games. Then it will randomly pick on for me to play and remove it from the list, temporarily until I have gone through the whole list. Then I click on reset. What I would like for it to do, but it doesn't so I figured I would have to make the program, list a game, but ask if I want to accept the name. If I do, it removes it from the list temporarily. But if I do not, it puts it back into the pool.

Is this possible?




Generate synthetic random image with predefined randomness

I am trying to generate circular image with two distinct colors. Currently, I can control the ratio of two colors but I want the ability to control the adjacency of the colors too. For example, if the randomness is high then the probability of getting two pixel of same color would be low. Below is my code to generate image so far:

import numpy as np 
import matplotlib.pyplot as plt

class GenerateImage:
    def __init__(self, radius=24):
        self.radius = radius
        self.image = np.zeros(shape=(48, 48, 3))
        
    def generate_random(self, prob=[0.5, 0.5]):
        mask = np.random.choice([0, 1], size=np.prod(self.image.shape[:2]), p=prob)
        mask = mask.reshape(self.image.shape[:2])
        self.image[:, :, 1] = mask * 255
        self.image[:, :, 2] = np.where(mask == 1, 0, 1) * 255
        
        x, y = np.ogrid[0:self.image.shape[0], 0:self.image.shape[1]]
        center_x = self.image.shape[0] / 2 - 0.5
        center_y = self.image.shape[1] / 2 - 0.5
        circle_mask = (x - center_x)**2 + (y - center_y)**2 > self.radius**2
        self.image[circle_mask] = [0,0,0]
        
    
    def display(self):
        plt.imshow(self.image)
        self.generate_random()
        plt.show()
        
        
        
if __name__ == '__main__':
    g = GenerateImage()
    g.generate_random(prob=[0.5, 0.5])
    g.display()

It produces images like:

enter image description here

There are linear patches of blue or green colors that I want to control. What would be a reasonable way to achieve that? Thanks.

Another question (if anyone knows): how to compute the entropy of a colored image (I can use skimage to find entropy of a grayscale image but couldn't find any resource to do that for colored images like the one above)




Randomize results onload React

i'm trying to randomize the results I receive from the API everytime I refresh the page. I´m a little bit stuck in which way to set up the onload.

This is my code

  handleRandom = (e) => {
    this.getMarvelResponse(null, null, e);
  };
  componentDidMount() {
    const random = Math.floor(Math.random() * 1473);
    this.getMarvelResponse(null, null, this.state.offset);
    onload = () => {this.handleRandom(random)}
  }

  getMarvelResponse = (id, name, offset) => {
    getCharacters({
      id: id,
      name: name,
      offset: offset,
    }).then(({ characters }) => {
      this.setState(
        {
          characters: characters.filter(
            (chr) => !chr.thumbnail.path.match(imageFound)
          ),      

          selectedCard: null,
          offset: offset,
          name: name,
        },
        () => {
          console.log(this.state.characters);
        }
      );
    });



R Generate random binary vector of fixed length with fixed sum

Quick question: In R, how to generate a random binary vector of fixed length with fixed sum.

For example:

I want a binary vector of length 100 that sum up to 15.

Thanks!




Monty Hall game coded in python, likelihood of winning after switching doors

There are probably similar threads already here, but anyways: First I created a working Monty Hall game in python:

You have 3 doors, pick one. If you find a goat (I wrote "poo"), you'll simply lose the game. If you don't choose the poodoor, you will be represented with a choice to change the door. It is argued that you have 2/3 chance of winning, if you choose to change. There is even a vsauce video about this..

So after the game worked, I created random inputs to the code and made the whole thing into a for loop, which adds to list the results: whether you chose to change or not, and if you won or not.

Regardless how how many times I run the loop, I get exactly 50/50 result with minor changes. Did I do my code wrong, or is the argument of 2/3 chance wrong?

If the subject interests you and/or if you know the answer to this, please comment! :) Comments on the code itself welcome too!

Thank you!

-Deep Man

Code1

Code2

Code3

Code4

EDIT: CONSOLE: Console

"""Monty hall testing deep_man"""

import random

def win_or_lose(choose, moneylist, choiselist):
    #automated change or not
    changeornot_autom = 0
    wonorlost = 0
    if choiselist [choose] == moneylist [choose]:
        # IF user chooses a poopdoor
        wonorlost = 0
        changevar = 0

    else:
        #IF user does not choose a poopdoor
        #make choiselist 1 become 2, now we search for money
        for loop in range(0, 3):
            if choiselist [loop] == 1:
                choiselist [loop] += 1
                changevar = 0
                break
            else:
                continue
        # IF user chooses the winning door:
        if choiselist [choose] == moneylist [choose]:
            for loop in range(0, 3):
                if moneylist [loop] == 1:
                    door = loop + 1
                    print(f"There was poop behind door: {door},"
                          f" Do you want to change to the unknown door? "
                          f"0 = no, 1 = yes: ")
                    changevar = random.randint(0, 1)
                else:
                    continue
            if changevar == 1:
                wonorlost = 1
            elif changevar == 0:
                wonorlost = 2
            else:
                wonorlost = -1
        #IF user chooses empty door
        else:
            for loop in range(0, 3):
                if moneylist [loop] == 1:
                    door = loop + 1
                    print(f"There was poop behind door: {door},"
                          f" Do you want to change to the unknown door?"
                          f" 0 = no, 1 = yes: ")
                    changevar = random.randint(0, 1)
                else:
                    continue
            if changevar == 1:
                wonorlost = 2
            elif changevar == 0:
                wonorlost = 1
            else:
                wonorlost = -1

    #Create a list of results
    wonorlost_and_changevar = [0, 0]
    wonorlost_and_changevar [0] = wonorlost
    wonorlost_and_changevar [1] = changevar
    return wonorlost_and_changevar


def moneyorpoop(moneylist):
    #What door has money, and what door has poo
    if moneylist == [0, 0, 2]:
        random_number = get_random_number(1)
        if random_number == 0:
            moneylist[random_number] += 1
        else:
            moneylist[random_number] += 1
    elif moneylist == [0, 2, 0]:
        random_number = get_random_number(1)
        if random_number == 0:
            moneylist[random_number] += 1
        else:
            moneylist[2] += 1
    else:
        random_number = get_random_number(1)
        if random_number == 0:
            moneylist[1] += 1
        else:
            moneylist[2] += 1
    return moneylist

def get_random_number(moneyorpoop):
    #Get the random number
    result = random.randint(0, moneyorpoop)
    return result

def main():
    switched_lost_won = [0, 0, 0]
    notswitched_lost_won = [0, 0, 0]

    # print instructions
    print("You have 3 doors. One door has poop behind it, one has money" \
          " behind it, third door has nothing behind it.")
    print("After your choise, the door which has poop behind it will be" \
          " revealed, and you will be presented")
    print("with a choise to change your choise to the remainind door")
    print("")

    for programloop in range(0, 1001):
        print("loop", programloop)
        doorlist = [0, 1, 2]
        #moneylist "2" means money, "1" means poop
        moneylist = [0, 0, 0]
        #choiselist "1" will be user choise
        choiselist = [0, 0, 0]
        choose = 0
        chosenvar = 0

        while chosenvar == 0:
            print("Choose a door: 1, 2, or 3: ")
            choose = random.randint(1, 3)
            if choose <= 3 and choose > 0:
                print("You chose", choose)
                choose -= 1
                choiselist [choose] += 1
                chosenvar += 1
            else:
                #Remnant of input based code
                print("You need to input a number between 1 and 3.")

        random_number = get_random_number(2)
        #add money behind the random door
        moneylist[random_number] += 2
        #add poop behind random door
        moneylist = moneyorpoop(moneylist)

        wonorlost_and_changevar = win_or_lose(choose, moneylist, choiselist)

        #wonorlost 2 = won, 1 = lost, 0 = poop, -1 = error
        #extract variables from list
        wonorlost = wonorlost_and_changevar [0]
        changevar = wonorlost_and_changevar [1]

        #print for debugging reasons
        print(changevar, wonorlost)

        #win or lose prints
        if wonorlost == -1:
            print("ERROR! Choose between 0 and 1 next time!")
        elif wonorlost == 0:
            print("You found poop. YOU LOSE!")
        elif wonorlost == 1:
            print("YOU LOSE!")
        else:
            print("YOU WIN!")

        #switched and lost won list
        if changevar == 1:
            switched_lost_won [0] += 1
            if wonorlost == 1:
                switched_lost_won[1] += 1
            elif wonorlost == 2:
                switched_lost_won[2] += 1
        #NOTswitched and lost won list
        if changevar == 0 and wonorlost != 0:
            notswitched_lost_won[0] += 1
            if wonorlost == 1:
                notswitched_lost_won[1] += 1
            elif wonorlost == 2:
                notswitched_lost_won[2] += 1

        print("Switched; Lost; Won")
        print(switched_lost_won)
        print("NOT switched; Lost; Won")
        print(notswitched_lost_won)
        print("")
        print("-------------------------------------------------------------")


    #After the programloop
    print("")
    print("Final Switched, lost, won", switched_lost_won)
    print("Final NOT switched, lost, won", notswitched_lost_won)

    print("Likelihood of winning IF SWITCHED:")
    likelyhood = switched_lost_won [2] / switched_lost_won [0]
    print(f"{likelyhood:.2f}")


if __name__ == "__main__":
    main()



SQL query with rand select

Please, can I have some help with a MySQL query? I have a list of 18 entries in a table with each a corresponding group, there are 6x groups. My requirement is to randomly pick 6 entries from that table and only take one entry per group.

Here is my current query, but the problem with this is it is not taking only 1 entry per group, I am getting 2 results for group 3 returned for example.

SELECT mask,group_id, icon, infoText FROM table_name ORDER BY RAND() LIMIT 6;

Current output when running above query, as you can see 2x results for group 1 are returned.

mask group_id icon infoText
2 1 dot blaba
7 1 dot blaba2
6 2 dot blaba3
4 3 dot blaba4
9 4 dot blaba5
10 5 dot blaba6

When I want it to something like this instead, when a random mask is selected but only 1 entry from that group

mask group_id icon infoText
1 1 dot blaba
2 2 dot blaba2
6 3 dot blaba3
3 4 dot blaba4
5 5 dot blaba5
12 6 dot blaba6



Randomly change logo background every time in PIL [closed]

I have written code to make a logo in my Telegram bot.

I want to add a random background when anybody makes a logo. Basically, work like this bot: https://t.me/Yone_Robot (command /logo <text>). But my code is not working. It changes the background every time I redeploy the bot.

My code:

import random

Listimg = ["img1", "img2"]
Randimg = random.choice(Listimg)
D = f".SheebaQueen/img/{Randimg}.jpg"

The bot is written in Python.




One-liner for generating natural language looking words [closed]

When teaching computing science, I sometimes need to create arbitrary samples of data for demonstrating various algorithms, for instance sorting algorithms.

I would like to get an easy way of generating lists of (random word, random value). If I need ~10 such tuples, I can hardcode (names, value) tuples. But if I need ~50 such tuples, I can't do that.

I tried using ad-hoc function generating alternate vowel and consonant string, but I noticed that many students would focus on this function rather than on the main algorithm, asking what is the purpose of such or such line of code, and spending most of the time on that ad-hoc function.

I don't encounter such an issue when importing some function because the module is like a black box for them.

Thus I wonder if you could figure out some module in standard Anaconda distributions (students should not have to install anything more) that could lead to an easy to type one-liner such as

from XXX import YYY
from random import random, randrange
L = [ ( YYY(random()), randrange(0, 100)) for _ in range(50) ]

where YYY(random()) or any other syntax would result in some more or less natural language sounding string.

I don't ask for existing words, since I usually claim they are some names of people, but I would rather get tabati than xwyaer. Of course, if you are aware of some hidden gem in scipy containing hardcoded names of towns or whatever, it would be great.

Any idea?




R: Select a random samples of the same length from a list of time series

I am looking for a way to randomly select intervals equal length from time series data from the following time series. Everything I found so far, either did not have the option to randomly select intervals (but only single values) or does only have the option to specifically select a certain range of data points that should be selected. Perhaps someone has a good solution to randomly select intervals of 100 consecutive data points from the following list:

x = seq(1, 1000, 1)
y = seq(1, 1000, 0.5)
z = seq(1, 2000, 1)
w = seq(1, 2000, 2)
list1 = list(x, y, z, w)

I appreciate any help!

Best, Johnson




lundi 28 juin 2021

How do I create random between 10 and 0(o and 10 not included)?

//This line of code gives random above 10 and under 20
    int randomResult =  random.nextInt(10-0 )+10 ;
    //This always gives 0
    int random result = random.nextInt(10-0);

What do I do? can you help?




why using rand() without setting seed with srand() some numbers change?

I'm generating random numbers with rand() bounded to 1000 with this little piece of code:

for(int i=0;i<pARRAYSIZE;i++) pARRAY[i] = rand()%MAX_VALUE_DATA;

(I'm NOT using srand() function, so by default seed would be 1? [1])

Sometimes I get this sequence:

362 , 27 , 690 , 59 , 763 , 926 , 540 , 426 , 172 , 736 , 211 , 368 , 567 , 429 , 782 , 530 , 862 , 123 , 67 , 135 , 929 , 802 , 22 , 58 , 69 , 167 , 393 , 456 , 11 , 42 , 229 , 373 , 421 , 919 , 784 , 537 , 198 , 324 , 315 , 370 , 413 , 526 , 91 , 980 , 956 , 873 , 862 , 170 , 996 , 281 , 305 , 925 , 84 , 327 , 336 , 505 , 846 , 729 , 313 , 857 , 124 , 895 , 582 , 545 , ...

And sometimes I get this other sequence:

27 , 690 , 59 , 763 , 926 , 540 , 426 , 172 , 736 , 211 , 368 , 567 , 429 , 782 , 530 , 862 , 123 , 67 , 135 , 929 , 802 , 22 , 58 , 69 , 167 , 393 , 456 , 11 , 42 , 229 , 373 , 421 , 919 , 784 , 537 , 198 , 324 , 315 , 370 , 413 , 526 , 91 , 980 , 956 , 873 , 862 , 170 , 996 , 281 , 305 , 925 , 84 , 327 , 336 , 505 , 846 , 729 , 313 , 857 , 124 , 895 , 582 , 545 , 814 , ...

Which is the same as the first one but with 362 at the start (the real squence have a size of 1024 numbers, when 362 don't exist it generates a 871 in a fixed position of the array to complete the 1024 numbers).

And in a relly few cases it generates this other sequence which is the second one without 27, 690 and 59:

763 , 926 , 540 , 426 , 172 , 736 , 211 , 368 , 567 , 429 , 782 , 530 , 862 , 123 , 67 , 135 , 929 , 802 , 22 , 58 , 69 , 167 , 393 , 456 , 11 , 42 , 229 , 373 , 421 , 919 , 784 , 537 , 198 , 324 , 315 , 370 , 413 , 526 , 91 , 980 , 956 , 873 , 862 , 170 , 996 , 281 , 305 , 925 , 84 , 327 , 336 , 505 , 846 , 729 , 313 , 857 , 124 , 895 , 582 , 545 , 814 , 367 , 434 , 364 , ...

[1] Some test I did: if I force the seed to be 1 with srand(1) I always get the following sequence:

383 , 886 , 777 , 915 , 793 , 335 , 386 , 492 , 649 , 421 , 362 , 27 , 690 , 59 , 763 , 926 , 540 , 426 , 172 , 736 , 211 , 368 , 567 , 429 , 782 , 530 , 862 , 123 , 67 , 135 , 929 , 802 , 22 , 58 , 69 , 167 , 393 , 456 , 11 , 42 , 229 , 373 , 421 , 919 , 784 , 537 , 198 , 324 , 315 , 370 , 413 , 526 , 91 , 980 , 956 , 873 , 862 , 170 , 996 , 281 , 305 , 925 , 84 , 327 , ...

Edit: without using srand() I got a new sequence, which is similar to the second one but without 27...

690 , 59 , 763 , 926 , 540 , 426 , 172 , 736 , 211 , 368 , 567 , 429 , 782 , 530 , 862 , 123 , 67 , 135 , 929 , 802 , 22 , 58 , 69 , 167 , 393 , 456 , 11 , 42 , 229 , 373 , 421 , 919 , 784 , 537 , 198 , 324 , 315 , 370 , 413 , 526 , 91 , 980 , 956 , 873 , 862 , 170 , 996 , 281 , 305 , 925 , 84 , 327 , 336 , 505 , 846 , 729 , 313 , 857 , 124 , 895 , 582 , 545 , 814 , 367 , ...

Code:

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

void initVector(int *pARRAY, int pARRAYSIZE) {
    for(int i=0;i<pARRAYSIZE;i++) pARRAY[i] = rand()%1000;
}

int main(int argc, char** argv){
    int rank, nrProcesos;

    MPI_Init(&argc, &argv); 
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    MPI_Comm_size(MPI_COMM_WORLD,&nrProcesos); 

    int *E = (int*) malloc(sizeof(int) * 1024);

    if (rank==0)
    {
        //srand(1);
        initVector(E, 1024);
    }

    #ifdef DEBUG
        if(rank == 0){
            for(int i=0;i<1024;i++){
                if(i%8==0) printf("\n");
                printf("%-4d, ", E[i]);
            } printf("\n");
        }
    #endif //DEBUG

    MPI_Finalize(); 
    return(0); 
}

mpicc -DDEBUG -o stackoverflow stackoverflow.c mpirun --bind-to none -np 4 stackoverflow




Can I create a List of functions in python?

I am trying to create a list of functions in my program in order to use the random module to randomly choose. in theory it look and work with this

import random

def test1():
  print("1st function")

def test2():
  print("2nd function")

def test3():
  print("3rd function")

def test_func():
  test_list = [test1(), test2(), test3()]
  apple = random.choice(test_list)
  return print(apple)

test_func()

the result of this is it prints out test_list and prints "NONE" for apple is there a way to get it to randomly pick a function and only print that function.




propability in php using random and range

I want to have a probability for a range of numbers to show less and others to show more. I had a JS code that works fine but I want to convert my code to php. I want to move to server-side. The idea of the code is that I will have a random number between 0 and 10000. I want for example the number from 0 t0 4 to have 0.05 probability.

This is my Old JS Code:

     function getRandomInt(max) {
            return Math.floor(Math.random() * max);
        }
        function range(start, end) {
            return Array(end - start + 1).fill().map((_, idx) => start + idx)
        }
        
        var randomVal = getRandomInt(10000);
            console.log(randomVal);

            var p1 = range(0, 4);//0.0005
            var p2 = range(5, 9);//0.0005
            var p3 = range(10, 19);//0.001
            var p4 = range(20, 519);//0.05
            var p5 = range(520, 1019);//0.05
            var p6 = range(1020, 1519);//0.05
            var p7 = range(1520, 2019);//0.05
            var p8 = range(2020, 3319);//0.13
            var p9 = range(3320, 4919);//0.16
            var p10 = range(4920, 6519);//0.16
            var p11 = range(6520, 8199);//0.168
            var p12 = range(8200, 9999);//0.18


            var stopAt;


            if (p1.includes(randomVal)) {
                console.log("in p1");
                stopAt = 20;
                
            }
            if (p2.includes(randomVal)) {
                console.log("in p2");
                stopAt = 50;
            }
            if (p3.includes(randomVal)) {
                console.log("in p3");
                stopAt = 70;
            }
            if (p4.includes(randomVal)) {
                console.log("in p4");
                stopAt = 80;
            }
            if (p5.includes(randomVal)) {
                console.log("in p5");
                stopAt = 135;
            }
            if (p6.includes(randomVal)) {
                console.log("in p6");
                stopAt = 165;
            }
            if (p7.includes(randomVal)) {
                console.log("in p7");
                stopAt = 190;
            }
            if (p8.includes(randomVal)) {
                console.log("in p8");
                stopAt = 230;

            }
            if (p9.includes(randomVal)) {
                console.log("in p9");
                stopAt = 265;
            }
            if (p10.includes(randomVal)) {
                console.log("in p10");
                stopAt = 292;
            }
            if (p11.includes(randomVal)) {
                console.log("in p11");
                stopAt = 320;
            }
            if (p11.includes(randomVal)) {
                console.log("in p12");
                stopAt = 350;
            }

I tried doing it this way in PHP. Its works but it gives random with the probability which I want

PHP:

$randomVal =rand(0,10000);
           

            floor($randomVal);
            
            $stopAt;


            if (in_array($randomVal,range(0, 4))) {
                //echo "p1";
                $stopAt = 20;
                
            }
            if (in_array($randomVal,range(5,9))) {
                //echo "p2";
                $stopAt = 50;
            }
            if (in_array($randomVal,range(10,19))) {
                //echo "p3";
                $stopAt = 70;
            }
            if (in_array($randomVal,range(20,519))) {
                //echo "p4";
                $stopAt = 80;
            }
            if (in_array($randomVal,range(520,1019))) {
                //echo "p5";
                $stopAt = 135;
            }
            if (in_array($randomVal,range(1020,1519))) {
                //echo "p6";
                $stopAt = 165;
            }
            if (in_array($randomVal,range(1520,2019))) {
                //echo "p7";
                $stopAt = 190;
            }
            if (in_array($randomVal,range(2020,3319))) {
                //echo "p8";
                $stopAt = 230;

            }
            if (in_array($randomVal,range(3320,4919))) {
                //echo "p9";
                $stopAt = 265;
            }
            if (in_array($randomVal,range(4920,6519))) {
                //echo "p10";
                $stopAt = 292;
            }
            if (in_array($randomVal,range(6520, 8199))) {
                //echo "p11";
                $stopAt = 320;
            }
            if (in_array($randomVal,range(8200, 9999))) {
                //echo 'p12';
                $stopAt = 350;
            }

I Also Searched and found a code but my PHP knowledge isn't that great so I didn't know how I can do it with my code

This is the code:

$weightedValues=array( 20 => 0.05, 50 => 0.05, 70 => 0.10, 80 => 5, 135 => 5, 165 => 5, 190=>5, 230 =>13, 265 =>16, 292 => 16, 320 => 16.8, 350 => 18);
function getRandomWeightedElement(array $weightedValues) {
    $rand = mt_rand(1, (int) array_sum($weightedValues));

    foreach ($weightedValues as $key => $value) {
      $rand -= $value;
      if ($rand <= 0) {
        return $key;
      }
        else{
            echo $rand;
        }
    }
  }



GMP random generator in C

I wanted to generate in do-while loop random number from range [1;10000000000000000000000]. I'm looking for simple and fast way.

I created

    #define n 10000000000000000000001
    
    mpz_init(n);
    
    gmp_randinit_mt(state);
    gmp_randseed_ui(state, 100000U);
    
    int main()
    {
    
   do{
    mpz_urandomm(r, state, n);
    
    gmp_printf("Number: %Zd\n",r)
    gmp_lib.gmp_randclear(state);
    gmp_lib.mpz_clears(r, n, null);
    
    }while(1)

}

I don't understand what should be state equal to. I've chosen mpz_urandomm() due to the end of range equal to n-1.




GMP generating large random number [closed]

I wanted to generate in do-while loop random number from range [1;10000000000000000000000]. I'm looking for simple and fast way. Thank you for solution.




I need help generating random sku code in php language

I have this function but can't get the output like this. Please help me to get this result RMXZ-MIGX-DYUJ-YVJM

function randomString()
{
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randstring = '';
    for ($i = 0; $i < 10; $i++) {
        $randstring = $characters[rand(0, strlen($characters))];
    }
    return $randstring;
}
echo randomString(); // output: A or B or ....Z

Thank you very much




Javascript random items from array without repeat on same position (Loops)

I have this array:

var colors = new Array("RED", "BLUE", "WHITE", "BLACK", "LIME", "YELLOW");

and I need select with LOOP function, (e.g. five times) random items but without repeating the items in the same position:

red, blue, white, black, lime, yellow - is ok

blue, white, lime, red, yellow, black - is ok

white,black, red, lime, red, yellow - is not ok, yellow is in the same position as before ... etc...

Can you help me?




How can I take random variables from Array in flutter

I am new to flutter. I have one String Array and it has 20 values. However, I want to take 12 random values from this array and create a new array with this values. Can you show me the way?




Generate random numbers for grid flat-list in react native

I need to make a grid in which on click a number will pop up, each time I click number should be random,

How could I create that random number.

I was making a flat-list and its data is only way i could pass to the react native flat-list and display it. But I'm unable to code it well




Duplicated values from Enum (rock paper scissors)

I'm trying to make a rock, paper, scissors application through C#. This part is supposed to pick a random value from enum (rock/paper/scissors), and it does the job but it picks random value twice. What is the problem?

Random random = new Random();
Type type = typeof(ComInput);

Array values = type.GetEnumValues();
//Array values = Enum.GetValues(type):

for (int i = 0; i < 2; ++i)
{
    int index = random.Next(values.Length);
    ComInput value = (ComInput)values.GetValue(index);

    Console.WriteLine("제 선택은");
    //Console.ReadLine();
    Console.WriteLine(value);
}



So I made list of words in text document and it's updating after button is pressed. Words are displayed randomly

So this code is made with python and kivy. Problem is that sometimes words may appear more than once. Basically, it's repeating some words. The goal is that I don't want to repeat a single specific word more than once. Here's my python code:

file = open("words.txt", "r", encoding="utf8")
file = file.read()

individual_words = file.split()
random_number = randint(0, len(individual_words))
self.ids.words_areva.text = str(individual_words[random_number])



dimanche 27 juin 2021

Getting the average on random grades

Does anyone know how to get the average of the random grades? She wants to generate just random grades and get the average but I had also done one where you input the grades on your end but I don't think that's what she was looking for.

import random

grade = random.randint(50,100)
grade2 = random.randint(50,100)
grade3 = random.randint(50,100)
grade4 = random.randint(50,100)
grade5 = random.randint(50,100)

if int(grade) >= 90 and int(grade) <= 100:
  print ("Grade 1:", grade, "A")
elif int(grade) >= 80 and int(grade) <=90:
  print("Grade 1:", grade, "B")
elif int(grade) >= 70 and int(grade) <= 80:
  print("Grade 1:", grade, "C")
elif int(grade) > 60 and int(grade) <=70:
  print("Grade 1:", grade,"D")
elif int(grade) <= 60:
  print("Grade 1:", grade, "F")
if int(grade2) >= 90 and int(grade2) <= 100:
  print ("Grade 2:", grade2, "A")
elif int(grade2) >= 80 and int(grade2) <=90:
  print("Grade 2:", grade2, "B")
elif int(grade2) >= 70 and int(grade2) <= 80:
  print("Grade 2:", grade2, "C")
elif int(grade2) > 60 and int(grade2) <=70:
  print("Grade 2:", grade2,"D")
elif int(grade2) <= 60:
  print("Grade 2:", grade2, "F")
if int(grade3) >= 90 and int(grade3) <= 100:
  print ("Grade 3:", grade3, "A")
elif int(grade3) >= 80 and int(grade3) <=90:
  print("Grade 3:", grade3, "B")
elif int(grade3) >= 70 and int(grade3) <= 80:
  print("Grade 3:", grade3, "C")
elif int(grade3) > 60 and int(grade3) <=70:
  print("Grade 3:", grade3,"D")
elif int(grade3) <= 60:
  print("Grade 3:", grade3, "F")
if int(grade4) >= 90 and int(grade4) <= 100:
  print ("Grade 4:", grade4, "A")
elif int(grade4) >= 80 and int(grade4) <=90:
  print("Grade 4:", grade4, "B")
elif int(grade4) >= 70 and int(grade4) <= 80:
  print("Grade 4:", grade, "C")
elif int(grade4) > 60 and int(grade4) <=70:
  print("Grade 4:", grade4,"D")
elif int(grade4) <= 60:
  print("Grade 4:", grade4, "F")
if int(grade5) >= 90 and int(grade5) <= 100:
  print ("Grade 5:", grade5, "A")
elif int(grade5) >= 80 and int(grade5) <=90:
  print("Grade 5:", grade5, "B")
elif int(grade5) >= 70 and int(grade5) <= 80:
  print("Grade 5:", grade5, "C")
elif int(grade5) > 60 and int(grade5) <=70:
  print("Grade 5:", grade5,"D")
elif int(grade5) <= 60:
  print("Grade 5:", grade5, "F")



Create a competitive guessing game between two players in OOP

I'm new to Java and I create a number guessing game to practice the concept of object-oriented programming, but I am not sure if I am doing it correctly.

The objective of the game is a competitive guessing game between two players where each player will get 3 turns each and I want to set on 5 rounds of the game will have. The one with the most correct guesses wins. Players will need to guess a number between 1 to 10. I give some hints for the guesses by indicating if they are getting too high or getting too low. Player 1 will always be the first to go, whoever wins in the first round will be the first player in the next round. Keep track of the number of wins for each player as well as their name and display which player is the winner for each round and who is the grand winner or draw.

I bet there are some errors especially in the Player class and TwoPlayer class? How can I improve my code?

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

public class Game {
    private Scanner input;
    private Player player;
    private GuessNumberGame guessNumberGame;
    private boolean running;
    private String command;
    private TwoPlayer twoplayer;

    Game() {
        this.player = new Player();
        this.input = new Scanner(System.in);
        this.guessNumberGame = new GuessNumberGame(10);
        this.running = true;
        this.twoplayer = new TwoPlayer();
    }

    public void init() {
        while (running) {
            System.out.println("Commands: Play or Stop?");
            System.out.print(">>");
            this.command = this.input.next();

            if (this.command.equals("stop")) {
                this.running = false;
            } else if (command.equals("play")) {
                this.player.play(this.input, this.guessNumberGame);
                this.guessNumberGame.setSecretNumber(10);

            } else {
                System.out.println("unknown command");
            }
        }
    }
    public class GuessNumberGame {
      private int secretNumber;
      private Random random;

    GuessNumberGame(int limit) {
        this.random = new Random();
        this.setSecretNumber(limit);
    }

    public void setSecretNumber(int limit) {
        this.secretNumber = this.random.nextInt(limit);
    }

    public int getSecretNumber() {
        return this.secretNumber;
    }
}
    public class TwoPlayer {
      private String name;
      private int playerGuess;
      
      public void setName(String name){
        this.name = name;
      }
      public String getName(){
        return this.name;
      }
      public void setplayerGuess(int playerGuess){
        this.playerGuess = playerGuess;
      }
      public int getplayerGuess(){
        return this.playerGuess;
      }
    }
      
    public class Player {
      public void play(Scanner input, GuessNumberGame game) {
        //create 2 players to play
        Player p1 = new Player();
        Player p2 = new Player();
        
        int tries = 3;
        int number = 0;
        int round = 5;
        int draws = 0;
        int playerOneRound = 0;
        int playerTwoRound = 0;
        
       
        System.out.print("Enter Player 1 name:");
        String p1Name = input.next();
        twoplayer.setName(p1Name);
        
        System.out.print("Enter Player 2 name:");
        String p2Name = input.next();
        twoplayer.setName(p2Name);
        
        
        for (int j = 0; j < round; j++){
          for (int i = 0; i < tries; i++) {
            System.out.println("Enter your guess number Player 1: ");
            number1 = Integer.parseInt(input.next());
            System.out.println("Enter your guess number Player 2: ");
            number2 = Integer.parseInt(input.next());
            if (number1 > game.getSecretNumber()) {
              System.out.println("Player 1 guess is too high.");
              tries--;
              System.out.print(" Player 1 has "+tries+" left.");
            }
            else if (number1 < game.getSecretNumber()) {
              System.out.println("Player 1 guess is too low.");
              tries--;
              System.out.print(" Player 1 has "+tries+" left.");
            }
            if (number2 > game.getSecretNumber()) {
              System.out.println("Player 2 guess is too high.");
              tries--;
              System.out.print(" Player 2 has "+tries+" left.");
            }
            else if (number2 < game.getSecretNumber()) {
              System.out.println("Player 2 guess is too low.");
              tries--;
              System.out.print(" Player 2 has "+tries+" left.");
            }
            else {
              break;
            }
          }
        
        if (number1 == game.getSecretNumber()) {
          playerOneRound++;
          System.out.println("Congratulations Player 1! You got it right.");
          round--;
            System.out.println("You have "+round+" game(s) left.");
        }
        else if (number2 == game.getSecretNumber()){
          playerTwoRound++;
          System.out.println("Congratulations Player 2! You got it right.");
          round--;
          System.out.println("You have "+round+" game(s) left.");
        }
        else if (number1 == game.getSecretNumber() && number2 == game.getSecretNumber()){
          System.out.println("Congratulations Player 1 and Player 2! You both got it draw.");
          round--;
          draws++;
          System.out.println("You have "+round+" game(s) left.");
        }
        else{
          round--;
          System.out.println("The number I was thinking of is "+game.getSecretNumber());
        }
    }
        System.out.println("--------RESULT----------");
        
        System.out.println(p1Name+" WON "+playerOneRound+" GAMES!");
        System.out.println(p2Name+" WON "+playerTwoRound" GAMES!");
        System.outprintln("DRAWS - "+draws);
        
        System.out.println();
  
        if (playerOneCounter > playerTwoCounter) {
          System.out.println("Congratulatons to you "+p1Name+"! You Win");
        } 
        else if(playerOneCounter < playerTwoCounter) {
          System.out.println("Congratulatons to you "+p2Name+"! You Win");
        }
        else {
          System.out.println("It was a Draw!");
        }
}
    }
}

And I have a TestGame where I have the main() method which starts the game.

  public static void main(String[] args){
    Game game = new Game();
    game.init();
  }
}



samedi 26 juin 2021

GMP generating random number in C

I wanted to generate random number called r in loop using gmp library. Then I add this random number r to the variable l. I prefer range of random r between 1 and 1000000.

int main()
{

do
{

   mpz_add_ui(l,l,r)

}while(1)

   return 0;

}

I think I should use function mpz_urandomb() but I don't know how to implement it.

Thank you for your help.




Java Quiz Wih Random Questions [closed]

I have to make a random question generator in Java for school, but I have no idea how to implement not generating questions that haven't been already asked.




random output from random variable discord.py

here's the current code:

@client.command()
async def randousername(ctx):
    Letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    Numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']

    randomLetter = random.choice(Letters)
    randomNumber = random.choice(Numbers)
    RandomRandom = random.choice('RandomLetter', 'RandomNumber')
    print(RandomRandom, RandomRandom)

now im gonna explain what I'm trying to do with it:

I'm trying to give a random output of numbers and letters. To make it fully random, I wanna make the randomNumber and randomLetter's positions in the output also be random.

another explanation: Let's say that I print(randomNumber,randomLetter), and this printed "2o". the code will never be able to print "o2", since the random number is placed before the random letter.

how would I be able to make that happen?




(Haskell) gi-gtk setting image in button callback

Hi Im actually terrible at Haskell Programming and even though I know what a Monad is Im unable to apply the concept properly

I followed a tutorial on creating a basic Gi-Gtk application. Now I want to react to a button press by setting the source of an Image to a String which I randomly choose from a constant List of Strings:

{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where

import Data.GI.Base
import System.Random 
import qualified GI.Gtk as Gtk
import Control.Monad.Random

akkorde = ["C11.png","C13.png","C69.png","C6.png","C7#11.png","C7#9.png","C7b13.png","C7b9.png","C7.png","C9.png","Cadd9.png","Cj7.png"]

selectAcc:: (MonadRandom m) => m [Char]
selectAcc = do 
  let n = length akkorde  
  i <- getRandomR (0, n-1)
  return (akkorde !! i)
main :: IO ()
main = do 
  name <- selectAcc
  Gtk.init Nothing
  win <- Gtk.windowNew Gtk.WindowTypeToplevel
  Gtk.windowSetTitle win "accordtrainer"
  Gtk.onWidgetDestroy win Gtk.mainQuit
  #resize win 640 480
  
  img <- Gtk.imageNewFromFile ("../" ++ name)   
  box <- new Gtk.Box [#orientation := Gtk.OrientationVertical ]
  #add box img
  #add win box
    
  msg <- new Gtk.Label[#label := ( "")]
  #packStart box msg True False 10
 
  btn <- new Gtk.Button [#label := "Click me!"]
  #packStart box btn False False 10
  on btn #clicked ( Gtk.imageSetFromFile img  (do { name <- selectAcc; return ("../" ++ name) }))
  Gtk.widgetShowAll win
  Gtk.main

the Problem arises at the line

  on btn #clicked ( Gtk.imageSetFromFile img  (do { name <- selectAcc; return ("../" ++ name) }))

I think Gtk.imageSetFromFile expects a Maybe[Char] but currently its only getting [Char] ghc says:

app/Main.hs:38:62: error:
    • No instance for (MonadRandom Maybe)
        arising from a use of ‘selectAcc’

the Just constructor should give me a maybe type

  on btn #clicked ( Gtk.imageSetFromFile img  (Just(do { name <- selectAcc; return ("../" ++ name) })))

but then I get a type missmatch

• Couldn't match type ‘[Char]’ with ‘Char’
  Expected type: Maybe [Char]
    Actual type: Maybe [[Char]]

the chain of errors/"fixes" continues

I think Im doing something fundamentally wrong but I dont know how to do this the "correct" way if you know how I should write this line or a better way to get to the randomly selected string please respond




Python: fastest way to sample a minimum amount of sets from a set of sets that has the largest union?

Given a set of unique sets, I want to sample a minimum amount of sets that has the union of the largest union, i.e., the universe. As an example, let's say we have a set of 20 random sets of integers with different sizes ranging from 1 to 10:

import random

random.seed(99)
length = 20
ss = {frozenset(random.sample(range(100), random.randint(1,10))) for _ in range(length)}
assert len(ss) == 20 # This might be smaller than 20 if frozensets are not all unique

The largest union (universe) is given by

universe = frozenset().union(*ss)
print(universe)

# frozenset({0, 6, 7, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 
#            26, 27, 29, 31, 32, 34, 37, 39, 40, 42, 43, 45, 46, 47, 48, 49, 
#            51, 52, 53, 54, 56, 59, 60, 62, 63, 64, 66, 67, 68, 69, 75, 76, 
#            77, 78, 79, 80, 81, 84, 86, 87, 88, 89, 91, 92, 93, 95, 97, 98, 99})

Right now I am using a brute-force method to search from the unions of 1 to 20 subsets using itertools.combinations. As shown below, the code finds a minimum amount of 17 subsets after 2.95 s.

from itertools import combinations
from time import time

t0 = time()
n = 1
sample = []
found = False
while not found:
    # Get all combinations of n subsets
    all_n_ss = list(combinations(ss, n))
    # Shuffle to gain randomness
    random.shuffle(all_n_ss)
    for n_ss in all_n_ss:
        u = frozenset().union(*n_ss)
        if u == universe:
            sample = n_ss
            found = True
            break
    # Add one more subset
    n += 1

print(len(sample))
print(sample)
print(time()-t0)

# 17
# (frozenset({0, 66, 7, 42, 48, 17, 81, 51, 25, 27}), 
#  frozenset({49, 27, 87, 47}), 
#  frozenset({76, 48, 17, 22, 25, 29, 31}), 
#  frozenset({14}), 
#  frozenset({0, 66, 68, 10, 46, 54, 25, 26, 59}), 
#  frozenset({75, 92, 53, 78}), 
#  frozenset({67, 68, 11, 79, 87, 89, 62}), 
#  frozenset({67, 99, 40, 10, 43, 11, 51, 86, 91, 60}), 
#  frozenset({6, 59, 91, 76, 45, 16, 20, 56, 27, 95}), 
#  frozenset({32, 98, 40, 46, 15, 86, 23, 29, 63}), 
#  frozenset({99, 37, 12, 77, 15, 18, 19, 52, 22, 95}), 
#  frozenset({39, 10, 11, 80, 18, 53, 54, 87}), 
#  frozenset({32, 93}), 
#  frozenset({34}), 
#  frozenset({64, 84, 22}), 
#  frozenset({32, 97, 69, 45, 16, 51, 88, 60}), 
#  frozenset({21}))
# 2.9506494998931885

However, in reality I have a set of 200 sets, which is infeasible for a brute-froce enumeration. I want a fast algorithm to sample just one random solution. Note that I want each sample has randomness, minimum amount and largest union.

Any suggestions?




How to stop view from going out of screen for randomized positions?

I have a screen ButtonPress that shows a button on random positions, it is working for most of the iterations but in some, it is going out of the screen and the button is not visible. I tried to follow this example but that does not seem to help as the button is still invisible for some iterations in the ButtonPress activity. Here's how I am generating the random positions:

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.button_press);

        button = findViewById(R.id.imageView5);
        button.setClickable(true);
        button.setOnClickListener(this);

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) button.getLayoutParams();
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        params.leftMargin = button.getWidth()
                + new Random().nextInt(metrics.widthPixels - 2*button.getWidth());
        params.topMargin = button.getHeight()
                + new Random().nextInt(metrics.heightPixels - 3*button.getHeight());
        button.setLayoutParams(params);


    }

And here's the layout file for the button:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#03B0F5"
    >

    <TextView
        android:id="@+id/button_press"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:gravity="center"
        android:background="#FFFFFF"
        android:text="@string/button_press"
        android:textSize="50sp"
        android:textColor="#03B0F5"
        android:layout_marginStart="0dp"
        />


        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:srcCompat="@drawable/ic_button"
            tools:ignore="VectorDrawableCompat" />
</LinearLayout>

I removed all the padding and margins from this resource file but it's still not working.




vendredi 25 juin 2021

Assistance with optimizing below MySql procedure

MySql - innodb_version 5.7.33

I working on a stored procedure which will be called periodically (lets say once a month) to populate a table with list of string in one column and with static values in other column. The table also has

  • ID column (AUTO_INCREMENT) and
  • timestamp column (CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)

The string is a concatenation of fixed characters plus integers (lets say 10). This integer has to be non repetitive random within the range.

CREATE DEFINER=`db`@`%` PROCEDURE `InsertRandom`(IN NumRows INT, IN MinVal INT, IN MaxVal INT)
BEGIN
    DECLARE i INT;
    DECLARE UniqueId INT(15);
    SET i = 1;
    START TRANSACTION;
    WHILE i <= NumRows DO
        SET UniqueId = concat('ABC', MinVal + CEIL(RAND() * (MaxVal - MinVal)));
        IF  NOT EXISTS (SELECT UNIQUE_ID FROM MY_TABLE WHERE UNIQUE_ID = UniqueId) THEN
            INSERT INTO MY_TABLE (`UNIQUE_ID`, `STATE`, `RANGE_ID`) VALUES (UniqueId, 'new', '100');
        END IF;
        SET i = i + 1;
    END WHILE;
    COMMIT;
END

The range (minVal & maxVal) will be 1 million for every procedure call.

For example,

CALL InsertRandom(1000000, 10000000,11000000);

The table will be purged once in 5 months retaining 1 month of data, so we can assume there will be at about 5 million records at a point when this procedure will executed and the usage of select inside loop is not optimal so please suggest an alternative approach.

Thank you.




Algorithm: Randomize Brightness and Contrast Values, With Constraints

I want to do a random brightness and contrast adjustment to an image, such that...

brightness = random in range (brightness_min, brightness_max)
contrast = random in range (contrast_min, contrast_max)   
outputImage = inputImage * contrast + brightness;

But when I do this, because the range of brightness and contrast values in my application are so large, I often output an image which is all white or all black.

I want an algorithm to choose a random brightness and contrast pair such that: no output is a solid color (unless already so), and: the output retains some specifiable amount of detail (this part is less important).

I don't know how to describe what I want in technical terms, nor begin constructing the solution. Any help is greatly appreciated. Thank you.




Why do I get an Uncaught TypeError for my random numbers?

I get Uncaught TypeErrors while my script is running. I have some dark boxes that I want to be animated some time and then get rid of the animation again. I have realised it with an intervall. During the intervall the class of the elements will be changed and then the changes will be reversed. I coose the selected element by a randomly generated index. And this random number seems to be the root of the problem, but I can't figure out why or how to solve it.

Here is my minimal example:

let randomNumber;
let boxes = document.querySelectorAll(".dark");
let randomNumbers = [];
let milliseconds = 2000;
setInterval(function() {
  randomNumber = Math.ceil(Math.random() * boxes.length);
  randomNumbers.push(randomNumber);
  boxes[randomNumber].className = boxes[randomNumber].className.replace(/(?:^|\s)dark(?!\S)/g, " animated");
  setTimeout(function() {
    boxes[randomNumbers[0]].className = boxes[randomNumbers[0]].className.replace(/(?:^|\s)animated(?!\S)/g, " dark");
    randomNumbers.shift();
  }, boxes.length * milliseconds);
}, milliseconds);
@keyframes animated_background_color {
  0% {
    background-color: #e66000;
  }
  25% {
    background-color: #ff9500;
  }
  50% {
    background-color: #ffcb00;
  }
  75% {
    background-color: #ff9500;
  }
  100% {
    background-color: #e66000;
  }
}

.box {
  height: 20px;
  margin-bottom: 4px;
  width: 20px;
}

.dark {
  background-color: black;
}

.animated {
  animation-name: animated_background_color;
  animation-duration: 3s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  background-color: #e66000;
}
<!DOCTYPE html>

<html>

<head>
  <title>Animation</title>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
</head>

<body>
  <div class="box dark"></div>
  <div class="box dark"></div>
  <div class="box dark"></div>
  <div class="box dark"></div>
  <div class="box dark"></div>
</body>

</html>



Scipy: Speeding Up Sampling

I have developed the following program for generating a list of subsamples, in chunks, for a specific task. It is, however, very slow, since I am doing random samples in a loop.

import scipy.stats as stats
import numpy as np

#GENERATE SOME RANDOMLY CHUNKED COUNT DATA
N_chunks=250
idx_chunks = np.random.randint(20, size=N_chunks)
idx_cumsum = np.cumsum(idx_chunks)
data_sample = stats.poisson(mu=5).rvs(size=np.sum(idx_chunks))
data_sample_split = np.split(data_sample, idx_cumsum)[:-1]

#GENERATE SUBSAMPLES OF THE LENGTH GIVEN BY EACH ELEMENT OF THE LIST
f = stats.poisson(mu=2)
output = []
total = 0
for _i1 in data_sample_split:
    temp = []
    for _ii1 in _i1:
        temp.append(f.rvs(_ii1))
    output.append(temp)

Is there a way I can I speed up the program, while obtaining exactly the same output?

I am specifically looking to presample all the samples I need, before reshaping to the list of lists. However, I do not know how to do this.




How do my make my image (rect) collide with my randomly generated circles to end the game?

I have been trying to solve this wor weeks. This is a free falling pit game, where my character (in this case a chimpanzee png) falls from the top of the screen to the bottom while trying to dodge the random black circles. I have tried so many angles at tackling this, I have tried the standard collision I was taught (pygame.sprite.groupcollide(Group1, Group2, False, True, collided = None) I have tried doing collisions with the colour black only, different formats of spawning my image and all that, and I haven't been able to find anything that works with my code. It has resulted inmy code being very messy. I have tried to clean it up for this, but it still might be hard to understand, but if anybody has any solution to this, please let me know as I have been stumped for weeks. I just want the game to close or "game over" when they touch a circle Code:

    import sys
import pygame as pg
RED = (255, 0, 0)
GRAY = (150, 150, 150)
GREEN =(34, 177, 76)
BLACK = (0,0,0)

import random
import math




def main():
    width, height = 1024, 768
    hbox, vbox = 80, 80
    w, h = 640, 240
    screen = pg.display.set_mode((width, height))
    BG = pg.image.load('jungle.jpg').convert()
    img = pg.image.load('MONKEY.png')
    img = pg.transform.scale(img, (80, 80))
    img.convert()
    rect = img.get_rect()
    rect.center = w//2, h//2
    clock = pg.time.Clock()
    Score = 0
    class Circle(pg.sprite.Sprite):
        def __init__(self):
            #You can initialise the size to a random value
            self.pos = [random.randint(0, 1000), random.randint(180, 600)]
            self.color = (0,0, 0)
            self.radius = 20

        def draw(self):
            pg.draw.circle(screen, self.color, (self.pos[0], self.pos[1]), self.radius)


    circles = []

    for i in range(20):
        circles.append(Circle())

    def checkIntersection(c1, c2):
        dx = c1.pos[0] - c2.pos[0]
        dy = c1.pos[1] - c2.pos[1]
        d = math.hypot(dx, dy)
        if d < c1.radius + c2.radius:
            return True
        return False


    for i in range(19):
        while checkIntersection(circles[i], circles[i + 1]):
            circles[i].pos = random.randint(0, 1000), random.randint(0, 700)
        
        velocity = (0, 0)
        done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        keys = pg.key.get_pressed()

        # booster
        move = 8 if keys[pg.K_LSHIFT] else 4

        if keys[pg.K_a]:  #to move left
            rect.x -= move
        if rect.x < 0 : rect.x = 0

        if keys[pg.K_d]: #to move right
            rect.x += move
        if rect.x > width-hbox : rect.x = width - hbox
        
        
        Score += 1
        rect.y += 2.5
        screen.blit(BG, (0,0))    
        screen.blit(img,rect)
        pg.draw.rect(screen, RED, rect, 1)
        pg.draw.polygon(screen, GREEN, ((1024,768), (0,768), (0,640),(1024,640)))
        font = pg.font.SysFont("comicsansms", 45)
        text = font.render (" " + str(Score), 1, BLACK)
        screen.blit(text,(480,700))
        pg.event.get()
        for circle in circles:
            circle.draw()
        pg.display.update()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
    sys.exit()



How to implement the best formula for line charts

I have successfully implemented my realtime ticking chart using the fomula which generates random numbers from a given range.

It is working, but my problem now is: My idea is to implement something similar to realtime stock/financial chart graphs. Mine doesnt look really good and anyone can actually see that the graph is plotting random figures:

this is how it looks like, it is generating randoms numbers in a formula that user can guess, for example it is plotting my line graph in this manner of random numbers: upp, down, up, down, up, down, following a given range with a slight difference from what I said.

I am using this formula:

random = new Random().nextInt((max1 - min1) + 1) + min1;
            data.addEntry(new Entry(set.getEntryCount(), (float) (random) + 0f), 0);
            data.notifyDataChanged();

where max1 and min1 is maximum and minimum range.

So what I want is a formula which gives me a nice chart which is similar or close to that of stock charts, they produce different patterns:

this is an example of the chart patterns that I need, so which fomulae would I need to get something like this?




Select random number within range as a new column

I am trying to create a new column of values in a dataframe that would be a random number within a range. As an example:

min <- sample(1:10, 10)
max <- sample(11:20, 10)

dt <- data.frame(min=min, max=max)

dt$value <- sample(dt$min:dt$max,1)

This gives me an error message.

How would I do this? Thank you




jeudi 24 juin 2021

Computing a random subset of permutations in Matlab to avoid memory errors

I’m trying to compute all permutations of 12 or 13 specific values (e.g., x = [73 78 84 82 79 68 85 67 84 73 79 78]), but I’m running into memory errors in Matlab (12 = 46.0 GB and 13 = 647.6 GB of memory).

Is there an easy way to select a random subset of, say, 4 million of these permutations?




What is causing the message "IndexError: list index out of range"?

I am comfortable with python but I can't figure out why this error is showing up because of my code:

import random
inp = input('Enter: ')
inp = str(inp)
char = 0
key = []
list = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%&*?+-')

if inp == 'New':
    while char < len(list):
        rand = random.randint(0, len(list))
        key.append(list[rand])
        char = char + 1
print(key)

The code won't always print the list "key" and instead give me the error "IndexError: list index out of range". How do I fix this?




Random numbers generation in PyCUDA

I am trying to generate random numbers using pycuda, code without random number generation code works fine. Any help will be appreciated.

from pycuda.compiler import SourceModule

code="""
#include <stdio.h>
#include <curand.h>
#include <curand_kernel.h>


__global__ void testrand2(unsigned long seed, float *a){
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    curandState state;
    curand_init(seed, idx, 0, &state);
    a[idx] = curand_uniform(&state);
}
__global__ void test(float *arr)
{
  dim3 threadsPerBlock(256,1,1);
  dim3 numBlocks(1,1);
  
  testrand2<<<threadsPerBlock,numBlocks>>>(1, arr);
}
"""

mod = SourceModule(code)
test = mod.get_function("test")

d = np.zeros(256, dtype=np.float32)

test (drv.InOut(d), block=(1,1,1), grid=(1,1))
print(d)

ERORR:

--------------------------------------------------------------------------- CompileError Traceback (most recent call last) in () 22 """ 23 ---> 24 mod = SourceModule(code) 25 test = mod.get_function("test") 26 print("main_Correlation Called")

2 frames /usr/local/lib/python3.7/dist-packages/pycuda/compiler.py in compile_plain(source, options, keep, nvcc, cache_dir, target) 153 cmdline, 154 stdout=stdout.decode("utf-8", "replace"), --> 155 stderr=stderr.decode("utf-8", "replace"), 156 ) 157

CompileError: nvcc compilation of /tmp/tmprygdeq52/kernel.cu failed [command: nvcc --cubin -arch sm_75 -I/usr/local/lib/python3.7/dist-packages/pycuda/cuda kernel.cu] [stderr: /usr/local/cuda/bin/../targets/x86_64-linux/include/curand_kernel.h(507): error: this declaration may not have extern "C" linkage

/usr/local/cuda/bin/../targets/x86_64-linux/include/curand_kernel.h(527): error: this declaration may not have extern "C" linkage

/usr/local/cuda/bin/../targets/x86_64-linux/include/curand_kernel.h(583): error: this declaration may not have extern "C" linkage

............ ............

/usr/local/cuda/bin/../targets/x86_64-linux/include/curand_discrete2.h(86): error: this declaration may not have extern "C" linkage

kernel.cu(19): error: kernel launch from device or global functions requires separate compilation mode

31 errors detected in the compilation of "kernel.cu". ]




SAS EG Random Sample with variable sample size

I need a stratified random sample that consists in a determined number of addresses. My stratification variable is the zip code. The sample size is already pre-determined and has different number of observations per zip code. How can I incorporate the desired number ob observations per zip code? Is it possible to do this with PROC SURVEYSELECT? I have the sample size in an external file.

Example:
ZIP CODE NUMBER_OBSERVATIONS
9999 10
8888 15
7777 10
6666 5

Is it possible? How can I do this? Thanks




How to add a component of randomness to a schedule

I am trying to schedule a job to run every 3 minutes on average, with a component of randomness between +/- 30 seconds. So the next job runs anywhere between 2mins 30secs - 3mins 30secs later.

This code works nicely for exactly 3 minutes, but I can't think of a way to introduce the 30 secs of randomness:

import schedule
def job:
   print('hi')

schedule.every(3).minutes.do(job)



How to return the index of an element in a list of lists?

List = [[1,2,3],[4,5,6],[7,8,9]]

i want to pick a random element in List and return the index of it.

when I do:

List.index(random.choice(List[random.randint(0,2)]))

it obviously gives me an error, because the code only indexes the list-elements in List.

what I would like to have is something like:

output: The random number is: 4 and the index is: (1,0) or List[1][0]



Setting random values to half of the dictionary and copying the rest

I have a python dictionary created by an other list via:

a = dict.fromkeys(some_list)

Because I created this dictionary via the above command all my values in the dictionary are None as expected. And it looks like this:

a = {('A', 'B'): None,
     ('A', 'C'): None,
     ('B', 'A'): None,
     ('C', 'A'): None}

What I want is: to be able to change the None values to random numbers via random.uniform(0,1).

However I don't wanna do this to whole of the dictionary instead only the first 2 keys (('A', 'B'), ('A', 'C')), and the rest (('B', 'A'), ('C', 'A')) should be copied from the first 2 keys.

Following sets all the values to random numbers. However I could not find a way to set the first two as random and the rest copied without hardcoding the keys.

for key in a:
    a[key] = random.uniform(0, 1)

Any Suggestions?




How do i acces a link from array in a random order without repeating the last one chosen?

  let urlArray = [
            "link",
            "link2",
            "link3",
        ];
        function randomUrl() {    

            let randomNumber = Math.floor(Math.random() * urlArray.length);
            let newUrl = urlArray[randomNumber];
            let visitedGame = document.referrer;
            setTimeout(function () {
                //if the previous link is not the same as the one generated access the generated link
                if (newUrl !== visitedGame)  {
                    window.location = newUrl;
               //access the next link from the array
                 } else{
                    
                 }
            }, 3000);
        }
        randomUrl();

I have this code that i'm stuck at.

So what i'm trying to do:

On some click ( that is not in the code right here, but it works ) i access this function. When i click that button, i need to generate a random link from this array, but without repeating the last accesed in the browser. so without the previous url that was accesed. I tried getting the document. referrer but it seems it doesn't work. Please help :(




Is there a short equivalent of matlab's nchoosek function in numpy or scipy?

In matlab nchoosek gives you all possible combinations k values taken from a set of size n:

 nchoosek(1:4,2)
ans =

   1   2
   1   3
   1   4
   2   3
   2   4
   3   4

The closest solution I came up with in Python was:

np.vstack([rng.choice(np.arange(5),size=3, replace=False, shuffle=False) for i in range(int(scipy.special.comb(5,2)))])

Which gives:

array([[0, 1, 4],
       [1, 3, 4],
       [0, 3, 4],
       [1, 2, 4],
       [0, 2, 4],
       [2, 1, 4],
       [0, 3, 4],
       [1, 2, 4],
       [2, 3, 1],
       [0, 1, 4]])

Isn't there a shorter and probably more efficient way to do this in python?




mercredi 23 juin 2021

How to sample a dataframe using a dataframe as weights with pandas

I want to sample rows from each columns of a dataframe according to a dataframe of weights. All columns of the dataframe of weights sum to 1.

A=pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
w=pd.DataFrame([[0.2,0.5,0.3],[0.1,0.3,0.6],[0.4,0.5,0.1]])
sampled_data = A.sample(n=10, replace=True, weights=w)

But this code yields the following error

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Obviously I would like the first column of A sampled according to the weights from the first column of w and so on.

With the solution like this:

sampled_data =
  1 2 3
0 2 6 8
1 2 5 7
2 3 4 8
. .....
9 1 6 9



Unique number from random integers

So I made a discord bot using python and there is a command that have as input two mentions and as output a random number between 1 and 8.

What I want to do is to make a result unique. For example we can convert the two mentions as numbers using users ids. And then find a formula or a way that the two ids will convert in a random number between 1 and 8 but that will always be the same. Every time we mention the two same users I want the same result. I don’t know if it’s possible with a formula or it will require to store some data. Of course I prefer a way that doesn’t require to store data.

Is it possible to do something like this ?




Choose random number of random items without replacement from numpy array

Assuming that I have a normal distribution of N(5,1), and numpy array np.array([1,2,3,4,5]).

I'm trying to choose random number from the array without replacement, and the number of the random number should be sampled from the normal distribution.

For example, this is what I got.

import numpy

rng = np.random.default_rng()
arr = np.array([1,2,3,4,5])

# choose 3 random numbers
n = 3

how_many = (1 * rng.standard_normal(n) + 5)
sample = rng.choice(arr, n, replace=False)

chosen = []
for s, h in zip(sample, how_many):
  chosen += [s] * int(h)

chosen
# [1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5]

Apparently, I found it really slow. Any ideas on how to make it fast?




randomized percentage of dog breed (in my case at least 5) that obviously should add up to 100%

The exercise problem is that there is a dog that you are trying to determine what types of the breed there is. In this case all breeds can be randomized to a certain percentage. In my case I just want to choose 5. How to make sure they all add up to 100%?




Append or insert random elements to my array

Ok I think I asked the wrong question:

    def draw(self, screen):
        super().draw(screen)

        if self.part == 1:
            screen.blit(self.record_text, (550, 20))
            screen.blit(self.main_image.image, (580, 280)) 
        else:
            # Second half 
            text2 = font.render('¿Qué has visto?',True, PURPLE)
            screen.blit(text2, (400,5))

            # Show all similar images
            cont = 0       
            
            for game_image in self.game_images:
                if cont < 4:
                    
                    game_image.draw(screen)
                cont += 1
            # We associate the correct rect to the correct image, to pass it later to the CORRECT Screen
            self.correct_image_rect = self.game_images[self.game_images.index(self.main_image)].rect

I want to print some images, but this is not reliable, because it doesnt print me the main_image sometimes, and I think the shuffle works as to, it will not print the same first 4 pictures that my folder has.




How many rows should I select for uniform distribution (sample checking database)?

I am looking for how many rows I should select from a database if I am trying to run a random sample check, each database differs in the number of rows so knowing the percentage will be useful. What is considered an accurate sample (10% of rows, 25%, etc.)?

Thanks!




Histogram of the 1D-random walk in Julia

This is a simulation of 100 1D-random "walkers" each taking 100 "steps" in either one direction or another by +1/-1.

using Plots
init = 0
walkers = 100
walk_length = 100
walks = cumsum(vcat(fill(init, 1, walkers),               # initial state
                    rand([-1, 1], walk_length, walkers)), # vertically append move direction
               dims=1)  # cumulative sum over the first dimension to get one walk per column
plot(walks, legend=nothing)

enter image description here

Since many walkers can end up at the same value at 100 steps, I would like to create a histogram at the end point, showing the amount of walkers there.
I think there might be a hist() function but I am not sure how to implement it.




Issue while saving rects, it crash my game

I have this code that saves the position and the rect from an object (usally small, like a drawing) and then spawns them (blits) in my screen. I encountered that if I put too many objects or too big, I´m guessing the rects collide and then the game crashes, but also, sometimes, even if I have not many objects, it can crash because this occurance.

How could I solve this problem? I´m guessing adding an if sentence so it checks that is not as near as to crash the game or something like that, where I save the rects of the images is in the for i in self.game_images: :

class GameScene(Scene):
    def __init__(self, game, images, main_image, next_scene):
        super().__init__(next_scene)
        
        self.game = game
        self.main_image = main_image
        self.game_images = images

        # Fade effect set-up
        self.fade = False
        self.fade_time = 0
        self.current_alpha = 255
        self.part = 1

        self.record_text = font.render('Atiende',True, PURPLE)
        self.correct_image_rect = None

        # Trying to use colliderect so it doesnt overlap
        # this is the same code as before but adapted to use the gameimage class and the rects stored there
        self.rects = []
        for i in self.game_images:
            position_set = False 
            while not position_set:
                x = random.randint(100,950)
                y = random.randint(100,600) 

                i.rect.x = x
                i.rect.y = y

                margin = 5
                rl = [rect.inflate(margin*2, margin*2) for rect in self.rects]
                if len(self.rects) == 0 or i.rect.collidelist(rl) < 0:
                    self.rects.append(i.rect)
                    position_set = True

        # this makes a number and object pair, and allows us to set the correct rects for the correct gameimage classes
        for i, rect in enumerate(self.rects):
            self.game_images[i].rect = rect

    # this is the fade stuff from before that was in draw. It really belongs here tbh
    def update(self, dt):
        if self.part == 1 and self.fade:
            self.fade_time += dt
            if self.fade_time > fade_timer:
                self.fade_time = 0
                self.main_image.set_alpha(self.current_alpha)
                self.record_text.set_alpha(self.current_alpha)
                # Speed whichin the image dissapears
                self.current_alpha -= 5
                if self.current_alpha <= 0:
                    self.fade = False
                    self.part = 2

        else:
            # we reset the main image alpha otherwise it will be invisible on the next screen (yeah, this one caught me out lol!)
            self.main_image.set_alpha(255)

    # draw is similar to before, but a bit more streamlined as the fade stuff is not in update
    def draw(self, screen):
        super().draw(screen)

        if self.part == 1:
            screen.blit(self.record_text, (550, 20))
            screen.blit(self.main_image.image, (580, 280)) 
        else:
            # Second half 
            text2 = font.render('¿Qué has visto?',True, PURPLE)
            screen.blit(text2, (400,5))

            # Show all similar images      
            for game_image in self.game_images:
                game_image.draw(screen)

            # We associate the correct rect to the correct image, to pass it later to the CORRECT Screen
            self.correct_image_rect = self.game_images[self.game_images.index(self.main_image)].rect

    # again we pass the event to the game object the same as with the other classes
    def get_event(self, event):
        if self.part == 2:
            if self.game.level == 13:
                self.game.game_over = True
            if self.correct_image_rect.collidepoint(event.pos):
                return 'CORRECT'
            for rect in self.rects:
                if not self.correct_image_rect.collidepoint(event.pos) and rect.collidepoint(event.pos):
                    return 'INCORRECT'