vendredi 30 septembre 2022

How can I test a function that takes an array and outputs 3 random elements?

I want to test this function using Jest. The problem is that I don't know how I can write the test without adding all the possible outcomes in the toBe(). Any hints are welcomed.

const options = [1, 2, 3, 4]
 const getElements= (options) => {
  const getRandomEl = (list) => list[Math.floor(Math.random() * list.length)];
  return [
    getRandomEl(options),
    getRandomEl(options),
    getRandomEl(options),
  ];

And here is my test:

describe("Helper tests", () => {
    test('We should get 3 random elements from a list', () => {
      expect(mathOperations.getElements([1, 2, 3, 4])).toBe([1, 2, 3] | [2, 3, 4] | [1, 2, 4]); //how to avoid adding all possible combinations in the toBe()?
    });
   })
};




Random number game in python, with according messages

I am trying to make a random-number game, where you have to guess which random number Python gets from 1-10. And also do so that if you write e.g. 11, 104 etc. it will ask you to try again to write a valid input.

This is what I have tried so far, but I cant seem to figure out what I have done wrong. All help is greatly appreciated:) Sorry if it is an easy question, I am still fairly new to Python

while True:
    try:
        number_in = int(input("Please insert a number between 1-10: "))
    except ValueError:
            print("Sorry. Try again to insert a number from 1 to 10")
            continue
            
if 1 < number <10:
    print("Your input was invalid. Please insert a number from 1 to 6")
    continue
else:
    break

game_1 = randint(1,10)

if number_in == game_1:
    print(f"The result was {game_1}. Your guess was correct, congratulations!")
else:
    print(f"The result was {game_1}. Your guess was NOT correct. Try again")



jeudi 29 septembre 2022

numpy - how to increment by one all values on axis 1

I would like to increment all values on axis 1 by one.

For instance, row[0] col[0] increases by 1, row[1] col[0] by 2, and so on...

Example of how to do this with a single-dimensional array:

y = np.random.random(size=(10,))
y += np.arange(start=1, stop=11, step=1)

result:

[ 1.66704813  2.90625487  3.961399    4.64969495  5.5286593   6.31736865
  7.24056032  8.25632077  9.02458071 10.1816335 ]

Now I have a multi-dimensional array I would like to do the same as above only by columns

y = np.random.random(size=(10,3))
y += np.arange(start=1, stop=11, step=1)  # Not going to work. Need each col to grow by one each row increment. like the single-dimensional array only by column.

end result is something like:

[[1.66704813 1.90625487 1.961399  ]
 [2.64969495 2.5286593  2.31736865]
 [3.24056032 3.25632077 3.02458071]
 [4.1816335  4.13044436 4.13969493]
 [5.48485214 5.58980863 5.59890548]
 [6.58126238 6.30004674 6.730429  ]
 [7.76121817 7.94366992 7.1039714 ]
 [8.81874117 8.00239219 8.16807975]
 [9.64509574 9.75334071 9.59641831]
 [10.11176155 10.71027095 10.77104173]]



Dice game in Python: randint and victory message

I'm experimenting a bit and trying to make a simple dice game. I want it to be so one could guess a number between 1-6, then have a dice randomly generate a number, and giving a message depending on if one was right or not.

I have tried:

guess_1 = input("Guess the number on the dice: ")
print("You have entered " + guess_1)

from random import randint
dice = randint(1,6)

if guess_1 == dice:
    print(f"The result was {dice}. Congratulations, you win!")
else:
    print(f"The result was {dice}. Sorry, try again!")

However, now, even if I guess correctly, I still wind up with "You have entered 6 The result was 6. Sorry, try again!"

Does anyone know what I have done wrong here? And if there is a way to do so that you get an error message if you write e.g. 15 instead of a number within the range of the dice?

All help greatly appreciated!




str_pad(mt_rand(1,999999),06,'0',STR_PAD_LEFT Generating similar numbers

 str_pad(mt_rand(1,999999),06,'0',STR_PAD_LEFT

I have had this code snippet on my WordPress site since 8 months ago. The purpose was to assign each user that fills the form (WPForm) a unique user ID. It has always worked well until today when I noticed that four entries have the same ID (One yesterday and Three today). I am running Astra Theme. Does anyone know what the course could be?




How do I create a function in r that assigns one person to 3 other person?

I would like to create a function that allows me to easily import any name list with last name and first name (2 columns) and then based on that name list, 3 persons should be randomly assigned to 1 other person. Just wondering how can I do that by creating by own function?

Any help will be appreciated. Thanks!




Probabilistic random selection

Run an iteration and randomly select items from a list with each item assigned a probability of being selected. Please, which module in python can I use to achieve this or a line of code...?




How do I choose a random textContent?

I am trying to make a simple generator with Javascript just for fun. It's an outfit generator with different combinations of clothing.

Right now I have two buttons for two types of outfits (I would like to add more in the future). I want to instead have one button, and it will choose an outfit type (#falloutfita or #falloutfitb) and then generate the random outfit based on that.

I thought maybe I could use an "or" || with the textContent but it looks like it's not possible.

Here is my Javascript code up through the first outfit type:

var allsweaters = ["blue hoodie", "black hoodie", "pink v-neck sweater", "gray pullover"];
var allpants = ["black casual pants", "dark old navy jeans", "medium old navy jeans", "black jumpsuit"];
var alllongshirts = ["long-sleeved white shirt", "long-sleeved gray shirt", "long-sleeved black shirt"];
var allovershirts = ["white button-up", "green jacket", "blue jean shirt"];

document.querySelector("#submitfalla").addEventListener("click", () => {
  var sweater = "";
  var pants = "";
  var lsshirt = "";
  var random_index = 0;
  for (let i = 0; i < 1; i++) {
    random_index = Math.floor(Math.random() * allsweaters.length);
    sweater += allsweaters[random_index];
    random_index = Math.floor(Math.random() * allpants.length);
    pants += allpants[random_index];
    random_index = Math.floor(Math.random() * allpants.length);
    lsshirt += alllongshirts[random_index];
  }

  document.querySelector("#falloutfita").textContent = sweater + " and " + lsshirt + " and " + pants;
});
<button id="submitfalla">Submit</button>

<div id="falloutfita"></div>

It's my first post on stack overflow, please let me know if there is any way I should edit this question too! I've looked at similar questions here but haven't been able to successfully apply them to mine.




How to randomly edit elements in a 2D array?

I have a 2D NumPy array in which I would like to randomly replace a few data points with different values. How do to do that for a general NumPy 2D array?

Example: Randomly replace 6 data elements of A having value 1 with value 2.

Input-
A = [
    [1,1,1,1,1,0,0,1,1],
    [1,0,1,0,1,1,0,1,1],
    [0,1,1,1,1,1,1,1,0],
    [1,1,1,1,1,0,0,1,1],
    [1,1,0,0,1,0,0,1,1],
    [1,1,1,1,1,0,0,1,1],
    ]

Output-
A'= [
    [1,1,1,2,1,0,0,1,2],
    [1,0,1,0,1,1,0,1,1],
    [0,1,1,1,1,1,1,1,0],
    [1,1,1,2,1,0,0,1,1],
    [1,1,0,0,1,0,0,1,2],
    [2,1,1,1,1,0,0,1,2],
    ]

How to achieve this using Numpy with few lines of code? Any help would be appreciated.




I am having wrong output in roll dice game when my guess matches the random dice output [duplicate]

I am building a game where the user has to guess which number between 1 and 6 the dice will role. Once the user gets the right guess they are supposed to receive a congratulatory message and if their guess is wrong they get try again

however even when guess matches the random output they get the message try again and not you win here is my code below please help me understand where i am going wrong

also i have changed the random to just 2 numbers instead of 6 to ensure user gets a quicker match once i figure out where problem is i will return random pool to 6

from random import randint
while True:
    dice = random.randint(1,2)
    user = input("choose a number between 1 and 6: ")
    print("The dice is: ", dice)
    print("You choose: ", user)
    
    if user == dice:
        print("you win")
    elif dice != user:
        print('try again')
    else:
        pass
    
    play_again = input('Would you like to play again, yes or no?')
    
    if play_again != 'yes':
        print("Goodbye")
        break



mercredi 28 septembre 2022

Rolling dice probability

I'm working on a project where I'm trying to find the probability of a dice which rolls a die and stores how many times it comes up at one, two, three and so on. It will do this many times, and calculate the difference between the face that turns up the most times and the face that shows up the least times. This should then be divided with the number of the face that was shown the most to give you a sort of ratio (in percent) of the difference. This should then be done 20 times with increasing number of times to roll the die, from 10 to 20 to 40 and so on by doubling the number of rolls each time.

I've been trying to solve this with only Iterations and not help from a list and or functions but haven't found a solution to it.

I found this online:

k = 10
for i in range(1,21):
    L = [0] * 6
    for j in range(k):
        dice = random.randint(0,5)
        L[dice] += 1
    ratio = 100 * (max(L) - min (L)) / max (L)
    print (k, ratio)
    k *= 2

output:

10 100.0

20 60.0

40 54.54545454545455

80 50.0

160 30.0

320 30.76923076923077

640 16.10169491525424

1280 16.170212765957448

2560 12.958963282937365

5120 12.1374865735768

10240 5.161656267725468

20480 3.7442396313364057

40960 1.5852239674229203

81920 3.2765682259107565

163840 1.1792967896920725

327680 0.303523431643232

655360 0.5303078706450406

1310720 0.6217280476551579

2621440 0.24166628560976725

5242880 0.1638989888130076

but it uses a list to solve it, so I was wondering if there was a way to solve this program with Iterations and not any help from a list or a function?

Would really appreciate the help




Time table quize [duplicate]

How can I stop users whenever their answer is correct by printing 'welldone'


num1 = randint(2,12)
num2 = randint(2,12)
result = int(num1)*int(num2)
mine = 0
while result != mine:
    mine = print(input('what is ' +str(num1)+ 'x' +str(num2)+ '?'))
    if result == mine:
        print('Welldone')
        break
    else:
        mine= print(input('again'))
print('Welldone')```

thanks



mardi 27 septembre 2022

How to create an array of objects , where all properties are fixed, values are generated randomly and it's get fixed after generated once?

I am learning react as beginner , I am trying to create an array of products object. I have created it in a js file. Then exported the array. In another file I have imported and it works. Problem is whenever I refresh the page it gets new random values. As I have use random function to generate the object values. What I want is, after generating the array of objects once, it won't generate randomly further. How can I do that?

export const cosmetics = [];
const names = [];
const prices = [];

//random generated  name list---------------------------------
function set_name() {
    const letters = 'abcdefghijklmnopqrstuvwxyz'
    for (let j = 0; j < 20; j++) {

        let name = '';
        for (let i = 0; i < 4; i++) {
            name += letters.charAt(Math.floor(Math.random() * 26))
        }
        names.push(name)
    }
}
// random generate prices list ---------------------------
function set_price() {
    for (let j = 0; j < 20; j++) {
        prices.push(Math.floor(Math.random() * 500) + 1000)
    }
}
//  create data set array of objects
function construct_data() {
    for (let i = 0; i < 20; i++) {
        const cosmetic = {
            id: i + 1,
            name: names[i],
            price: prices[i]
        }
        cosmetics.push(cosmetic)
    }
}

set_name();
set_price();
construct_data();





lundi 26 septembre 2022

Why my number guessing game does not work?

Less than one day into learning Python. I'm trying to make a simple number-guessing game, but I've run into a problem: the number is always incorrect, but there's only 10 to pick from! Here's my code for reference:

import random



def game():
    randomNum = random.randint(1, 11)
    guess = 0
    print(input("Guess a number between 1 and 10: "))
    while guess != randomNum:
        if guess == randomNum:
            print("Correct! You win!")
            break
        else:
            print(input("Incorrect, guess again: "))


game()

Any reason why this is happening?




Random assignment 1s and 0s with a maximum

I have a dataset with two different columns (X and Y) that both contains the exact same amount of 0s and 1s:

0     1 
3790  654

Now I want to have column Y to contain an exact amount of 1733 1s and 2711 0s. But the 1079 extra 1s (1733-654) must be assigned randomly. I already tried the following:

ind <- which(df$X == 0)
ind <- ind[rbinom(length(ind), 1, prob = 1079/3790) > 0]
df$Y[ind] <- 1

But if I run this code, there is everytime a different number of 1s, and I want it to be exactly 1733 if I run it. How do I do this?




Clustering by using Locality sensitive hashing *after* Random projection

It is well known that Random Projection (RP) is tightly linked to Locality Sensitive Hashing (LSH). My goal is to cluster a large number of points lying in a d-dimensional Euclidean space, where d is very large.


Questions: Does it make sense to cluster the points via LSH after having reduced the dimensionality of their input space by using first RP? Why yes/no? Is there any redundancy in the combined use of RP as dimensionality reduction method before LSH as clustering method?




Random integers, Array, Linear search

The program is about creating random values and doing linear search. The results shown when run is the "the input value" is not in the list, though it is present in the generated random list Thank you so much.

import java.util.Random;
import java.util.Scanner;
import java.util.HashSet;
import java.util.Set;


public class LinearSearch {

    public static void main(String[] args) {
                    
        int array [] = new int [100];
        
        Random ValGener = new Random ();
        Set set = new HashSet <Integer>();
        
        for (int i = 1; i <= array.length; i++) {
            int randomNumber = ValGener.nextInt(100);
            
            if (!set.contains(randomNumber)){
                    set.add(randomNumber);
                    
            System.out.println(i + " Random No: " + randomNumber);
                }else i--;
            
             }
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the random searched value");

            int value = input.nextInt();
    
            for (int index = 0; index < array.length; index++){

                if (array [index] == value){

                       System.out.println(value+ " is found at Index "+(index+1));
                       }
           
                else; {

                       System.out.println(value+ " is not in the list");
                      break;
                       }
     
                    }
                
}   

}



Random questions without repetition python kivy

I am on my way to build a quiz app, the questions and answer options are in a image displayed in a screen. Each question have theyr own screen, everything works but what i try to do now is to call those screens randomly and this is working too but what i want to do now is to not let the app to display the same question(screen) again and also everytime when i start the app is starting with the same screen. I tried to do something with np.random.permutation but with no succes.. i need to mention that i am new in python / kivy. Is somebody here to help me to pass this step ?? THANKS FOR YOUR HELP !!

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
import random
import numpy as np


class Q1(Screen):
    pass


class Q2(Screen):
    pass


class Q3(Screen):
    pass


class Q4(Screen):
    pass


class WrongAnswer(Screen):
    pass


class TestApp(App):

    def wrong_answer(self):
        screen = ['WrongAnswer']
        return random.choice(screen)

    def random_screen(self):
        screens = list(np.random.permutation(np.arange(0,4))['Q1', 'Q2', 'Q3', 'Q4'])
        return random.choice(screens)

    def build(self):

        sm = ScreenManager()
        sm.add_widget(Q1(name='Q1'))
        sm.add_widget(Q2(name='Q2'))
        sm.add_widget(Q3(name='Q3'))
        sm.add_widget(Q4(name='Q4'))
        sm.add_widget(WrongAnswer(name='WrongAnswer'))

        return sm


if __name__ == '__main__':
    TestApp().run()

<Q1>:
    Image:
        source: 'Q1.png'

        FloatLayout:
            size: root.width, root.height/2

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.random_screen()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()


<Q2>:
    Image:
        source: 'Q2.png'

        FloatLayout:
            size: root.width, root.height/2

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.random_screen()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

<Q3>:
    Image:
        source: 'Q3.png'

        FloatLayout:
            size: root.width, root.height/2

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.random_screen()

<Q4>:
    Image:
        source: 'Q4.png'

        FloatLayout:
            size: root.width, root.height/2

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.random_screen()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":1.16}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.5, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

            Button:
                size_hint: 0.3, 0.25
                pos_hint: {"x":0.09, "top":0.7}
                background_color: 1, 1, 1, 0.2
                on_release: root.manager.current = app.wrong_answer()

<WrongAnswer>:
    Image:
        source: 'L1.png'



dimanche 25 septembre 2022

How can I select a random sequence of n rows for each group in a pandas data frame?

Suppose I have the following data frame:

raw_data = {
    'subject_id': ['1', '1', '1', '1', '2','2','2','2','2'],
    'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Brian','Bob','Bill','Brenda','Brett']}
df = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name'])

How can I select a sequence of n random rows from df for each subject_id? For example, if I want a sequence of 2 random rows for each subject_id, a possible output would be:

subject_id   first_name
1            Amy
1            Allen
2            Brenda
2            Brett

The post that seems most similar to this question seems to be:

select a random sequence of rows from pandas dataframe

However, this does not seem to take into account the grouping that I need to do.




printout only one time array items

i made this little class that printout in rando my array, but sometimes catch 2 or more times the same index.

es: 2 cook 3 pick 4 relax 3 pick

how can i make it to print only 1 time any item shuffled ?

es: 2-1-3-4 ecc...

i need it to remain an array. thanks for help

here the code:

java.util.Random random = new java.util.Random();

String[] lista = {"1 drink","2 cook","3 pick","4 relax"};

public String[] getLista() {
    return lista;
}

public void setLista(String[] lista) {
    this.lista = lista;
}


public String randomNumber(String[] lista) {
    int rnd = new Random().nextInt( lista .length);
     return lista[rnd];



random number javascript onclick doesn't work

I'm trying to use setTimeout.

Without setTimeout my function works,but using setTimeout it stops. Any one knows what I am doing wrong? I want that function works only 3 seconds after click.

let d6
document.getElementById("rollButton").onclick = function d6click(){
d6 = Math.floor(Math.random() * 6) + 1;
document.getElementById("resultd6").innerHTML = d6;
};
setTimeout(d6click, 3000)



Random integers between 1 to max value of unsigned 32 bit integer without duplicates [closed]

I want to generate random integers between 1 to max size of unsigned 32 bit integer. I have tried ThreadLocalRandom but it is generating too many duplicates. Generator function should be thread safe.




How to have 3 random objects spawn on 3 places

The goal is having random objects spawn on 3 positions once . the code works and looks like this but with more if statements and 3 small stataments:

if mainloop != 3:
  if smallloop1 != 1:
     if randomnumber == x:
        object.goto(x, y)
        mainloop += 1
        smallloop += 1

the problem is that the if statement doesnt stop so multiple objects spawn
im also not getting any error messages
I tried changing the if statements to while loops which didnt change anything except having to stop them with the break command or using a list instead of a random number which made the thing more complicated and again didnt change anything
Thanks in advance




samedi 24 septembre 2022

how to randomize and insert question with picture

please java code to insert picture and random quiz. it does not work:

let MCQS = [
   {question: "What does HTML stand for?",
      choice1: "Hyperlinks and Text Markup Language",
      choice2: "Hyper Text Markup Language",
      choice3: "Hyper Text Making Language",
      choice4: "Hyper Text Mark Language",
      answer: 1
   },
   {question: "What does CSS stand for?",
      choice1: "Colorful StyleSheet",
      choice2: "Creative Style Sheet",
      choice3: "Cascading Style Sheet",
      choice4: "Computer Style Sheet",
      answer: 2
   },
   {question: "Which HTML tag is used to define an internal style sheet?",
      choice1: "<script>",
      choice2: "<style>",
      choice3: "<html>",
      choice4: "<svg>",
      answer: 1
   },
   {question: "Which is the correct CSS syntax?",
      choice1: "body{color:black}",
      choice2: "{body{color:black}",
      choice3: "body={color:black}",  
      choice4: "body:color{black}",
      answer: 0
   },
   {question: "How do you insert a comment in a CSS file?",
      choice1: "/*This is Comment*/",
      choice2: "//This Is Comment",
      choice3: "<!--- This Is Comment --->",
      choice4: "//This Is Comment//",
      answer: 1
   },
   {question: "How do you insert a comment in a HTML file?",
      choice1: "/*This is Comment*/",
      choice2: "//This Is Comment",
      choice3: "<!--- This Is Comment --->",
      choice4: "//This Is Comment//",
      answer: 2
   },
   {question: "Which property is used to change the background color?",
      choice1: "backgroundColor",
      choice2: "BgColor",
      choice3: "Color-Background",
      choice4: "background",
      answer: 3
   },
   {question: "How to write an IF statement in JavaScript?",
      choice1: "if i==5",
      choice2: "if(i==5)",
      choice3: "if(i==5)then",
      choice4: "if i==5 then",
      answer: 2
   },
   {question: "Inside which HTML element do we put the JavaScript?",
      choice1: "xxxx",
      choice2: "xxxxxxx",
      choice3: "xxxxxxxxxx",
      choice4: "xxxxxxxxxxxxxx",
      answer: 2
   },
   {question: "How does a WHILE loop start?",
      choice1: "while(i <= 0)",
      choice2: "while(i <= 0 i++)",
      choice3: "while i <= 0",
      choice4: "while (i++ i <= 0)",
      answer: 0
   }];



vendredi 23 septembre 2022

Mutually Exclusive Variable Definitions in Nested Randomisations - Python

I'm attempting to return an output containing several nested random choices of strings from lists using Python's random module with the outputs of variables from choice 1 being exclusive to choice 2. Essentially, I want x_choice1 to never equal x_choice2 in the final output and same goes for y_choice1 and y_choice2. Here's some context... (this is all within a main function, btw).

        x = ["x1", "x2", "x3", "x4"]

        y = ["y1", "y2", "y3", "y4"]

        # Makes random assignment to multiple x choice and y choice variables from x and y lists

        x_choice1 = random.choice(x)
        y_choice1 = random.choice(y)

        x_choice2 = random.choice(x)
        y_choice2 = random.choice(y)

        # z1 and z2 vars combine choices from both lists

        z1 = x_choice1 + " " + y_choice1

        z2 = x_choice2 + " " + y_choice2

        # While loops to make each x and y choice vars mutually 
        # exclusive with additional prints to signal when the program 
        # is re-rolling the value of vars

        while x_choice1 == x_choice2:
            print("reassigning x variables")
            x_choice1 = random.choice(x)
            x_choice2 = random.choice(x)

        while y_choice1 == y_choice2:
            print("reassigning y variables")
            y_choice1 = random.choice(y)
            y_choice2 = random.choice(y)

        # Final variables to combine nested random vars

        final1 = ["first: " + z1, "first: " + z1, "first: " + z1]

        final2 = ["second: " + z2, "second: " + z2, "second: " + z2]

        # Final random selection of nested random vars

        final_choice1 = str(random.choice(final1))

        final_choice2 = str(random.choice(final2))

        # Output both final choices

        output = final_choice1 + " " + final_choice2

        print(output)

This works exactly how I want it to when I remove the 'nesting' of the variables (assigning z1 and z2, the random selection of final1 and final2, etc.). For example...

    x = ["x1", "x2", "x3", "x4"]

    y = ["y1", "y2", "y3", "y4"]

    x_choice1 = random.choice(x)
    y_choice1 = random.choice(y)

    x_choice2 = random.choice(x)
    y_choice2 = random.choice(y)

    while x_choice1 == x_choice2:
        print("reassigning x variables")
        x_choice1 = random.choice(x)
        x_choice2 = random.choice(x)

    while y_choice1 == y_choice2:
        print("reassigning y variables")
        y_choice1 = random.choice(y)
        y_choice2 = random.choice(y)

    output1 = x_choice1 + " " + y_choice1
    output2 = x_choice2 + " " + y_choice2

    print(output1)
    print(output2)

This outputs something like this:

reassigning x variables
reassigning x variables
x3 y1
x2 y4

Which every time never has the first x equivalent to the second and same for y and also triggers the message if it has to re-roll the choices, so I know it works.

How can I make the while loops in the first example work in the same way? At the moment it does trigger the "reassigning variables" message but then the values always return the same (ex. x4 x4, y2 y2).




How to get random characters from multiple different arrays in JavaScript

const array1 = ["A", "b", "C", "D", "f"]
const array2 = ["❤️", "🔥", "👋", "🦑", "😅"]
const array3 = ["0", "1", "2", "3", "4", "5"]


function renderItem() {
    let randomI = Math.floor(Math.random() * array1.length)
    console.log(array2[randomI])
}


function generateRandom () {
    let randomValue = ""
    for(let i = 0; i < 4; i++) {
        randomValue += renderItem()
    }
    return randomValue
}

I create an input field in HTML where the user can select a number between (6 - 18). and two input checkboxes. if both or one of them are checked✅ I want to generate random characters from three(3) of the arrays or from two(2) different arrays. if none of theme are not checked I want to generate random characters from the first array.

now my question is how do I get random e.g.(10) characters from those 3 different arrays?




Creating a schedule of games with "Conference" and a randomized "Non-Conference" with varied conference sizes

There would be 30 total games where 12 are non conf. and 18 conf. The conference are no smaller than 8 and no larger than 16 and can have odd or even numbers. There will be up to a couple hundred schools to matchup. If there is an odd number there will be non-conf games mixed into the conference schedule. I am thinking of making it 31 or 32 weeks and adding a bye or 2 byes so that will not have to happen.

I am using swift.

I have tried creating randomizing all possible matchups and then creating the schedule from there and having troubles. I also have done the basic round-robin equation but it doesn't work for odd number without a bye.




jeudi 22 septembre 2022

Random Number Game and Removing Numbers

I'm trying to create a random number game in Python which the computer starts by giving a random number from 1 to 10 and then consecutively, the computer and the user can remove a few numbers. The person that removes the last number to 0 loses.

An example of the output that I imagine is like this:

The starting number is: 5
computer removes: 3
2 numbers are left
User removes: 1
1 number is left
computer removes 1
user wins!

What functions can I use to perform the removing task?




C# - Random method returns consecutively repeated values

I'll try to be brief, I think the code is quite simple. I'm trying to create a password generator using a starting string, containing all usable characters (ie "passwordChars") to be used in a FOR loop in association with the Random.Random method to randomly extract a character from the string and then recompose it in a new one to create the password.

private void GeneratePassword()
{
    string passwordChars = null;

    if (isMaiuscEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = "MNBVCXZLKJHGFDSAPOIUYTREWQ";
        }
        else
        {
            passwordChars += "MNBVCXZLKJHGFDSAPOIUYTREWQ";
        }
    }

    if (isLowerEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = "alskdjfhgzmxncbvqpwoeiruty";
        }
        else
        {
            passwordChars += "alskdjfhgzmxncbvqpwoeiruty";
        }
    }

    if (isNumberEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = "2674589103";
        }
        else
        {
            passwordChars += "2674589103";
        }
    }

    if (isSymbolsEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = @"!()-.?[]_`~:;@#$%^&*+=";
        }
        else
        {
            passwordChars += @"!()-.?[]_`~:;@#$%^&*+=";
        }
    }

    int passwordCharsLenght = passwordChars.Length;
    string password = null;

    for (int pwdLenght = 0; pwdLenght < int.Parse(PasswordSizeTextBox.Text); pwdLenght++)
    {
        Random randomizer = new Random();
        int charIndex = randomizer.Next(passwordCharsLenght);

        if (String.IsNullOrEmpty(password) == true)
        {
            password = passwordChars[charIndex].ToString();
        }
        else
        {
            password += passwordChars[charIndex].ToString();
        }
    }

    PasswordOutputTextBlock.Text = password;
}

The problem is that in this way, the result will be a constant repetition of one or more characters, for example:

INPUTS:
Password size = 50, isUpperEnabled = true, isLowerEnabled = true,
isNumberEnabled = true, isSymbolsEnabled = true.

OUTPUT: 
AAAAAAAAAAAAAAAAAAAAAA3333333333333333333333333333

But if I add a MessageBox between the randomizer and the writing of the character obtained in the password strnga then everything works correctly, the password is generated perfectly never generating consecutive repetitions. The code with the inserted MessageBox:

private void GeneratePassword()
{
    string passwordChars = null;

    if (isMaiuscEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = "MNBVCXZLKJHGFDSAPOIUYTREWQ";
        }
        else
        {
            passwordChars += "MNBVCXZLKJHGFDSAPOIUYTREWQ";
        }
    }

    if (isLowerEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = "alskdjfhgzmxncbvqpwoeiruty";
        }
        else
        {
            passwordChars += "alskdjfhgzmxncbvqpwoeiruty";
        }
    }

    if (isNumberEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = "2674589103";
        }
        else
        {
            passwordChars += "2674589103";
        }
    }

    if (isSymbolsEnabled == true)
    {
        if (string.IsNullOrEmpty(passwordChars) == true)
        {
            passwordChars = @"!()-.?[]_`~:;@#$%^&*+=";
        }
        else
        {
            passwordChars += @"!()-.?[]_`~:;@#$%^&*+=";
        }
    }

    int passwordCharsLenght = passwordChars.Length;
    string password = null;

    for (int pwdLenght = 0; pwdLenght < int.Parse(PasswordSizeTextBox.Text); pwdLenght++)
    {
        Random randomizer = new Random();
        int charIndex = randomizer.Next(passwordCharsLenght);

        MessageBox.Show("STOP");

        if (String.IsNullOrEmpty(password) == true)
        {
            password = passwordChars[charIndex].ToString();
        }
        else
        {
            password += passwordChars[charIndex].ToString();
        }
    }

    PasswordOutputTextBlock.Text = password;
}

I hope that I have been clear enough and that someone understands what I am doing wrong. Thanks in advance to everyone.




Finding sum in a random array list

I'm trying to make a random array list in range [-250, 250] and print the numbers, then the sum just once, at the end of the code for all of the numbers below. here is my code:

public class Main {
  public static void main(String[] args) {
      Random rand = new Random();
      int max = 250;
      int min = -250;
      for  ( int  i = 1 ; i <= 50 ; i ++){
          int rez = min + rand.nextInt(max) * 2;
          System.out.println("The number is : " + i);
          int sum = rez + rez;
          System.out.println("The sum is: " + rez);
      } 

This is the code so far. It works. But I want to print the sum just once, at the end of the code for all of the numbers above. My code so far prints the sum individually.

I also tried it like this


    for  ( int  i = 1 ; i <= 50 ; i ++) {
            int rez = min + rand.nextInt(max) * 2;
            System.out.println("The number is : " + i);
            int sum = rez + rez;
        }
            System.out.println("The sum is: " + rez); 

but it gives me this error "Cannot resolve symbol 'rez'" Can someone please tell me what I did wrong?




Making a random selection from a list of links based on input in a second elif statement in a function?

Python newbie here, and I'm having some trouble with a little beginners project I'm trying to make (also, apologies if the title of the question isn't very explanatory, I'm still learning the lingo).

The gist of the project is that based on the user's input of what "mood" they're feeling, the program will return a YouTube video of music based on that input. For example in the code below, I started with a prompt called "jazzy", which will return jazz music:

import random
import webbrowser

jazzy = [["https://www.youtube.com/watch?v=fAi7IeJG-6Y"], ["https://www.youtube.com/watch?v=bcp2MFfF_xc&t=1686s"], ["https://www.youtube.com/watch?v=eZAuY5M7J-Y"]]
funky = [["https://www.youtube.com/watch?v=ZPHoVmBIqPk"], ["https://www.youtube.com/watch?v=mVphcpIoTpc&t=940s"]]

def user_mood():
    mood = input('What mood are we in today?')
    if mood == "jazzy":
        jazz_open = webbrowser.open_new(random.choice(jazzy))
        jazz_open()
    elif mood == "funky":
        funk_open = webbrowser.open_new(random.choice(funky))
        funk_open()
    elif mood != "jazzy" or "funky":
        print("Sorry, I don't have an option for ", mood, "in my catalogue.")

user_mood()

The "jazzy" section; that is, the if statement portion of the code works perfectly. It randomly chooses from the list in jazzy no problem. However, when I try to input "funky", to get the same process going but for the "funky" list, the program simply closes (using VSCode). Trying it in the windows command prompt returns the last elif statement which says it doesn't have the input option in the catalogue.

The goal for this little project is to expand the number of genres and the number of options in the lists to a respectable size, but seeing as I'm still very new to Python, I'm not sure if using just the one function for the whole project is a good idea, or if I should split the project into numerous functions for each genre/input.

Thanks a lot in advance! :)




mercredi 21 septembre 2022

create stack with unique random numbers fast

I created a method where I generate a stack of random unique numbers. The code works but I need this to run a lot faster. Does anyone have a suggestion.

Lower is the lowest number for the random number, upper is the highest number for the random number and count is the amount of numbers I need.

I tried searching around for a better solution, but I couldn't make it work.

public static Stack<int> RandomNumbersGenerator(int lower, int upper, int count)
        {
            Stack<int> stack = new Stack<int>();
            Random rnd = new Random();
            while (count > 0)
            {
                int h = rnd.Next(lower, (upper + 1));
                if (!stack.Contains(h))
                {
                    stack.Push(h);
                    count--;
                }

            }
            return stack;
        }



$sample aggregate not functioning correctly in MongoDB

i am trying to grab a random document from my collection and I keep receiving the error:

PlanExecutor error during aggregation :: caused by :: The argument to $size must be an array, but was of type: missing

obviously not trying to use the $size aggregate just the parameter with the $sample aggregate.

[{
 $project: {
  _id: '$_id',
  sender_id: '$sender_id',
  date_time: '$date_time',
  numberOfLikes: {
   $size: '$favorited_by'
  }
 }
}, {
 $match: {
  numberOfLikes: {
   $gte: 9
  }
 }
}, {
 $lookup: {
  from: 'UsedClessics',
  localField: '_id',
  foreignField: 'reply_id',
  as: 'UsedClessics'
 }
}, {
 $match: {
  'UsedClessics.type': {
   $ne: 'reply'
  }
 }
}, {
 $match: {
  sender_id: {
   $ne: 'system'
  }
 }
}, {
 $match: {
  sender_id: {
   $ne: '848846'
  }
 }
}, {
 $sample: {
  size: 1
 }
}]



mardi 20 septembre 2022

Unwrapped optional keeps refreshing / Working with optionals, arrays and randomElement()

I was wondering how you would approach making the following application work:

  • You have an array where you take a random element.
  • You make it multiply with a random number.
  • You have to input the answer and then whether or not you were right you get a score point.

Trying to make it work I stumbled upon the following problems:

  • When actually running the program every time the view was updated from typing something into the TextField, it caused the optional to keep getting unwrapped and therefor kept updating the random number which is not the idea behind the program.
  • How do I check whether or not the final result is correct? I can't use "myNum2" since it only exists inside the closure

Here's my code:

    
    @State var answerVar = ""
    @State var myNum = Int.random(in: 0...12)
    let numArray = [2,3,4,5] // this array will be dynamically filled in real implementation
    
    var body: some View {
        VStack {
            List {
                Text("Calculate")
                    .font(.largeTitle)
                
                HStack(alignment: .center) {
                    if let myNum2 = numArray.randomElement() {
                        Text("\(myNum) * \(myNum2) = ") // how can i make it so it doesn't reload every time i type an answer?
                    }
                    
                    TextField("Answer", text: $answerVar)
                        .multilineTextAlignment(.trailing)
                }
                
                HStack {
                    if Int(answerVar) == myNum * myNum2 { //how can i reuse the randomly picked element from array without unwrapping again?
                        Text("Correct")
                    } else {
                        Text("Wrong")
                    }
                    Spacer()
                    Button(action: {
                        answerVar = ""
                        myNum = Int.random(in: 0...12)
                    }, label: {
                        Text("Submit")
                            .foregroundColor(.white)
                            .shadow(radius: 1)
                            .frame(width: 70, height: 40)
                            .background(.blue)
                            .cornerRadius(15)
                            .bold()
                    })
                }
            }
        }
    }
} ```



Is there a way to vectorize this loop?

I'm trying to simulate the results of two different dice. One die is fair (i.e. the probability of each number is 1/6), but the other isn't.

I have a numpy array with 0's and 1's saying which die is used every time, 0 being the fair one and 1 the other. I'd like to compute another numpy array with the results. In order to do this task, I have used the following code:

def dice_simulator(dices : np.array) -> np.array:
  n = len(dices)
  results = np.zeros(n)
  i = 0
  for dice in np.nditer(dices):
    if dice:
      results[i] = rnd.choice(6, p = [1/12, 1/12, 1/12, 1/4, 1/4, 1/4]) + 1
    else:
      results[i] = rnd.choice(6) + 1
    i += 1
  return results

This takes a lot of time compared to the rest of the program, and think it is because I'm iterating over a numpy array instead of using vectorization of operations. Can anyone help me with that?




I try to display Random Strings with random.randint or random.randstr python

I try to make an app that is generating random questions when i press the button "ask" but i am stuck at this error..

{ return self.randrange(a, b+1) TypeError: can only concatenate str (not "int") to str }

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
import random


class MyRoot(BoxLayout):

    def __init__(self):
        super(MyRoot, self).__init__()

    def generate_question(self):
        self.random_question.text = str(random.randint("Is a car a car?", "Is a color a color"))


class RandomQuestionApp(App):
    def build(self):
        return MyRoot()





randomApp = RandomQuestionApp()
RandomQuestionApp().run()



<MyRoot>:
    random_question: random_question
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Question"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_question
            text: "_"
            font_size: 30

        Button:
            text: "Ask"
            font_size: 15
            on_press: root.generate_question()


THANKS !!




lundi 19 septembre 2022

Difference between random() and randint() when need to generate weighted sampling

I need to generate n indices, from 0 to n-1 randomly (the goal is to later use the generated index to implement weighted sampling).

First, I used randint(0, n-1). However it did not pass the test for the problem https://leetcode.com/problems/random-pick-with-weight/

The solution passes when the index is generated using random.random() since the latter outputs the float, which you then look for in the array:

def pickIndex(self) -> int:
    
    random_index_not_working = randint(0, self.prefixed_weights[-1])
    random_index = self.prefixed_weights[-1] * random.random()
    
    print(random_index_not_working, random_index)

Output:

23 6.6781083742021154

0 11.119979387153617

14 22.958546966743995

So for the true "weighted" sampling to work, I apparently need to use float.

The rest of the solution:

from random import randint, random 
from itertools import accumulate

def __init__(self, w: List[int]):
    self.prefixed_weights = []
    for ww in accumulate(w):
        self.prefixed_weights.append(ww)
            
def find_index(self, random_index):
    # 0..8 [1, 4, 9] 3
    
    left = 0
    right = len(self.prefixed_weights) - 1
    
    while left <= right:
        mid = (left + right) // 2
        
        if self.prefixed_weights[mid] > random_index:
            # search in the left part
            if mid - 1 >= 0 and self.prefixed_weights[mid-1] > random_index:
                right = mid - 1
            else:
                return mid
        elif self.prefixed_weights[mid] < random_index:
            # search in the right part
            if mid + 1 < len(self.prefixed_weights) and self.prefixed_weights[mid+1] < random_index:
                left = mid + 1
            else:
                return mid+1
        else:
            return mid
    
           

Why generating integer indices using randint() between [0..n-1] does not yield the same probability distribution as compared to generating a float between (0,1) using random()and multiplying it by n?




How to display random questions in KV label or in a KV Layout

I am new in PY and KV and i am trying to make a quizz app . I learned how to generate random questions in PY and to be displayed in the IDE console but now i am trying to display them in a KV Layout and if the answer is the right one , a random question to be generated and now i am stuck at this step... and yep.. HEEELP PLEASE :(( !!


from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager

from kivy.config import Config
Config.set("graphics", "Resizable", "1")


class Q1(Screen):
    pass


# Random code

import random

def randomq():
    print("How many questions ?")
    numberOfProblems = input()
    numberOfProblems = int(numberOfProblems)

    if numberOfProblems > 3:
        print("You can answer only to 3 questions.")
        randomq()
    if numberOfProblems <= 0:
        print("Finish")
        exit(0)
    else:
        for questionsWanted in range(numberOfProblems):
            question1 = 1
            question2 = 2
            question3 = 3
            question4 = 4

            questionNumber = random.randint(1,2)

            if questionNumber == 1:
                question1Answer = input("What is color of grass ?")
                if question1Answer == "green":
                    print("Correct")
                else:
                    ("Not correct")

            if questionNumber == 2:
                question2Answer = input("What is a car ?")
                if question2Answer == "A car" or question2Answer == "car":
                    print("Correct")
                else:
                    ("Not correct")

randomq()



class ScreenManagement(ScreenManager):
    pass



class QuizApp(App):
    pass





QuizApp().run()

#:import random random

ScreenManagement:
    Q1:

<Q1>:
    FloatLayout:
        orientation: "vertical"

        Label:
            text: "Is the earth round ?"
            font_size: self.width/25
            pos_hint: {"x":0, "y":0.2}

        Button:
            text: "Yes"
            font_size: self.width/30
            size_hint: 0.5, 0.12
            pos_hint: {"x":0.25, "y":0.4}

        Button:
            text: "No"
            font_size: self.width/30
            size_hint: 0.5, 0.12
            pos_hint: {"x":0.25, "y":0.52}





How to convert python to Pseudocode?

I am learning how to use Pseudocode and have made a randomly generated 10 x 10 grid in python. I am trying to convert my python script into Pseudocode. Any suggestions?, Thanks

int main(void)
{
  int i = 0;
  while (i <= 99)
  {
    printf("%02d ", i);
    
    i++;

    if (i % 10 == 0) printf("\n");
  }

  return 0;
}

 



VBA - Generate random number only to 3 digits with Norm_inv OR ptimize the function

I wrote a macro for generate random number from sample. The RNG core is:

For i = 6 To LR

Set row = RANGE(Cells(i, 8), Cells(i, LC))

prumer = Application.Average(row)
smodch = Application.stdev(row)

    
    For A = B To LCNEW
       Cells(i, A).Value = Application.Norm_Inv(Rnd(), prumer, smodch)
       Cells(i, A).Value = Application.ROUND(Cells(i, A).Value, 3)
       Cells(i, A).NumberFormat = "0.000"
    Next A
    
Next i
 

It takes a row, calculate average and stdev and then do the stuff.

But on my computer it runs very quick (like 5-10 sec for 80 rows with 10 numbers and calculating 100 more randomized) - and on older computer it runs like 5 minutes! Can I somehow calculete norm inv only to 3 digits? Or optimalize it more?

The whole code is:

Sub RNGTOX()

   Dim lastcell As RANGE
   Dim row As RANGE
   Dim i As Long
   Dim A As Long
   Dim B As Long
   Dim prumer As Variant
   Dim smodch As Variant
   Dim LR As Long
   Dim LC As Long
   Dim ocislovani As RANGE
   Dim sSIDE As Worksheet
        
 If RANGE("H6").Value = vbNullString Then
 MsgBox "Chybí data."
 Exit Sub
 End If
            
Application.ScreenUpdating = False
     
Set sSIDE = ActiveSheet
Set lastcell = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)

LR = Cells(Rows.count, 1).End(xlUp).row
LC = Cells(6, Columns.count).End(xlToLeft).Column
B = LC + 1
LCNEW = RANGE("B2").Value + 7

If LCNEW <= LC Then
MsgBox "Počet už je dosažený. Není třeba dopočítávat."
Exit Sub
Else
End If

'ocislovani souboru
Set ocislovani = sSIDE.RANGE(sSIDE.Cells(5, 8), sSIDE.Cells(5, LCNEW))

counter_cisla = 1
For Each cell_a In ocislovani
cell_a.Value = counter_cisla
counter_cisla = counter_cisla + 1
Next cell_a


'i radek, A sloupec
For i = 6 To LR

Set row = RANGE(Cells(i, 8), Cells(i, LC))

prumer = Application.Average(row)
smodch = Application.stdev(row)

    
    For A = B To LCNEW
       Cells(i, A).Value = Application.Norm_Inv(Rnd(), prumer, smodch)
       Cells(i, A).Value = Application.ROUND(Cells(i, A).Value, 3)
       Cells(i, A).NumberFormat = "0.000"
    Next A
    
Next i


RANGE("H6").Select
       
Application.ScreenUpdating = True


End Sub




dimanche 18 septembre 2022

Setting a list without writing it manually? (Python3)

I'm having some issues with my python program. I need to generate a list of numbers from 1 to 100 for use inside of a variable.

import random
import time

tries = 0
sumcoin = 0

list = (1, 100)

def run():
        while True:
                global sumcoin
                global tries
                correct = (list)
                guessed = (list)
                if guessed == correct:
                        print (f"\033[0;32;40mCorrect Guess! It was {correct}, found after {tries} attempts.\033[0;37;40m.")
                        sumcoin=sumcoin+1
                        print (f"You guessed  {sumcoin} times Correctly!")
                        tries = 0
                        sumcoin=sumcoin+1
                time.sleep(1)
                tries=tries+1
run()

The code is intended to generate a number from 1 to 100, guess it, and if it guesses wrongly then it will restart the process I will make the variable random with random.choice() or randint. This is the snippet output:

user@user:~ $ python3 list.py 
Correct Guess! It was (1, 100), found after 0 attempts..
You guessed  1 times Correctly!
Correct Guess! It was (1, 100), found after 1 attempts..
You guessed  3 times Correctly!
Correct Guess! It was (1, 100), found after 1 attempts..
You guessed  5 times Correctly!
Correct Guess! It was (1, 100), found after 1 attempts..
You guessed  7 times Correctly!
Correct Guess! It was (1, 100), found after 1 attempts..
You guessed  9 times Correctly!
Correct Guess! It was (1, 100), found after 1 attempts..
You guessed  11 times Correctly!
Correct Guess! It was (1, 100), found after 1 attempts..

As you can see, it only guessed the exact variable "(1, 100)". I am trying to make a random number out of 100 each time a new number is guessed. I searched online for the issue, but could not find any reliable results that could help me. Any and all assistance would be really, really appreciated.




PHP script that show content from random pages

  1. I need to show content from 3 pages at once in my index.php ;
  2. Extract the content from every page (only 3 pages), from line 50 (start) to 100 line (stop).
  3. Random order for the 3 content extracted.

Code for random content (shows only 1 result, not 3)

<?php
srand();
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php", "folder/content5.php", "folder/content6.php");
$rand = array_rand($files);
include ($files[$rand]);
?>

This is the code to extract content from pages:

<?php $section1 = file_get_contents("folder/content1.php", FALSE, NULL, 50, 100); echo $section1; ?>
<?php $section2 = file_get_contents("folder/content2.php", FALSE, NULL, 50, 100); echo $section2; ?>
<?php $section3 = file_get_contents("folder/content3.php", FALSE, NULL, 50, 100); echo $section3; ?>
<?php $section4 = file_get_contents("folder/content4.php", FALSE, NULL, 50, 100); echo $section4; ?>
<?php $section5 = file_get_contents("folder/content5.php", FALSE, NULL, 50, 100); echo $section5; ?>
<?php $section6 = file_get_contents("folder/content6.php", FALSE, NULL, 50, 100); echo $section6; ?>



Is there any encryption method that uses TRNGs?

I am new to asking questions so I apologize in advance for the ignorance! Firstly, can we create a true random generator whose entropy source is the loss of electrical signals that 0s and 1s cannot detect? Secondly, if we have a system that let's say could do this, could we be able to encrypt data in a way that makes people unable to decrypt with the current resources? Of course, as far as security and encryption are concerned it all depends on time. If such a system does exist, could you please point me out as I cannot find it?




Softly moving divs

I have this two blurred circles.

In the 1st step I would like to float around the screen randomly in a soft manner. There are a lot of examples with linear movements but I am imagining something more organic, think underwater. I don't really know how to go about it.

In the 2nd step I would like the mouse position to slightly influence those movements.

Hope someone can help me. Thanks a lot :)

 #c1{ 
  position: fixed;
  height: 150px;
  width: 150px;
  background: rgba(135,125,121,.8);
  border-radius: 50%;
  filter: blur(50px);
  transform: translate(20%, 20%);

   
   }
   
  #c2{ 
  position: fixed;
  height: 200px;
  width: 200px;
  background: rgba(135,125,21,.8);
  border-radius: 50%;
  filter: blur(50px);
  transform: translate(100%, 20%);
   
   }
<div id="c1"></div>
<div id="c2"></div>



how to get a A SUGGESTION, not just a word in python

i have a list of suggestion parsed from json which look likes ['just a suggestion', 'and this too suggestion', 'dont care, this suggestion']

and i write this code:

import json
import random
import dpath.util as dp

with open('.logs') as json_file:
    data = json.load(json_file)
    res = dp.values(data, "/posts/*/com")
    file = open(".text", "w")
    file.write(str(res))
    file.close()
    file = open(".text", "r")
    tt = file.read()
    text = random.choice(tt.split())
    print(text)

but, this give to me only words. something like care or another word from list. how do i get a random suggestion from a list?




samedi 17 septembre 2022

How to implement a benchmark for a java mergesort program?

I want to implement a benchmark where the Method MergeSort and it's performance is measured. I have tried to fill the array that is to be mergesorted with random numbers but when the code is run the array prints the same random number 10 times. Why is this?
PS. I can't post the entire program I have written. Stackoverflow is saying it's too much code.

    public static void main(String[] args)
    {
        int arraySize = 10;
        int[] a = new int[arraySize];
        int k = 1000;
        int m = 1000;
        Random rnd = new Random();

        for (int j = 0; j < k; j++)
        {
            // fill the arraySize array with random numbers 
            for (int i = 0; i < 10*m; i++)
            {
                Arrays.fill(a, rnd.nextInt());
            }
        }

        long startTime = System.nanoTime();
        // array with predefined numbers and size
        //int[] a = { 11, 30, 24, 7, 31, 16, 39, 41 };
        int n = a.length;
        MergeSort m1 = new MergeSort();
        System.out.println("\nBefore sorting array elements are: ");
        m1.printArray(a, n);
        m1.mergeSort(a, 0, n - 1);

        long endTime = System.nanoTime();
        long timeElapsed = endTime - startTime;

        System.out.println("\n\nExecution time in nanoseconds: " + timeElapsed);
        System.out.println("Execution time in milliseconds: " + timeElapsed / 1000000);

        System.out.println("\nAfter sorting array elements are:");
        m1.printArray(a, n);
    }
}



Display image from ACF gallery only if it has meta field

I have an ACF image gallery and have set up a True / False (1/0) custom field to image attachments named "featured_image". Inside the gallery, several images are selected as the featured image while others are not.

What I would like to achieve is to randomly select one of the images which has the "featured_image" custom field as true.

My code thus far is included below, however I cannot get it to work by selecting only images from the gallery marked as "featured_image", or know how to make the selection random. Help is appreciated!

        <?php 
        $images = get_field('project_documentation', 'option');
        
        if( $images ): ?>
        <?php 
        $i = 0;
        foreach( $images as $image ): 
        $featured = get_field('featured_image', $image['id']);
        
        if ($featured == '1' ) { ?>
        
        <div class="gallery-image">
        <a href="<?php echo $image['url']; ?>"><img src="<?php echo $image['sizes']['large']; ?>" alt="<?php echo $image['alt']; ?>" /></a>
        </div>
        
        <?php } $i++; endforeach; ?>
        <?php endif; ?>



TypeError: Message=int() argument must be a string, a bytes-like object or a real number, not 'builtin_function_or_method'

So I am trying to make a random sample generator and I've got the following functions just for the sampling functions but it doesn't seem to work? (I'm trying to challenge myself by not using numpy or import random at all. However I am allowed to use import math

This is my pseudo number functions as a pre set-up incase something there is wrong:

def fakenpzeros(size):
    rows, cols = 1, size
    matrix = [([0]*cols) for i in range(rows)]
    return matrix
def pseudo_uniform(low = 0,
                   high = 1,
                   seed = 123456789,
                   size = 1):
    #generates me a number thats uniform between the high and low limits I've set
    return low + (high - low) * pseudo_uniform_good(seed = seed, size = size)
def pseudo_uniform_bad(mult = 5,
                       mod = 11,
                       seed = 1,
                       size = 1):
    U = fakenpzeros(size)
    x = (seed * mult + 1) % mod
    U[0] = x / mod
    for i in range(1, size):
        x = (x * mult + 1) % mod
        U[i] = x / mod
    return U
def pseudo_uniform_good(mult = 16807,
                        mod = (2 ** 31) - 1,
                        seed = 123456789,
                        size = 1):
    U = fakenpzeros(size)
    x = (seed * mult + 1) % mod
    U[0] = x / mod
    for i in range(1, size):
        x = (x * mult + 1) % mod
        U[i] = x / mod
    return U

Then this is my code for the random sampling

def randsamp(x):
    #Sets a seed based on the decimal point of your system clock, solves the rand.seed problem without introducing the random library
    t = time.perf_counter
    seed = int(10**9*float(str(t-int(t))[0:]))
    #makes an index of random smaples
    l = len(x)
    s = pseudo_uniform(low=0, high=l, seed=seed, size = 1)
    idx = int(s)
    return (x[idx])

I got an error of:

Message=int() argument must be a string, a bytes-like object or a real number, not 'builtin_function_or_method'

Could someone tell me what's wrong here? I've searched up this error but similar errors are like 'not list' or 'not NoneType' and none of their solutions seem to help me.

The specific line of code that is the problem is:

seed = int(10**9*float(str(t-int(t))[0:]))



vendredi 16 septembre 2022

random.shuffle erasing items and not shuffling properly

I am initializing two multivariate gaussian distributions like so and trying to implement a machine learning algorithm to draw a decision boundary between the classes:

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

mu0 = [-2,-2]
mu1 = [2, 2]
cov = np.array([[1, 0],[0, 1]]) 
X = np.random.randn(10,2)
L = np.linalg.cholesky(cov)
Y0 = mu0 + X@L.T 
Y1 = mu1 + X@L.T

I have two separated circles and I am trying to stack Y0 and Y1, shuffle them, and then break them into training and testing splits. First I append the class labels to the data, and then stack.

n,m = Y1.shape
class0 = np.zeros((n,1))
class1 = np.ones((n,1))
Y_0 = np.hstack((Y0,class0))
Y_1 = np.hstack((Y1,class1))

data = np.vstack((Y_0,Y_1))

Now when i try to call random.shuffle(data) the zero class takes over and I get a small number of class one instances.

random.shuffle(data)

Here is my data before shuffling:

print(data)
[[-3.16184428 -1.89491433  0.        ]
 [ 0.2710061  -1.41000924  0.        ]
 [-3.50742027 -2.04238337  0.        ]
 [-1.39966859 -1.57430259  0.        ]
 [-0.98356629 -3.02299622  0.        ]
 [-0.49583458 -1.64067853  0.        ]
 [-2.62577229 -2.32941225  0.        ]
 [-1.16005269 -2.76429318  0.        ]
 [-1.88618759 -2.79178253  0.        ]
 [-1.34790868 -2.10294791  0.        ]
 [ 0.83815572  2.10508567  1.        ]
 [ 4.2710061   2.58999076  1.        ]
 [ 0.49257973  1.95761663  1.        ]
 [ 2.60033141  2.42569741  1.        ]
 [ 3.01643371  0.97700378  1.        ]
 [ 3.50416542  2.35932147  1.        ]
 [ 1.37422771  1.67058775  1.        ]
 [ 2.83994731  1.23570682  1.        ]
 [ 2.11381241  1.20821747  1.        ]
 [ 2.65209132  1.89705209  1.        ]]

and after shufffling:

data
array([[-0.335667  , -0.60826166,  0.        ],
       [-0.335667  , -0.60826166,  0.        ],
       [-0.335667  , -0.60826166,  0.        ],
       [-0.335667  , -0.60826166,  0.        ],
       [-2.22547604, -1.62833794,  0.        ],
       [-3.3287687 , -2.37694753,  0.        ],
       [-3.2915737 , -1.31558952,  0.        ],
       [-2.23912202, -1.54625136,  0.        ],
       [-0.335667  , -0.60826166,  0.        ],
       [-2.23912202, -1.54625136,  0.        ],
       [-2.11217077, -2.70157476,  0.        ],
       [-3.25714184, -2.7679462 ,  0.        ],
       [-3.2915737 , -1.31558952,  0.        ],
       [-2.22547604, -1.62833794,  0.        ],
       [ 0.73756329,  1.46127708,  1.        ],
       [ 1.88782923,  1.29842524,  1.        ],
       [ 1.77452396,  2.37166206,  1.        ],
       [ 1.77452396,  2.37166206,  1.        ],
       [ 3.664333  ,  3.39173834,  1.        ],
       [ 3.664333  ,  3.39173834,  1.        ]])

Why is random.shuffle deleting my data? I just need all twenty rows to be shuffled, but it is repeating lines and i am losing data. i'm not setting random.shuffle to a variable and am simply just calling random.shuffle(data). Are there any other ways to simply shuffle my data?




How To Generate Random Unique Numbers In Java [closed]

How do I generate random unique numbers within a range of 999999 without repetitions in Java?




How to generate 4 digit number as per regex

how to generate a 4-digit random pin which should be valid as per regex in java

For Example :

Regex is : ^(?!(.)\1{3})(?!19|20)(?!0123|1234|2345|3456|4567|5678|6789|7890|0987|9876|8765|7654|6543|5432|4321|3210)\d{4}$

String id = String.format("%04d", random.nextInt(10000));

using random generator it can generate any number which can violate the PIN rule

Like these should not be generated: 0123, 7890, 0987

Is there any way to generate PIN which should be valid as per regex ?




generating quasi-random sequences of events in R

I am trying to write a function in R that will generate random events over time following these criteria:

  1. There are N initial events (say 10)
  2. All events have roughly the same probability at the beginning (obviously summing to 1)
  3. Randomly one of the events has an increase in probability (say twice the currently most probable event)
  4. Over time the probability of all events changes with the one that has been experienced the most decreasing at a higher rate (say 0.3)
  5. Randomly a new event is introduced and its probability is far higher than all the others (say 0.5)

So far I managed to write part of the code but I am very far from my goal and I don't even think what I have tried so far is really correct.

 
#install.packages("randtoolbox")
library(randtoolbox)

quasi_random_events<-function(n_events=10,rateIncrease=2,rateDecrease=0.3,newEvent=0.5, iter=5){
  #1) There are N initial events (say 10)
  events<-LETTERS[1:n_events]
  # 2)All events have roughly the same probability at the beginning (sum to 1)
  n <-length(events)
  #Sobol sequence
  x <- sobol(n = n)
  probs <- x / sum(x)
  sum(probs) == 1
  

  res<-lapply(1:iter,function(x){
  # 3)Randomly one of the events has an increase in probability (say twice the currently most probable event)
  up=sample(events,1)
  probUp=which(events==up)
  probs[probUp]*rateIncrease

  #------------- here I should update all the other probabilities to sum to 1
  #???????
    
  # 4)Over time the probability of all events changes with the one that has been experienced the most decreasing at a higher rate (say 0.3)
  #?????
  # 5)Randomly a new event is introduced and its probability is far higher then all the others (say 0.5)
  #????
  
  
  })
  return(res)
}

The final results should be a function that at each iteration updates the previous probability as described from points 3 to 5.




jeudi 15 septembre 2022

JavaScript | Creating a random string of numbers and letters for a password everyday that stays the same for 24 hours

I'm looking to create an HTML page that displays a random string of characters that only changes every 24 hours automatically. This page will be used by another website that will use it as a password. I've tried some stuff but I can't get it to stay for 24 hours. It keeps changing Everytime I refresh the page.




Randomly generating different list from list

first I created a list called “citys” then it tried to swap randomly two elements in the “citys” list for 5 times and at the same time tried to store the new lists in the “number_of_citys” but it turns out bad every time it loops, it insert the last swapped arrays only. I used this randomly generated list , citys= [[1,2], [3,4],[1,3],[5,2]] , to create another list. And I expected my list to be, orders_of_citys=[[[1,2], [5,2],[1,3][3,4]] , [[5,2], [1,2],[1,3][3,4]],[ [1,3], [1,2],[5,2][3,4]], [[3,4], [1,2],[5,2][1,3]], [1,3], [1,2],[5,2][3,4]] ] but I got the following order_of_citys =[[[1,3], [1,2],[5,2][3,4]], [1,3], [1,2],[5,2][3,4]], [1,3], [1,2],[5,2][3,4]] ,[1,3], [1,2],[5,2][3,4]], [1,3], [1,2],[5,2][3,4]]] I have used append(), +=, and insert built in function and operators but I still get the same array. please I would like some one to point me my problem.The code I wrote is the following.

import random
  
citys = []
number_of_cities = 5
orders_of_citys = []
pop = 5

#give random place for cities on 2D plane
for i in range(number_of_cities):
        citys.append( [ random.randint(0, 1000), random.randint(0, 1000)])

#suffle  points (citys) position to get different path
def swap(c, a, b):
        value = c[a]
        c[a] = c[b]
        c[b] = value
        return c

for j in range(pop):
    a = random.randint(0, len(citys)-1)
    b= random.randint(0, len(citys)-1)
    new_path = swap(citys, a, b)
    orders_of_citys.append(new_path)

Thanks!




How to generate random positive real number in Julia?

I wanna fill my array in Julia by positive real numbers. But I found information only how to do it with integers or real numbers (including negatives). Is it possible? Thanks!




How can i generate a new random number after one round in c#?

I have a problem with my programm. I want to write a random number guessing game. I have actually everything but when i ask the user if he/she wants to do it again and he/she says yes, the same number from the 1. round is also in the second round. Like:

  • Write your number down: 90.
  • Great u guessed the number!
  • Do u want to play again [y|n] y.
  • write another Number: 90.
  • Great u guessed the number!

enter image description here




mercredi 14 septembre 2022

Concat items from two list randomly, in random order, without replacement in Python 3

I tried to make two lists that randomly concat to each other, which created a new list of unique series. What I did so far:

import random
import itertools

letter_list = ['ABCD','EFGH','IJKL','MNOP'] #List of series of letters

number_list = random.sample(range(1000, 9999), 4) #create a list of four 4-digits numbers. 

new_list = list(itertools.product(letter_list,number_list))

print(new_list)

Output I have so far:

('ABCD', 1568) ('EFGH', 9173) ('IJKL', 8897) ('MNOP', 7379)

Output that I want:

[EFGH8897,IJKL9173,ABCD7379,MNOP1568]

A random concat from the letter list and number list, randomly chosen and without replacement. the new list in random order as well.




mardi 13 septembre 2022

Using While Loop in __init__ to meet specific condition in Python

I am working with a senior developer who pointed out that the below code written is not the best practice.

import random


class RandomNumbers:

    def __init__(self):
        self.BASE_TEXT = ''' {} + {} '''
        while True:
            self.A = random.randint(1, 10)
            self.B = random.randint(1, 5)

            if self.A > self.B:
                break

    def generate(self):
        return self.BASE_TEXT(self.A, self.B)

I want to ensure that random number A is always greater than random number B. To meet this condition I can't think of any other way apart from using while with an if condition.

The comment I got from the senior developer is that

Neither do I understand what he means by that nor do I see any problems with code with an API response.

you cannot have something that runs randomly on the class constructor, especially since we will need an API response for it

Can someone please review the code and validate that there is no issue with the code?




Adding random values to python list elements

I have a list :

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

I want to add a different random number to each element in the list using np.random.randn() I start by creating another list containing the rando values by using:

noise = []
for i in range(len(a)):
    b = (random_noise * np.random.randn())
    noise.append(b)

And the add the two lists

a + b 

My question is, is there a simplified method in which i can add the noise directly to a elements without the need to creating the loop, in seek of saving time in the large problems.




Generating unique random number with condition Snowflake

I would like to generate some UNIQUE random numbers in Snowflake with a specific starting/ending point. I would like for the numbers to start at 1,000 and end at 1,000,000.

Another requirement is joining a string at the beginning of these numbers.

So far I have been using this statement:

SELECT CONCAT('TEST-' , uniform(10000, 99000, RANDOM()));

Which works as expected and gives me the output of e.g. 'TEST-31633'.

However the problem is I am generating these for a large amount of rows, and I need for them to be completely unique.

I have heard of the 'SEQ1' functions however not sure how I could specify a starting point as well as adding a 'TEST-' with the CONCAT function at the beginning. Ideally they won't be in a strict sequence but differ from each other.

Thank You




Selecting a random value from vector but excluding particular values

I thought this was an easy one but I cannot find any solution for it.

I have this vector called cues= ["R" "B" "C" "P" "Y" "G"]; from which I want to randomly select one value, but excluding one (or two) of the values each time.

For example, I would like to get a random value from the vector excluding the "R" value, or in a second condition I would like "R" and "Y" not to be selected from the sample.

I have tried using randsample and randperm but neither of them seems to include this option. Any help very much appreciated!

Thanks, Mikel




Is getrandmax() a fix number?

In getrandmax() i get a value max of 2147483647
It is the same on all the computer, or does it change and can be increased/decresed ?




SELECT returns multiple answers

I have names table with columns id, name and last_name. So what i'm trying to do is select random name from it, i tried this:

SELECT name FROM names WHERE id = floor(random()*18 + 1);

But it returns no value, one, two or even three names sometimes, why is this happening and how can i fix it




lundi 12 septembre 2022

Best way to generate unique Random number in Java

I have to generate unique serial numbers for users consisting of 12 to 13 digits. I want to use random number generator in Java giving the system. Time in milliseconds as a seed to it. Please let me know about the best practice for doing so. What I did was like this

Random serialNo = new Random(System.currentTimeMillis());
System.out.println("serial number is "+serialNo);

Output came out as: serial number is java.util.Random@13d8cc98




Generating random numbers with the Trusted Executable Environment in Android

When developing high security apps using a hardware based encryption on Android its nice to have the Keystore API for encryption functionalities. However when needing to use random values it seams like the recomended way to do it is to use SecureRandom class which seams to be a software based solution.

How is it that it doesn't seam to be possible to have hardware secure random numbers on Android taking advantage of the hardware based solution for encryption that already exists?




Generating the same random number per column values

I have a table which in which I would like to generate random numbers in a specific format (e.g. TEST-10256). For which I have been using the below:

concat('TEST-' , uniform(10000, 99000, RANDOM()))

However I now want to update a table with these random numbers based on two columns, so the desired outcome would be this:

enter image description here

I am not sure how to keep the same random value per previously matching it on the same values in ROW1 & ROW2.




Python - How to generate Random Natural Number with no limit on Upper Bound

I want to generate random natural number without any upper bound.

For example I can generate random natural number using random.randint(1, 1000) but I don't want to specify the upper bound. How can I achieve that?




dimanche 11 septembre 2022

Is there a way to get a random key and its respective value from a TreeMap?

I want to get a random key and its respective value from a TreeMap. The idea is that a random generator would pick a key and display that value. The key is a string and the value is a double. For example myMap.put("CanSoupWt", 1.0).




Image Changing On Reload [Without Typing All Names Of Images]

Im not the best coder. So I want something pretty simple, and it would help alot if you can even explain the process and what each part means


so say i have the .html file Basic Example

then i have a folder containing images with the prefix "image" then followed by a number (example - "image1.png", "image2.png")

everytime the page reloads itll just pick a random one. Ive seen a bunch of similar posts but they have you write out all the images paths in a table or whatever, I dont wanna do that, is there an easier way. Ive done something with .gif files but i lost that html file somewhere.




Given a list of random variable and an expected value, how to generate probability distribution in python

I have a list of random values x_1,x_2, ... x_n and an expected value X.I wanna write a function that takes these 2 things and randomly generates one of the many probability distributions that meets the above mentioned constraint.

Rephrasing the question as generate a vector p of length n such that

0 <= p_i < =1

| p | = 1

p.x = X

Using information I found here I hacked together the below solution, but it doesn't work as the probabilities are not b/w 0 and 1

def normal_random_distribution(data_array, data_len, X_array, expd_vl):
    e_mat = np.concatenate(([X_array], [np.ones(data_len)]), axis = 0)
    f_mat = np.array([expd_vl, 1])
    v_vec = np.linalg.lstsq(e_mat, f_mat,rcond=None)[0]
    e_null = sla.null_space(e_mat)
    lamda_lower = np.linalg.pinv(e_null) @ (-1 * v_vec)
    lamda_upper = np.linalg.pinv(e_null) @ ( 1 - v_vec)
    lamda = lamda_lower + random.random()*(lamda_upper - lamda_lower)
    sol = v_vec + e_null @ lamda
    return sol

How can I generate p ? The sol has l1 norm 1, and |sol * x| = X. I was hoping interpolating b/w lamda_lower and lamda_upper would make it b/w 0 and 1 but it does not.




Grammatically correct indefinite article in Python

I am creating a random sentence generator that can apply the correct indefinite article (a, an) to the sentence. But I am getting results such as these: I eat a apple. I ride an bike. What am I doing wrong?

Import random
def main():
    pronoun = ["I ", "You "]
    verb = ["kick ", "ride", "eat "]
    noun = [" ball.", " bike.", " apple.", " elephant."]
    ind_art = "an" if random.choice(noun[0]).lower() in "aeiou" else "a"

    a = random.choice(pronoun)
    b = random.choice(verb)
    c = ind_art
    d = random.choice(noun)

    print(a+b+c+d)
main()



How to generate huge dimension uniform distribution over small range of int in C++ fastly?

My problem is generating N dimensional array, N is huge, more than 10^8, each dimension lies at i.i.d uniform distribution over 1~q(or 0~q-1), where q is very small, q<=2^4. And array must be good statistically. So the basic soltuion is

constexpr auto N = 1000000000UZ;
constexpr auto q = 12;
std::array<std::uint8_t, N> Array{};
std::random_device Device{};
std::mt19937_64 Eng{Device()};
std::uniform_int_distribution<std::uint8_t> Dis(0, q);
std::ranges::generate(Array, [&]{return Dis(Eng);});

But the problem lies in performance, I have several plans to improve it:

  1. because s=q^8<=2^32 so, we use
std::uniform_int_distribution<std::uint8_t> Dis(0, s);

add decompose the result t<q^8 into 8 different t_i<q, but this decomposition is not straightforward, and may have performance flaw in decomposition.

  1. use boost::random::uniform_smallint, but I don't know how much improvement will be? this cann't be used together with method 1.

  2. use multi-threading like openmp or <thread>, but C++ PRNG may not be thread-safe, so it's hard to write to my knowledge.

  3. use other generator such as pcg32 or anything else, but these are not thread-safe as well.

Does anyone offer any suggestions?




samedi 10 septembre 2022

How can i run a batch script a random amount of times over a specified period each day, with a random amount of time between each run?

I have a batch script, which i initiate every day at 7am and i want this to run no longer than (approximately) 12 hours. During this 12 hour period, i want this batch script to run a python file a random amount of times (between 4 and 8). So far, i have this batch script to divide the 12 hour period by the random amount of times and run the python file with an equal time delay between each run.

This is working nicely, however, i would like to try and take this a step further, whereby the Python file is run with a random time delay (subject to a minimum) between each run and the total delay during the day equals 12 hours.

I am not sure how to do this, but have an idea to start. I was thinking of having a delay 'pot' of 12hrs * 60mins = 720mins. First calculating a random number, say X, between 4 and 8. Then I need to calculate X amounts of random time delays that all add up to 720 and each delay is a minimum of say 30. Any help or pointers would be appreciated.

So far, my batch script looks like this:

REM Generate random integer between 4 and 8
set /a rand_n=%random% %%5 + 3
echo %rand_n%

REM Calculate interval
set /a interval=(12*60*60)/(%rand_n%)
echo %interval%


REM for /l %%x in range(%rand_n%) do (
for /l %%i in (1,1,%rand_n%) do (

    REM Delay
    timeout %interval%

    REM Run Python script
    py python_file.py
    
    )



vendredi 9 septembre 2022

Memory usage of `numpy.random`

Consider the following script:

import numpy as np
import tracemalloc

def zero_mem():
    a = np.zeros((100, 100))

def nonzero_mem():
    b = np.random.randn(100, 100)


if __name__ == "__main__":
    tracemalloc.start()
    zero_mem()
    print(tracemalloc.get_traced_memory())
    tracemalloc.stop()

    tracemalloc.start()
    nonzero_mem()
    print(tracemalloc.get_traced_memory())
    tracemalloc.stop()

The output running numpy 1.22.2 on python 3.8.10 is

(0, 80096)
(72, 80168)

The question is: why isn't the second row (0, 80168)? In other words: why is there memory still in use after nonzero_mem(), unlike when calling zero_mem()?




jeudi 8 septembre 2022

Normally distributed vector given mean, stddev|variance

how to do this in torch

 np.random.normal(loc=mean,scale=stdev,size=vsize)

i.e. by providing mean, stddev or variance




Trying to make two turtles move randomly in a square and saying when they're close to each other

So my assignement is to:

  1. make a blue rectangle
  2. write a function that makes the turle move in a random direction within an interval of 90 degrees and move forward in a random interval of 0-25
  3. create a blue square
  4. Move the turle to a random point in the square
  5. Code so the turtle moves back inside the square if it leaves it
  6. Create an additonal turle (both should have different colors)
  7. Use the same statement to move both turtles (with the move_random function) 500 times
  8. if the turtles are closer than 50 units - print a string that counts the number of times they are 50 units close.

This is what it should look like: enter image description here

I've added some comments to explain my thought process

Also i get an error saying that "else" is invalid syntax

Any and all help is appreciated

The code:

import turtle

import random

#makes the jump function
def jump(t, x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()  

#creares a turtle at a defined place    
def make_turtle(x, y):
    t = turtle.Turtle()
    jump(t, x, y)    # Use of the function defined above
    return t

#function to create a rectangle and fill it with a color
def rectangle(x, y, width, height, color):
    t = make_turtle(x, y)
    t.speed(0)
    t.hideturtle()
    t.fillcolor(color)
    t.begin_fill()
    for dist in [width, height, width, height]:
        t.forward(dist)
        t.left(90)
    t.end_fill()
    
#function to move turtle in a random heading (90 degree interval) between 0--25 units forward
#While also making it turn around if it is outside of the square
def move_random(t):
    if abs(t.pos()[0]) >= 250 or abs(t.pos()[1]) >= 250:
        target = (0, 0)
        d =  (0,0)
    t.setheading(d)
    else:
        ini = t.heading()
        new = rd.randint(ini - 45, ini + 45)
        t.setheading(new)
        t.forward(rd.randint(0, 25))
    
 #creates the square and both turtles   
    t = make_turtle(0 , 0)
    t.color("green")
    t2 = make_turtle(0 , 0) 
    t2.color("black")
    rectangle(-250, -250, 500, 500, "lightblue")
    jump(t, rd.randint(-250, 250), rd.randint(-250, 250))
    jump(t2, rd.randint(-250, 250), rd.randint(-250, 250)) #jumps the turles randomly in the square
    meet = 0
    for i in range(1, 501): #makes the turtles move randomly as specified above
        move_random(t)
        move_random(t2)
    if t.distance(t2) < 50: 
        t.write("close")
        meet += 1

print(str(meet), "close encounter") #prints the amount of times they are close to each other



C# Random Floating Point Numbers

Write a program that displays an array of random floating point numbers of size 5 rows and 6 columns.

Each number has to be randomly generated. Each number has to have exactly two digits to the right of decimal point (e.g. 13.14). The numbers generated are between 5 and 19. If the number is odd, the background color should be Blue. If the number is even, the background color should be Red. If the fraction part of the generated number is less than .6 then that number should be skipped (i.e. not displayed). Another number should be generated to replace it. Use the "continue" key word is C# to achieve this. You are not allowed to use the syntax of arrays in C# for this HAW. The display should be format in an array style 5 different lines on the console, each line will have 6 numbers of each row. Make sure to format the spacing correctly. Take care of uneven rows




mercredi 7 septembre 2022

Get random value sets from table without using cursor or While loop

I have a table with 5 columns: ID - int identity,col1,col2,col3,col4,(all 4 cols are varchar)

There are approx. 68,000 unique col1/col2 values. For each of these, there can be between 1 and approx. 214,000 unique col3/col4 values.

My task is to retrieve one random col3 and col4 (from the same row) for each of the unique col1/col2 values.

Is it possible to accomplish this without using a While loop or a cursor? I've done some research and know how to get random values (and the identity column helps with that), but the only way I can see to do this is to go thru the 68,000 unique col1/col2 values 1 by 1, and grab a random col3/col4 value from each.

Also, these row counts are for preliminary development/testing (collected from 4 previous months of data). When this goes live we will be going back 27 months. So obviously, we are talking about a massive amount of data.

I've seen some mentions of using CTE's, but have not been successful in finding an example or explanation.

Thanks for your help.




Java Blackjack program to generate random outcomes for different players

I am building a blackjack program using threads in Java. I have three players, Andrew, Billy and Carla. I am supposed to output their score result after a round of cards. Where they're supposed to beat the dealer with a score that is greater than 15 but less than or equal to 21. I am having a problem outputting their results because I am trying to use the random class to produce different scores each round. Here's my code

package blackjack.client;
import blackjack.system.*;
public class Blackjack21 {
    private static int cardTotal;
    public static void main(String[]args){
    CardCounter cardCounter = new CardCounter();
    BlackJackThread b1 = new BlackJackThread("Andrew", cardTotal);
    BlackJackThread b2 = new BlackJackThread("Billy", cardTotal);
    BlackJackThread b3 = new BlackJackThread("Carla", cardTotal);
    
    b1.start();
    b2.start();
    b3.start();
    }
}

package blackjack.system;
public class BlackJackThread extends Thread{
    private CardCounter cardCounter = new CardCounter();
    private String playerName;
    private int cardTotal;
    public BlackJackThread(String playerName, int cardTotal){
        this.playerName = playerName;
        this.cardTotal = cardTotal;
    }
    
    public void run(){
        cardCounter.checkForWin(playerName, cardTotal);
    }
}

package blackjack.system;
import java.util.Random;
import java.util.*;
public class CardCounter {
    
public synchronized void checkForWin(String player, int cardTotal){
Object[] suitNumber = {2,3,4,5,6,7,8,9,"jack","king","queen"};    
String suit[] = { "Clubs", "Diamonds", "Hearts", "Spades"};
List<Object>playersHand = new ArrayList<Object>();
Random suitType = new Random(); 
int n = suitType.nextInt(4);
Random numberOnSuit = new Random();
int m = numberOnSuit.nextInt(11);
for(int i=0; i<=3; i++){
    playersHand.add(suitNumber[i]+""+suit[i]);
    if((suitNumber[m] == "jack")||(suitNumber[m]=="king"||suitNumber[m]=="queen")){
        cardTotal+= 10;
    }else{
    String wrapperObject =cardTotal+""+suitNumber[m];
    Integer unboxObject = new Integer(wrapperObject);
    cardTotal+=unboxObject;
    }
}
    if((cardTotal > 15) && (cardTotal <= 21)){
        System.out.println(player+"'s hand:"+playersHand);
        System.out.println(player+" "+cardTotal+" "+"beats dealer");
    }else{
        System.out.println(player+"'s hand:"+playersHand);
        System.out.println(player+" "+cardTotal+" "+"loses");
    }
}
}

Here's my output. I want to ensure that all three players have different scores but different outcomes every time I run the thread enter image description here




Picking a random sample out of dyads

I have a data set that includes longitudinal data of couples.

For my analysis,I have to randomly pick 1 member of each dyad. I have userID for each individual and coupleID for the respective couples.

Is there any R package/input that will make this possible?

I am completely lost here so I would appreciate every hint! Thank you so much!




How do I pass an ArrayList

New to Java coding, please bear with me. I'm trying to pass my ArrayList chosenWords held in my method getChosenWords(int length) to my method getRandom(int length). I need the ArrayList so I can chose a random index and return a random string.

Note, it's not declared in the Class fields and I am not able to change the parameters of my methods. I have to find another way to pass the ArrayList in but I'm unsure how to. The unit test uses these set parameters and I can't change parameters or the fields as other classes rely on them staying the same.

I'm pretty sure this is the line that needs changing ArrayList<String> chosenWords; and currently I have an error variable not initialised on this line. random.nextInt(chosenWords.size());

Any suggestions?

Method1

// Takes strings in ArrayList words and stores strings with char int length to ArrayList chosenWords

public ArrayList<String> getChosenWords(int length) {
       ArrayList<String> chosenWords = new ArrayList<>(); 
       
       for(String word1 : words) {
            if(word1.length() == length) {
                 chosenWords.add(word1);
            }
       }
       return chosenWords;  
}

Method2

//Returns a randomly selected string from ArrayList chosenWords

public String getRandom(int length) {
    ArrayList<String> chosenWords;
    Random random = new Random();
    int randomIndex = random.nextInt(chosenWords.size());
    return chosenWords.get(randomIndex);        
}



mardi 6 septembre 2022

Printing symbols after random function

I made a program that involves a lot of randomization.

It all works fine, except for array number 5 char a5, which includes 2 strings. There's a 5% chance of any of them appearing.

Once I execute my program, random symbols appear once in a while, if I launch it enough times, I hear the "Critical stop" error sound but no visible error.

My program has an input loop to prevent me from launching it again, which I'll keep here for ease of use.

Here's the minimal code:

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

main(){
    srand (time(NULL));
    int j, v;
    char i, mlt [6], a5[2][6] = {" x2", " x3"}; 
    do{ 
    system ("cls");
        for (j=0; j<10; j++){
            
            v = rand () % 95;
            char* b4[6] = {a5[v]};
            char mik[10] = (" ");
            
            strcpy (mlt, mik);
            strcat (mlt, *b4);
            printf (" %s\n", mlt);
        }
    printf ("Press 'n' to exit... ");
    scanf (" %s", &i);
    }
    while (i!='n' && i!='N');
}

Here's a screensnip example of a random launch (on my normal program):

output of normal code and a symbol




lundi 5 septembre 2022

HTML/CSS/JS Random Div Position without Overlap Not Working

I am attempting to make a webpage that randomly positions divs across the page on loading without them overlapping. I found code online that does exactly what I want it to, (Linked Here) but I am having issues with the code. I copied all of the components from the above link into a pre-existing site, but it does not work. All of the divs appear to be overlapping in the top right corner of the page. I would appreciate any help in making this feature work, as I would love to use it on a website I am working on.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <script src="assets/js/script.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>

</head>
<body>
    <div class="random">Div 1</div>
    <div class="random">Div 2</div>
    <div class="random">Div 3</div>
    <div class="random">Div 4</div>
    <div class="random">Div 5</div>
    <div class="random">Div 6</div>
    <div class="random">Div 7</div>
    <div class="random">Div 8</div>
    <div class="random">Div 9</div>
    <div class="random">Div 10</div>
    <div class="random">Div 11</div>
    <div class="random">Div 12</div>
</body>
</html>

CSS:

.random {
  position: absolute;
  margin: 2;
  border: 1px solid black;
  font-size: xx-large;
  top: 0px;
  left: 0pc;
  
}
.placed {
  color: red;
  border: 1px solid red;
}

JS:

;(() => {
  "use strict";
  const TRIES_PER_BOX = 50;
  const randUint = range => Math.random() * range | 0;
  const placing  = [...document.querySelectorAll(".random")].map(el => Bounds(el, 5));
  const fitted = [];
  const areaToFit = Bounds();
  var maxTries = TRIES_PER_BOX * placing.length;
  while (placing.length && maxTries > 0) {
      let i = 0;
      while (i < placing.length) {
          const box = placing[i];
          box.moveTo(randUint(areaToFit.w - box.w), randUint(areaToFit.h - box.h));
          if (fitted.every(placed => !placed.overlaps(box))) {
              fitted.push(placing.splice(i--, 1)[0].placeElement());
          } else { maxTries-- }
          i++;
      }
  } 
  function Bounds(el, pad = 0) {   
      const box = el?.getBoundingClientRect() ?? {
          left: 0, top: 0, 
          right: innerWidth, bottom: innerHeight, 
          width: innerWidth, height: innerHeight
      };
      return {
          l: box.left - pad, 
          t: box.top - pad, 
          r: box.right + pad, 
          b: box.bottom + pad,
          w: box.width + pad * 2,
          h: box.height + pad * 2,
          overlaps(bounds) { 
              return !(
                  this.l > bounds.r || 
                  this.r < bounds.l || 
                  this.t > bounds.b || 
                  this.b < bounds.t
              ); 
          },
          moveTo(x, y) {
              this.r = (this.l = x) + this.w;
              this.b = (this.t = y) + this.h;
              return this;
          },
          placeElement() {
              if (el) {
                  el.style.top = (this.t + pad) + "px";
                  el.style.left = (this.l + pad) + "px";
                  el.classList.add("placed");
              }
              return this;
          }
      };
  }
  })();