dimanche 31 décembre 2023

How does Javascript convert the result of xorshift128+ to a float value between 0 and 1 for Math.random()?

I need to write a program exploiting cryptographic insecurity of javascript's Math.random() for a CTF thing. However I do not know how javascript converts an int to a float between 0 and 1. The pseudo-randomization algorithm of javascript, as far as I understand is xorshift128+, which in python would look something like this:

def cast_to_int32(x):
    return x & 0xffffffff


def xorshift128plus():
    global state0
    global state1
    state0 = cast_to_int32(cast_to_int32(18030 * (state0 & 0xffff)) + cast_to_int32(state0 >> 16))
    state1 = cast_to_int32(cast_to_int32(30903 * (state1 & 0xffff)) + cast_to_int32(state1 >> 16))
    return cast_to_int32(cast_to_int32(state0 << 16) + (state1 & 0xffff))

However bitwise operations in this scenario are performed on integers, not floats. But the result of javascript's Math.random() is a float between 0 and 1. How does javascript convert that? I know the most intuitive thing to suggest would be a simple division by 2^32 or 2^31 but I've tried that and couldn't reproduce the results.

I tried dividing the int result by (2^31-1),(2^31),(2^32-1),(2^32) but none of these reproduced the results of Math.random() from the same state.




samedi 30 décembre 2023

How can i pass a random number generator as argument to a function that will produce several different numbers inside the function? [duplicate]

So, I have created several different random number generator functions (rng) that produce values of a random variable X which follow different distribution functions. Now, I want to experiment with the central limit theorem, and have a function (x_n) that produces n different values of X for a given distribution function, so, given the distribution function, I want to produce several different values of X, and then find their mean value.

I tried to just define a function that takes as arguments the number of values I want to generate and the function f (the rng) that I want the variable X to follow. I tried to call the RNG inside the function several times, but, of course, when I put the predefined distribution function as an argument into the x_n(n,rng), it generates only one random number, into the argument section, and then this random number is used throughout the entire run of x_n.

How can I call the rng many times inside the function x_n(n,rng) and produce many different numbers inside of it?

import random as r

#def uniform():
    #return r.random()

def x2():
    u=r.random()
    return u**(1/3)

def x_n(n,f):
    x_n=0
    for i in range(n):
        rand=f
        x_n+=rand
        #print(rand)
    return x_n/n

x_n(5,x2())
x_n(7,r.random())
x_n(20,uniform())

P.S.: One idea I had was to create random number generators that take an argument and just change the argument inside x_n()'s loop, but I was hoping there was another way, so that I can pass just r.random() as the distribution function.




lundi 18 décembre 2023

Restricted C Struct Randomizer

I am attempting to randomize members of a C struct with a few difficulties:

  1. The randomized struct may not be larger than the original one
  2. Each member has an alignment which has to be respected
  3. Members are of different sizes obviously
  4. Some members are fixed in place
  5. Members may not overlap with respect to their sizes
  6. Each member has a range in which it has to end up [min offset, max offset]

I freestyled a randomizer that respects properties 1 to 5. Also taking into account property 6 greatly complicates things. Is there an algorithm that does this kind of thing or could be abused to do it?

For context:

I have this struct representing the properties of a member of a C struct:

struct Member {
    uint32_t size;
    uint32_t offset;
    uint32_t alignment;
    uint32_t maxadd; // Max increase of offset
    uint32_t maxsub; // Max decrease of offset
};

My randomizer gets a list of objects of this struct, one object per member. It is supposed to find new, randomized offsets for each member, while not having any members overlap in the end and not translating a member by more than maxadd/maxsub.

I am not trying to randomize the strings in a struct definition. I am trying to randomize the memory layout itself. Because it is supposed to work on fully compiled binaries, the resulting layout may not consume more memory than the original struct (e.g. by translating a member by a million bytes). My randomizer also knows the size of the original struct.




Distributing random numbers with multiple conditions

My students handed in group projects. Now they are supposed to give feedback to other student's works. Each student should give feedback to two other student projects. I want to assign these projects randomly. Two conditions have to be met:

  1. A student should not give feedback to their own project.
  2. A student should not give feedback to the same project twice.
#Example Data
group <- c(1,1,1,2,2,3,3,3,4,4)
name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")
feedback1 <- c(1,1,1,2,2,3,3,3,4,4)
feedback2 <- c(1,1,1,2,2,3,3,3,4,4)
df <- data.frame(group, name, feedback1, feedback2)

As you can see, the groups are not the same size (some groups have 2 members, some have 3). I created a loop that checks if someone is about to give feedback to himself. If so, a random number is chosen from all the group numbers, until a fitting number is chosen. One occurrence of the chosen number is then removed from the group numbers and the next student is checked.

# Fill feedback1
for (i in 1:nrow(df)) {
  while (df$feedback1[i] == df$group[i]) {
    df$feedback1[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback1[i], group)]
}

This works so far:


   group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4

If I add the second condition ("students should not give feedback to the same groups") the loop fails to work:

# Fill feedback2
group <- c(1,1,1,2,2,3,3,3,4,4)

for (i in 1:nrow(df)) {
  while (df$feedback2[i] == df$group[i] & df$feedback1[i] == df$feedback2[i] ) {
    df$feedback2[i] <- sample(group, 1)
  }
  group <- group[-match(df$feedback2[i], group)]
}

I do not get an error message, but df$feedback2 just stays the same for all students:

 group name feedback1 feedback2
1      1    a         2         1
2      1    b         3         1
3      1    c         3         1
4      2    d         1         2
5      2    e         1         2
6      3    f         4         3
7      3    g         4         3
8      3    h         2         3
9      4    i         1         4
10     4    j         3         4
  1. What is the mistake in my second loop for feedback2?
  2. What would be (in general) a better way to do approach the problem?

Best regards




Issue of random background in firefox browser

I've got script of random background which is working of every browser except firefox (only mobile version). In this browser the images not covering all screen but some part.

Here is a code:

<script>function pic() {

var bgm = ['image1.webp', 'image2.webp'];

$('body').css({ 'background': 'url(' + bgm[Math.floor(Math.random() * bgm.length)] + ') no-repeat', 'background-attachment': 'fixed', 'background-position': '50% 50%', 'background-size': 'cover' }); }

pic();

Why on firefox browser (only mobile version) the image not cover all screen?




dimanche 17 décembre 2023

How to predict Random numbers

If I have some code like this:

import random
for i in range(10):
    print(randint(0,1))

Now I know the previous 10 outputs how can I predict the 11th one? I know it's possible, how can I find it?




lundi 11 décembre 2023

Excel VBA Code for lottery and duplicates

I want to make a lottery in Excel where I can draw aprox 30 random numbers between 1-1000 and where the 30 numbers aren't duplicates.

I can't figure out how to check if the Array have duplicates and run the code again if so.

I currently use below VBA code to generate random numbers/winners. I do not think this is the most efficient way but this is what i got... :)

Public Sub CommandButton1_Click()
    Dim MIN, MAX, OUT, i
    Static a, n, z
    MIN = Array(1, 1, 1, 1): MAX = Array(10, 10, 10, 10): OUT = Array("Q1", "Q2", "Q3", "Q4")
    z = UBound(MIN)
    If Not IsArray(n) Then ReDim a(z): ReDim n(z)
    For i = 0 To z
        If n(i) = 0 Then Reset a(i), n(i), MIN(i), MAX(i)
        Range(OUT(i)) = a(i)(n(i)): n(i) = n(i) - 1
    Next
End Sub

Private Sub Reset(a, n, MIN, MAX)
    Dim i, j
    Randomize: n = MAX - MIN + 1: ReDim a(1 To n)
    For i = 1 To n
        j = Rnd * (i - 1) + 1: a(i) = a(j): a(j) = i - 1 + MIN
    Next
End Sub

If you can help me or know of a better way to code this please hmu! :)

Thanks! Oskar




mercredi 6 décembre 2023

Difficulty generating unique random numbers using Python's random module [closed]

I am working on a project where I need to generate a list of unique random numbers in Python using the random module. I've tried using random.sample to achieve this, but I'm running into issues with [describe the specific problem or error].

Here's a simplified version of my code:

import random

# Some code here to initialize a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Attempt to generate a random subset of unique numbers
try:
    random_subset = random.sample(numbers, k=5)
    print(random_subset)
except ValueError as e:
    print(f"Error: {e}")

Can someone please guide me on how to properly generate a subset of unique random numbers using the random module in Python?




mardi 5 décembre 2023

Equal group randomization in groups already assigned treatment

I have a list of 80 subjects already randomized into 4 groups (1-4). Now, I want to introduce a crossover design so each subject will eventually be in all 4 groups. Tried to do this with the sample function, but I need an equal distribution of each possibility of the 3 remaining groups to be randomized.

For example: Subject A was already randomized to group 1. Now I need to randomize the remaining 3 groups (2, 3, 4) There are 6 options to randomize the 3 remaining groups: 234 243 324 342 423 432

So I need to ensure that every subject who was initially assigned to group 1 (20 subjects) gets an even distribution of one of those 6 permutations above. The same for every subject initially assigned to group 2, 3 and 4

I tried

#for loop going through each row of the dataframe
for(x in 1:nrow(crossover)) {
  #TRIAL 2
  #randomly selects an integer between 1 and 4

 y<- sample(1:4, 1, replace = TRUE)
  
  #if it equals Assigned.Arm.Index, then randomly select again
 while (y == crossover$Assigned.Arm.Index[x]){

    y <- sample(1:4, 1, replace = FALSE)
  }
  
  #set New.Arm.Index column to y
  crossover$Trial_2[x] <- y

crossover is the name of my dataframe, assigned.arm.index is the premade initial randomization. I created 3 new columns for the remaining randomization I'm trying to fill.

When i asked for help regarding equal randomization across all subjects, I was told to use the rep function, something like:

sample(rep(1:6, 4) , rep= FALSE) 

but it's not fully making sense to me. Im new to R and appreciate any help!




Finding a sum of random numbers in Excel

I have a column of 57 purchases and a column of 18 payments. Is there a way to look up which purchases total a certain amount? Example would be if I had purchases of $10, $15, and $1 in column A, and one of the payments was $26 in column B, it would be identified?

I've tried pivot tables and a variety of formulas and nothing has worked.




Running simulations on high performing computing cluster generates the same results

I am performing Gillespie simulations a thousand times which take a very long time. I decided to run 10 scripts each with 100 simulations on high performing computing clusters of my school. However, once I did this and checked the results, the list of the results from the first script are the same as the second script. Meaning if I run the same scripts twice I get the exact same list of results back. Why is this happening given the fact that Gillespie simulations generate random results?




lundi 4 décembre 2023

Dummy data: generating random text and numerical data into one csv/excel file?

So I'm trying to generate dummy data that contains 3 columns: sq. feet, price and Borough. For the first two, which are purely numerical this is fine. I have 50,000 rows of data for both on a spreadsheet. However, when I add Borough and specify random values from a list I receive the following output:

       Sq. feet    Price  Borough
0           112   345382        5
1           310   901500        5
2           215   661033        5
3           147  1038431        5
4           212   296497        5

I have not used a package associated with numerical generation like np.random.randint

Instead I used "Borough" : random.randrange(len(word))

Where have I gone wrong?

My code below

import random

import pandas as pd
import numpy as np

WORDS = ["Chelsea", "Kensington", "Westminster", "Pimlico", "Bank", "Holborn", "Camden", "Islington", "Angel", "Battersea", "Knightsbridge", "Bermondsey", "Newham"]
word = random.choice(WORDS)
np.random.seed(1)
data3 = pd.DataFrame({"Sq. feet" : np.random.randint(low=75, high=325, size=50000),
                     "Price" : np.random.randint(low=200000, high=1250000, size=50000),
                      "Borough" : random.randrange(len(word))
                     })

df = pd.DataFrame(data3)
df.to_csv("/Users/thomasmcnally/PycharmProjects/real_estate_dummy_date/realestate.csv", index=False)

print(df)

I'm expecting a random line of word values from the WORDS [], instead the return value is just the number 5. It's obviously meaningless making another module just for the text-based data and printing them in different files.




dimanche 3 décembre 2023

What are the possibilities this code can produce an output which is dangerous for my computer? [closed]

enter image description here . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 😂😂😂😂😂Seriously asking...Any idea??? never tried it though...




samedi 2 décembre 2023

Program c that generate a random number to use it in guessing_number programme [duplicate]

I need a new function on C langue ( not the one that's existe in the library) tha generate a random number , then i will use it to tell the user if the number that he entered is lower.or.higher "I'm a beginner " Thank you

New function to generate number




Random walk algorithm

I'm trying to create a program which plots the different paths and points which you can take on the Cartesian plane using the following algorithm: Starting from the origin (0, 0), in step 1, you do one of the following:

*jump 1/2 to the right or 1/2 to left or terminate where you are.

If the movement hasn't ended yet, then in step 2:

*jump 1/4 upwards or 1/4 downwards or terminate where you are.

If the movement hasn't ended yet, then in step 3:

*jump 1/8 to the right or 1/8 to the left or terminate where you are,etc.

You would essentially do this indefinitely, where in step k, if k is even and the movement has not end yet, you would jump (1/2)^k upwards or downwards. Similarly, in step k if k is odd you jump (1/2)^k to the right or left or terminate where you are.

I want to plot the set of endpoints you can reach in this way in finitely many steps. Is the following code correct? By the way,the coloured circles at the end of each path is an endpoint. Are these plotted correctly?

import numpy
import pylab
import random
import matplotlib.pyplot as plt
axes = plt.axes()
k = 50

x = numpy.zeros(k)
y = numpy.zeros(k)
lst = []
for j in range(1,30):
  for i in range(1,k):
    dir = [-1,1][random.randint(0,1)]
    if i%2!=0:
        x[i] = x[i - 1] + 1/(2**(i)) * dir
        y[i] = y[i - 1]
    else:
      x[i] = x[i - 1]
      y[i] = y[i - 1] + 1/(2**(i)) * dir
  plt.plot(x, y,marker = 'o')
plt.title("Different paths the random walk movement sequences could take")
pylab.show()

Graph of possible paths plotted




vendredi 1 décembre 2023

How can I ask a user with the scanner to insert the ammount of random numbers he/she would like to be created and sort it f. e. with bubblesort?

I am currently studying computer science in my first semester and I have an assignment I need some kind help with. I am supposed to create an array which fills in the amount of random numbers the user specifies using the java.util.Scanner. Currently my code looks like this:

package lia.prog1.exercises.set09;

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

public class SortingTool
{

    private void bubblesort(int[] arr)
    {
        int sortArray;
        int i;
        int j;
        int tempArray;

        Scanner scanner = new Scanner(System.in);
        sortArray = scanner.nextInt();
        System.out.println("How many numbers do you want to sort?");



        for (i = 0; i < (arr.length - 1); i++)
        {
            for (j = 0; j < arr.length - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    tempArray = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tempArray;
                }
            }
        }
    }

    private void insertionsort(int [] data)
    {
        int [] sorted = new int[data.length];

        for (int i = 0; i < data.length; i++)
        {
            int min = Integer.MAX_VALUE;
            for (int j = 0; j < data.length; j++)
            {
                if (min > data[j])
                {
                    int temp = min;
                    min = data[j];
                    data[j] = temp;
                }
            }
            sorted[i] = min;
        }
    }

}



Difficulty with Rock Paper Scissors game

I'm making a code in Java that is a rock-paper-scissors game. In particular, I am trying to make it so that the randomized outputs, aka if a user loses, wins, or ties, it is counted into the score.

For example, the user inputs either rock, paper, or scissors. If they choose rock, they will get a random output that determines whether or not they win, lose, or tie. If they got the output, let's say, "You chose rock. I chose paper. You lose!" I want to add that score result as "1 loss." in my while loop. However, I don't know how to make the program count the random outputs like that.

My code is below and I put comments in it to try and better explain what I want to do.

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

public class rockpaperscissors {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

while(true){

    System.out.println("Please choose (r)ock, (p)aper or (s)cissors:");
    String answer = input.nextLine();
    int win = 0;
    int lose = 0;
    int tie = 0;
    
    if(answer.equals("r")) {
        String[] str = { "You chose rock. I chose paper. You lose!", /* lose++; */ "You chose rock. I chose scissors. You win!",  /* win++; */ "You chose rock. I chose rock. We tie!"  /* tie++; */ };
        Random r = new Random();
        System.out.println(str[r.nextInt(3)]);
        
        
     
    }
    if(answer.equals("p")) {
        String[] str = { "You chose paper. I chose scissors. You lose!",  /* lose++; */ "You chose paper. I chose rock. You win!",  /* win++; */ "You chose paper. I chose paper. We tie!"  /* tie++; */ };
        Random r = new Random();
        System.out.println(str[r.nextInt(3)]);
   
  }
    if(answer.equals("s")) {
        String[] str = { "You chose scissors. I chose rock. You lose!",  /* lose++; */ "You chose scissors. I chose paper. You win!",  /* win++; */ "You chose scissors. I chose scissors. We tie!"  /* tie++; */ };
        Random r = new Random();
        System.out.println(str[r.nextInt(3)]);
   
  }
  
    
    System.out.println("Score: " + win + " win(s), " + lose + " loss(es), " + tie + " tie(s)");
  System.out.println("Play again (y/n)?"); 
   String c = input.nextLine();

   if(c.equalsIgnoreCase("n")){ 
      break;
     }

}

}
}

I've tried using switch statements, but they haven't been working out. I've also been trying to use if statements but my code never works. Please note that I'm still fairly new to java so there are functions that I am quite unfamiliar with.




jeudi 30 novembre 2023

Change URL every 10min based on redirect

I got 10 urls in a file.

I want to show each url for 10 minutes and when done start over again.

<?php

$version = "v1.01";

$linksfile = "urlrotator.txt";

$urls = file("$linksfile");
$url = rand(0, sizeof($urls) - 1);

$goto = "$urls[$url]";

header("Location: $goto");

This just rotate random.

Need to be based on time

The urlrotator.txt content look like following

nr1.html
nr2.html
nr3.html
nr4.html
nr5.html
nr6.html
nr7.html
nr8.html
nr9.html
nr10.html



mercredi 29 novembre 2023

not changing colors in java GraphicsProgram

The problem is asking me to spawn a circle on the canvas with a click. This part works fine. The next part is if i click a circle it needs to keep switching to random colors from: green, yellow, black, red , blue until the color is green. The code I wrote kinda does change the color but the change doesn't appear visually.

`import java.awt.Color; import java.awt.event.MouseEvent;

import acm.graphics.*; import acm.program.GraphicsProgram; import acm.util.RandomGenerator;

public class VAR4N5 extends GraphicsProgram {

private RandomGenerator rgen = RandomGenerator.getInstance();

private final static int CIRCLE_D = 40;
private final static int DELAY = 50;

private GOval clickedCircle = null;

public void run() {
    addMouseListeners();
}

public void mouseClicked(MouseEvent e) {

    if (getElementAt(e.getX(), e.getY()) == null) {
        drawCircle(e.getX(), e.getY());
    } else {
        clickedCircle = (GOval) getElementAt(e.getX(), e.getY());
        changeColor();
    }
}



private void drawCircle(double xClick, double yClick) {
    double x = xClick - CIRCLE_D / 2.0;
    double y = yClick - CIRCLE_D / 2.0;
    GOval circle = new GOval(CIRCLE_D, CIRCLE_D);
    circle.setFilled(true);
    circle.setFillColor(rgen.nextColor());
    add(circle, x, y);
}

private void changeColor() {
    int randomNum = 0;
    while (true) {
        randomNum = rgen.nextInt(1, 5);
        if (randomNum == 1) {
            clickedCircle.setFillColor(Color.GREEN);
            break;
        }
        if (randomNum == 2) {
            clickedCircle.setFillColor(Color.BLACK);
        }
        if (randomNum == 3) {
            clickedCircle.setFillColor(Color.YELLOW);
        }
        if (randomNum == 4) {
            clickedCircle.setFillColor(Color.RED);
        }
        if (randomNum == 5) {
            clickedCircle.setFillColor(Color.BLUE);
        }
        clickedCircle.setLocation(clickedCircle.getX(), clickedCircle.getY());
        pause(DELAY);
    }
}

}




Need help finding issue in meal generator

I have a meal generator that generates meals for 4 days of the week. There are some meals that I want to count as 2 meals because they produce leftovers. I also have some of the meals in groups (pesto, spaghetti, and tortellini are pasta) which I do not want to appear together in the output. If no pasta meals are selected, 4 meals should show up in the output. If one pasta meal appears in the output, then there should be 3 meals total: the pasta meal, and 2 non pasta meals. That means that a pasta meal cannot be selected as the 4th meal ever.

My code is split into 3 files: main.cpp

#include "include\mealSelector.h"

int main() {
    std::vector<std::string> meals = {
        "Spaghetti", "Pesto", "Frozen Pizza", "Nachos", "Potato Skins",
        "Quesadillas", "Hoagies", "Lunch meat sandwiches", "Brats",
        "Chicken, Potatoes and Broccoli", "Taquitos and Mini Corn dogs",
        "App Night", "Grilled Cheese", "Mac & Cheese", "Tortellini"
    };

    MealSelector mealSelector(meals);
    mealSelector.shuffleMeals();
    mealSelector.selectMeals();

    return 0;
}

mealSelector.cpp

#include "include/MealSelector.h"
#include <algorithm>

MealSelector::MealSelector(const std::vector<std::string>& initialMeals)
    : meals(initialMeals), mealCount(0), pastaAllowed(true) {} // Initialize [Meal Group]Allowed here

void MealSelector::shuffleMeals() {
    std::random_device rd{};
    std::seed_seq ss{ rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd() };
    std::mt19937 mt{ ss };
    std::shuffle(meals.begin(), meals.end(), mt);
}

void MealSelector::selectMeals() {
    for (const auto& meal : meals) {
        if (mealCount >= 4) {
            break; // Exit the loop once we have 4 meals
        }

        if (canSelectPastaMeal(meal) && ((mealCount < 3) || (mealCount == 3 && pastaAllowed))) {
            handleSelectedPastaMeal(meal);
        } else {
            handleRegularMeal(meal);
        }
    }
}

void MealSelector::printAndAddMeal(const std::string& meal) {
    std::cout << meal << std::endl;
    chosenMeals.insert(meal);
}

bool MealSelector::isPastaMeal(const std::string& meal) {
    return (meal == "Pesto" || meal == "Spaghetti" || meal == "Tortellini");
}

bool MealSelector::canSelectPastaMeal(const std::string& meal) {
    if (isPastaMeal(meal)) {
        if (!pastaAllowed || mealCount >= 3) {
            return false; // Disallow selecting more pasta meals if one is already selected
        }

        for (const auto& selectedMeal : lastPastaSelections) {
            if (mealCount - selectedMeal.second < 3 && meal != selectedMeal.first) {
                return false; // Check conditions for pasta meal selection
            }
        }
    }
    return true;
}

void MealSelector::handleSelectedPastaMeal(const std::string& meal) {
    if (mealCount >= 4 || !pastaAllowed) {
        return; //Exit if already selected 4 meals or if pasta is not allowed
    }

    //Check if the pasta meal is allowed based on previous selections
    if (isPastaMeal(meal) && lastPastaSelections.find(meal) != lastPastaSelections.end()) {
        return; // Exit if this pasta meal was already chosen
    }

    // Ensure mutual exclusion among pasta meals
    for (const auto& pasta : {"Spaghetti", "Tortellini", "Pesto"}) {
        if (pasta != meal && lastPastaSelections.find(pasta) != lastPastaSelections.end()) {
            return; // Exit if another pasta meal was already chosen
        }
    }

    printAndAddMeal(meal);
    mealCount += (isPastaMeal(meal)) ? 2 : 1; // Pasta meals count as 2 meals

    if (isPastaMeal(meal)) {
        pastaAllowed = false; // Set pastaAllowed to false after selecting one pasta meal
        lastPastaSelections[meal] = mealCount;
    }
}

void MealSelector::handleRegularMeal(const std::string& meal) {
    if (!isPastaMeal(meal) && mealCount == 3) {
        pastaAllowed = false;
    }
    printAndAddMeal(meal);
    mealCount++;
}

mealSelector.h

#pragma once

#include <iostream>
#include <vector>
#include <random>
#include <unordered_set>
#include <unordered_map>

class MealSelector {
private:
    std::vector<std::string> meals;
    std::unordered_set<std::string> chosenMeals;
    std::unordered_map<std::string, int> lastPastaSelections; // Track last selection for each pasta meal
    int mealCount;
    bool pastaAllowed;

public:
    MealSelector(const std::vector<std::string>& initialMeals);

    void shuffleMeals();
    void selectMeals();

private:
    void printAndAddMeal(const std::string& meal);
    bool isPastaMeal(const std::string& meal);
    bool canSelectPastaMeal(const std::string& meal);

    void handleSelectedPastaMeal(const std::string& meal);
    void handleRegularMeal(const std::string& meal);
};

When I run my code, sometimes it outputs something like this: Tortellini Spaghetti Grilled Cheese

This: Potato Skins Lunch meat sandwiches Mac & Cheese Tortellini

Or This: Spaghetti Tortellini Pesto

I cannot for the life of me figure out what is wrong. It may be a brain fart but please help.




mardi 28 novembre 2023

Facing a problem in a coding and decoding words in secret language kinda project [closed]

The problem here is in decoding. When I encode the word "hello" it gives me this output "ollehhello". What's wrong? I know it will not work for sentences. I tried to decode everything i encode but I think I'm making a mistake somewhere. I included random symbols numbers and letters in starting and at end of the word and inserted a symbol after each char of the word.

import random
import string

def get_random_symbols(length):
    return ''.join(random.choice(["<", ">", "?", "/", ";", ".", "*", "^", "&", "(", ")", "_", "!", "@", "#", "4", "%", "^", "&"]) for _ in range(length))

def get_random_numbers(length):
    return ''.join(random.choice(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]) for _ in range(length))

def get_random_letters(length):
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))

def reverse(x):
    return x[::-1]

def transform_word(word):
    transformed_word = ''
    for letter in word:
        transformed_word += letter + get_random_symbols(1)
    return transformed_word


def transformation(text):
    output = []
    for word in text.split():
        if len(word) <= 3:
            word = (
                get_random_numbers(1) +
                reverse(word) +
                get_random_symbols(1) +
                get_random_letters(1)
            )
            output.append(word)
        else:
            transformed_word = (
                # get_random_numbers(2) +
                get_random_letters(2) +
                get_random_symbols(1) +
                reverse(transform_word(word)) +
                get_random_symbols(1) +
                get_random_letters(1)
            )
            output.append(transformed_word)
    return ' '.join(output)

def decoded_transformation(encoded_code):

    def remove_unnecessary_elements(word):
      word_after_removal = word[3:-2]
      return word_after_removal

  
    def remove_symbols(word):
        return word.replace('<', '').replace('>', '').replace('?', '').replace('/', '').replace(';', '').replace('.', '').replace('*', '').replace('^', '').replace('&', '').replace('(', '').replace(')', '').replace('_', '')


    def remove_numbers(word):
        return word.replace('1', '').replace('2', '').replace('3', '').replace('4', '').replace('5', '').replace('6', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '')
      

    decoded_output = []
    for word in encoded_code.split():
        if len(word) <= 5:
            decoded_word = reverse(remove_symbols(remove_numbers(word)))
        else:
            decoded_word = remove_unnecessary_elements(word)
            decoded_word = remove_symbols(remove_numbers(decoded_word))
            decoded_word += reverse(decoded_word)
        decoded_output.append(decoded_word)
    return ' '.join(decoded_output)

def code(user_input):
    return transformation(user_input)

def decode(user_input):
    return decoded_transformation(user_input)

command = input("What do you want to do, code or decode? Type 'code' or 'decode' : ")

if command.lower() == "code":
    user_input = input("Enter the message to be coded: ")
    print("The coded message is :\n", code(user_input))
elif command.lower() == "decode":
    user_input = input("Enter the message to be decoded: ")
    print("The original message was :\n", decode(user_input))
else:
    print("Wrong command given")

input("Press enter to exit")

I tried to research it on chatgpt and google but I am unable to find a way to get "hello".




dimanche 26 novembre 2023

Using python to create a random password generator

import string

def generate_password(length):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

# Set the desired length for the password
password_length = 12  # Change this to your desired password length

# Generate and print a random password
generated_password = generate_password("password_length")
print("Generated Password:", generated_password)

I am new to python, this is a code for a random possword generator and it is not working. Pls help




Random Data Generator using List of Items in Columns

I need to take a series of populated columns and generate many rows of combinations with random values.

I've managed to write some VBA that is neither efficient nor stylish - however, on the whole, it works.

All except for one issue, which I'll come on to in a minute.

The code reads down each of the 10 columns outputting to a code combination, adding a random value in the 11th column. The following image shows the example of the input source of 10 lists of items:

Input sheet

The current Output shows the merger of the lists, with a random value: Output sheet

The issue that I have is, if just one of the input columns has just 1 item, UBound() fails with a type mismatch. This will fail: Remove FY25

Please use the code below to run and test after setting up the following fields in a tab called ListDims.

I'm sure that the whole code can be simplified by using arrays, so feel free to offer a simpler, quicker solution.

Sub RandomCombo()
    Dim wsOutSheet As Worksheet
       
    'Change this to point to the start column of the first dimension output
    lnStartcol = 13
    lnNoOfDims = 10
    
    ListA = Application.WorksheetFunction.Transpose(Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value) 'data starts in 2nd row
    ListB = Application.WorksheetFunction.Transpose(Range("B2:B" & Cells(Rows.Count, "B").End(xlUp).Row).Value) 'data starts in 2nd row
    ListC = Application.WorksheetFunction.Transpose(Range("C2:C" & Cells(Rows.Count, "C").End(xlUp).Row).Value) 'data starts in 2nd row
    ListD = Application.WorksheetFunction.Transpose(Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row).Value) 'data starts in 2nd row
    ListE = Application.WorksheetFunction.Transpose(Range("E2:E" & Cells(Rows.Count, "E").End(xlUp).Row).Value) 'data starts in 2nd row
    ListF = Application.WorksheetFunction.Transpose(Range("F2:F" & Cells(Rows.Count, "F").End(xlUp).Row).Value) 'data starts in 2nd row
    ListG = Application.WorksheetFunction.Transpose(Range("G2:G" & Cells(Rows.Count, "G").End(xlUp).Row).Value) 'data starts in 2nd row
    ListH = Application.WorksheetFunction.Transpose(Range("H2:H" & Cells(Rows.Count, "H").End(xlUp).Row).Value) 'data starts in 2nd row
    ListI = Application.WorksheetFunction.Transpose(Range("I2:I" & Cells(Rows.Count, "I").End(xlUp).Row).Value) 'data starts in 2nd row
    ListJ = Application.WorksheetFunction.Transpose(Range("J2:J" & Cells(Rows.Count, "J").End(xlUp).Row).Value) 'data starts in 2nd row

    Application.DisplayAlerts = False
    lnCounter = 2
    If (Sheet_Exists("Data") = True) Then
        Sheets("Data").Delete
    End If
    If (Sheet_Exists("Data") = False) Then
        Sheets.Add(After:=Sheets("ListDims")).Name = "Data"

    End If
    
    Set wsOutSheet = ThisWorkbook.Worksheets("Data")
    
    Sheets("ListDims").Select

   
    Range(Cells(1, lnStartcol), Cells(100000, lnStartcol + 10)).Select
    Range(Cells(1, lnStartcol), Cells(100000, lnStartcol + 10)).Clear
    
    Cells(1, lnStartcol) = Cells(1, 1)
    For i = 1 To lnNoOfDims
        Cells(1, lnStartcol + i) = Cells(1, 1 + i)
    Next i
    
    
    For a = 1 To UBound(ListA)
        For b = 1 To UBound(ListB)
            For c = 1 To UBound(ListC)
                For d = 1 To UBound(ListD)
                    For e = 1 To UBound(ListE)
                        For f = 1 To UBound(ListF)
                             For g = 1 To UBound(ListG)
                                For h = 1 To UBound(ListH)
                                    For i = 1 To UBound(ListI)
                                        For j = 1 To UBound(ListJ)
                                            Cells(lnCounter, lnStartcol) = ListA(a)
                                            Cells(lnCounter, lnStartcol + 1) = ListB(b)
                                            Cells(lnCounter, lnStartcol + 2) = ListC(c)
                                            Cells(lnCounter, lnStartcol + 3) = ListD(d)
                                            Cells(lnCounter, lnStartcol + 4) = ListE(e)
                                            Cells(lnCounter, lnStartcol + 5) = ListF(f)
                                            Cells(lnCounter, lnStartcol + 6) = ListG(g)
                                            Cells(lnCounter, lnStartcol + 7) = ListH(h)
                                            Cells(lnCounter, lnStartcol + 8) = ListI(i)
                                            Cells(lnCounter, lnStartcol + 9) = ListJ(j)
                                            
                                            'Generate a random value
                                            Cells(lnCounter, lnStartcol + 10) = WorksheetFunction.RandBetween(100, 9999)
                                            lnCounter = lnCounter + 1
                                        Next j
                                    Next i
                                Next h
                            Next g
                        Next f
                    Next e
                Next d
            Next c
        Next b
    Next a
    
    Application.CutCopyMode = False
    Selection.Copy
    
    Sheets("Data").Select
    Range("A1").Select
    ActiveSheet.Paste
    Sheets("ListDims").Select
    Selection.Clear
    Range("A1").Select
    Sheets("Data").Select
    Range("A1").Select
    Application.DisplayAlerts = True
    
End Sub
Function Sheet_Exists(WorkSheet_Name As String) As Boolean
Dim Work_sheet As Worksheet

Sheet_Exists = False

For Each Work_sheet In ThisWorkbook.Worksheets

    If Work_sheet.Name = WorkSheet_Name Then
        Sheet_Exists = True
    End If

Next

End Function





generate random values from pd.dataframe with one condition

i have a given dataframe which looks like this:

data = {
  "Name": ["Mike", "Tom", "Marta", "Ole", "Jose", "Omar"],
  "Desk1": [1, 0, 1, 1, 1, 0],
  "Desk2": [0, 0, 1, 1, 0, 1],
  "Desk3": [1, 1, 1, 1, 1, 1],
  "Desk4": [1, 1, 1, 1, 1, 1],
  "Desk5": [0, 1, 0, 1, 0, 1],
  "Desk6": [1, 1, 1, 1, 1, 1],
}

1 is desk[x] is possible, 0 is desk[x] not possible.

I want to loop through the df 4x and generate a randomly picked list for each name looks like this: Mike = ["Desk2", "Desk4", "Desk6", "Desk3"] Tom = ["Desk5", "Desk3", "Desk4", "Desk6"] and so on...

Conditions:

  1. The desk only can be given in the first loop one time
  2. The desk should not be picked in the following loop.

Theoretically there are existing multiple possibities, which can be calculatet with different runs of the script.

I already created lists for Desk_total: Desk_total = ["Desk1", "Desk2", "Desk3", "Desk4", "Desk5", "Desk6"]

List for the names... TomDesk = ["Desk3", "Desk4", "Desk5", "Desk6"]

create empyt list like: Tom_rot = [] for each name

for r in range(1, 4):
   Desk_temp = Desk_total.copy()

   for m in range(len(df)):
       var = random.choice(TomDesk]) #here it sould be the pandas row number

       if (val is in Desk_temp) == True and (val is not Tom_rot[-1]) == True:
          Desk_temp.remove(val)
          Tom_rot.append[val]

and continue looping...

it stops at the second loop second latest and does not contiue. No matter the last Desk would match from Desk_temp to the "Omar_rot"-List

Is it possible to do that within the df or only with the loops as i tried?

Actually i think is a mathematical problem to solve.




My php code should move through the picture but it doesn't... what am I doing wrong?

I have a big crisis with a php code, which I am concerned, that the code should be right, but when I run it on an php reader, the animation isn't working... maybe someone knows, what I did wrong.

What I am trying to archive: A php code for a 10 px circle which is moving through a black background. It should move for 72 seconds and every 6th second it should arrange at a certain point (specified at the position text).. In between these certain positions, the circle should move for 6 seconds randomly through the picture.

That's the php code I'm trying to make work, but unfortunately it isn't :/

<?php
// set header to get svg
header('Content-Type: image/svg+xml');

// start svg document
echo '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';
echo '<svg width="600" height="600" xmlns="http://www.w3.org/2000/svg">';

echo '<rect width="100%" height="100%" stroke="black" />';

// gt circle
echo '<circle cx="0" cy="20" r="5" fill="white">';

// get animation path
echo '<animateMotion dur="72s" repeatCount="indefinite" keyPoints="0;0.0833;0.1667;0.25;0.3333;0.4167;0.5;0.5833;0.6667;0.75;0.8333;0.9167;1" keyTimes="0;0.0833;0.1667;0.25;0.3333;0.4167;0.5;0.5833;0.6667;0.75;0.8333;0.9167;1">';
echo '<mpath href="#motionPath"/>';
echo '</animateMotion>';

echo '</circle>';

// get path for movement
echo '<path id="motionPath" fill="none" stroke="none" d="M0 20 ';

// get positions with random movements
$positions = array(
    array(300, 30),
    array(412.6, 235),
    array(200, 300),
    array(412.6, 365),
    array(300, 170),
    array(300, 500),
    array(300, 240),
    array(157.1, 382.5),
    array(300, 65),
    array(217.7, 252.5),
    array(300, 65),
    array(300, 205)
);

// random amount of movements (4-7)
for ($i = 0; $i < count($positions) - 1; $i++) {
    list($x1, $y1) = $positions[$i];
    list($x2, $y2) = $positions[$i + 1];

    $numMovements = rand(4, 7);

    for ($j = 0; $j < $numMovements; $j++) {
        $dx = ($x2 - $x1) / $numMovements;
        $dy = ($y2 - $y1) / $numMovements;
        $x1 += $dx;
        $y1 += $dy;

        echo "$x1 $y1 ";
    }
}

echo '" />';

// close svg-document
echo '</svg>';
?>



samedi 25 novembre 2023

Show image using a random number in code behind

I tried this and it is not working for me. I have 14 images (7 of each appearing side by side-acctimg1.jpeg, acctimg2.jpeg, etc.) The images reside in the images folder under templates. This is the Home.master.vb page in the templates folder. If I hard code the path on the aspx page as templates/images/acctimg1.jpeg the images appear. I have put a breakpoint and looked at the urls created and they appear correct. Does this use of random number to create a url need to be in a pre render sub instead of page load?

 <table align="center">
                        <tr>
                            <td align="left">
                                <asp:Image ID="acctimage" runat="server" Width="275" Height="220"  /></td>
                            <td align="right">
                                <asp:Image ID="taximage" runat="server" Width="275" Height="220" /></td>
                        </tr>
                    </table>



 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim a As Int16
    a = Int((7 * Rnd()) + 1)
    acctimage.ImageUrl = "templates/images/acctimg" + Convert.ToString(a) + ".jpeg"
    Dim b As Int16
    b = Int((7 * Rnd()) + 1)
    taximage.ImageUrl = "templates/images/tax" + Convert.ToString(b) + ".jpeg"
End Sub



Xoshiro 256++ vs 256** statistical properties

I'm looking for the difference in statistical properties for a monte Carlo simulation between these two prngs, but can't find anything.

Regarding the speed, on my computer it seems Xoshiro256** runs faster, but on the Internet I've seen addition is more optimized than multiplication for big numbers, so I have some doubts.

I hope you can link me something or just write the some details here.




vendredi 24 novembre 2023

How would I get a random array, if I am using multiple arrays from an object?

Ok, so I am new to Javascript. I have created an object with 3 separated arrays.

const messages = {
  message:[
   ["joke1","joke2","joke3"],
   ["tease1","tease2","tease3"],
   ["boost1","boost2","boost3"]
};

now I need to take a random message every time the user logs in. so for example:

 messages.message[0][2] or messages.message[2][0]

i cant get the second part of this code to work.

The first part was easy.

i was able to get the first random number from the array. that is put into the variable chooseArray1

here is where I am struggling.

const secondIndex = messages.message[chooseArray1[Math.floor(Math.random() * messages.message[chooseArray1])];

now Im getting an error here at the second [ in front of Math I cant seem to figure out how to get the random number of an array with an index.

I hope this makes sense. Apparently I have the coding skill of a rock.




How to stop .blit() from wrapping pixels across screen, or help finding an alternative that does the same?

I am trying to generate terrain randomly, and I have made it scroll it just as a test, but when the pixels hit the end of the screen, they play back on the other side as such:brokenscroll before hitting the other side it looks like:scrolling Here's my code:

import pygame as py
import random as r
import time as t
import math as m
py.init()
left = 0
Ylev = 8
display = py.display.set_mode((512, 512))
display.fill((175, 215, 225))
def scrollX(screenSurf, offsetX):
    width, height = screenSurf.get_size()
    copySurf = screenSurf.copy()
    screenSurf.blit(copySurf, (offsetX, 0))
    if offsetX < 0:
        screenSurf.blit(copySurf, (width + offsetX, 0), (0, 0, -offsetX, height))
    else:
        screenSurf.blit(copySurf, (0, 0), (width - offsetX, 0, offsetX, height))
while True:
    num = round(r.randint(0, 5) ** 1/4)
    neg = r.randint(0, 1)
    if neg == 0:
        num = -num
    Ylev += num
    if Ylev < 0:
        Ylev = 0
    if Ylev > 16:
        Ylev = 15
    print(Ylev)
    scrollX(display, -16)
    py.draw.rect(display, (0, 100, 20), py.Rect(31 * 16, Ylev * 16, 16, 16))
    py.display.flip()
    t.sleep(0.25)````
I am trying to achieve image 2, but with the ability to hit the other side of the screen and still generate new terrain. How can this be achieved, and if possible, how can I allow a player (represented by 2 pixels) to interact with this terrain, in the form of movement, but disallowing movement through the generated terrain. Can this be achieved by detecting the colour of a pixel (e.g. the terrain) and letting the player interact with it that way, or do I need a list of all the terrain pixels?
I tried to update everything but the first row, but
    1. This leads to the first pixel never being displayed, and
    2. This doesn't fix the problem.



jeudi 23 novembre 2023

Get a Random Boolean by Percentage using tkinter

Please could you explain how to use tkinter to make an Entry widget that passes a percentage value to the function below e.g. the user enters 60 into the input field which then passes the user’s value to the percent = 55 argument so it updates in real time to whatever value the user types in?


    def reset(percent=55):
        prob = random.randrange(0,100)
        if prob > percent:
            return True
        else:
            return False
    
    print(reset(15))  

  

N.B Matplotlib, random and NumPy are being imported.

Tried using the input(), int() and str() functions but the IDLE still produces errors. Editing the 'percent=' argument too much causes the program to crash.

The 'percent=' argument only seems to accept the format: percent=number




Correctly seeding numpy random generator

For my scientific experiments, I usually seed using:

rng = np.random.Generator(np.random.PCG64(seed))

which for the current numpy version is equivalent to

rng = np.random.Generator(np.random.default_rng(seed))

As I repeat my experiments n times and average their results, I usually set the seed to all the numbers between 0 and n.

However, reading the documentations here and here it states that

Seeds should be large positive integers.

or

We default to using a 128-bit integer using entropy gathered from the OS. This is a good amount of entropy to initialize all of the generators that we have in numpy. We do not recommend using small seeds below 32 bits for general use.

However, in the second reference, it also states

There will not be anything wrong with the results, per se; even a seed of 0 is perfectly fine thanks to the processing that SeedSequence does.

This feels contradictory and I wonder, if small seeds are now totally fine to use, or one should move towards higher seeds. Especially, I wonder, (i) at which point (if any) would a large seed make a difference to a low seed and (ii) if one does scientific experiments (e.g. machine learning / algorithmic research) should one prefer higher to lower seeds or should it not make a difference?

PS: This question is highly related to Random number seed in numpy but concerns the now recommended Generator. Furthermore, the answer seems not in-depth enough as it does not include a discussion about high and low seeds.




How can I change multiple images each day to different ones from the same folder using JavaScript?

Im gunna try this again in more detail so I have a website with multiple images on the home page which I change manually each week from my images folder which has over 500 images, is there a way I can do this using javascript so each day it changes so a different image, kind of like storing all the image links in a javascript file, does this make sense?

here is the code to display each section take a look at the website page so you can understand more what I mean wealthybones dot com

<h3 class="no-title">Recently Added</h3>
        <div class="no">
            <img src="images/move.png" alt="">
            <a href="files/jamaledwards"><img src="images/deadhome/jamaledwards.png" alt=""></a>
            <a href="files/margaretjohn"><img src="images/deadhome/margaretjohn.png" alt=""></a>
            <a href="files/michaelgambon"><img src="images/deadhome/michaelgambon.png" alt=""></a>
            <a href="files/halroach"><img src="images/deadhome/halroach.png" alt=""></a>
            <a href="files/genekelly"><img src="images/deadhome/genekelly.png" alt=""></a>
            <a href="files/petercushing"><img src="images/deadhome/petercushing.png" alt=""></a>
            <a href="files/jimhenson"><img src="images/deadhome/jimhenson.png" alt=""></a>
            <a href="files/hennyyoungman"><img src="images/deadhome/hennyyoungman.png" alt=""></a>
            <a href="files/donaldpleasence"><img src="images/deadhome/donaldpleasence.png" alt=""></a>
            <a href="files/brookemccarter"><img src="images/deadhome/brookemccarter.png" alt=""></a>
            <a href="#search22"><img src="images/search.png" alt=""></a>
        </div>
    </div>



mercredi 22 novembre 2023

What is the period of Python numpy.random.randint?

I am looking for some more detailed technical details regarding the implementation of Numpy's randint() function.

Specifically details regarding the period or implementation would be great. I didn't find anything in the documentation other than a note saying that new code should use a different module.

I wonder if that is because the quality of the implementation of randint() is quite poor / basic?

This question has come about as I am seeing some slightly strange results in some random data generation process.




How to apply complicated random formula n-th time?

I have a big spreadsheet with a lot of data and formula, in F19 is a random value which is built from all these data and formula. I would like to get a sample of N=30 values that are given by this formula. Of course I could copy paste the number, refresh the sheet, recopy paste etc N times, but let's be smart here. Is there a way to do so?

I have tried using ARRAYFORMULA() but not sure how to use it to get a sample of N values from the F19 cell.




mardi 21 novembre 2023

TypeError: super_shuffle() missing 1 required positional argument: 'color_list'

This is my code

import random
import copy

def super_shuffle(color_list):
    color_list_2 = copy.copy(color_list)
    random.shuffle(color_list_2)
    for old, new in zip(color_list, color_list_2):
        if old == new:
            return super_shuffle(color_list)
    
    return color_list_2

color1 = input("Pick a color:")
color2 = input("Pick a color:")
color3 = input("Pick a color:")
color4 = input("Pick a color:")
color5 = input("Pick a color:")
color6 = input("Pick a color:")
color_list = [color1, color2, color3, color4, color5, color6]

super_shuffle()

I am trying to get it to take your colors and shuffle them into a list, but then it comes up with this error

TypeError: super_shuffle() missing 1 required positional argument: 'color_list'

I am also trying to get it so I can edit the list after the list is already shuffled

I type in some colors but when they get shuffled, it is supposed to print them, but it doesn't. It just comes up with the error. I was expecting for it to print a list of my colors shuffled, but it just errored.




lundi 20 novembre 2023

rotation lists based on columns out of pandas dataframe with restrictions

I want to create a random tool for a station rotation for the names: I have a given Dataframe with the following shape:

data = {'Name': ['Tom', 'Mike', 'Carl', 'Juli', 'Tina', 'Wendy'],
        'station1': [0, 1, 1, 1, 0, 0],
        'station2': [1, 1, 1, 1, 1, 0], 
        'station3': [1, 1, 1, 1, 1, 1],
        'station4': [1, 1, 1, 1, 1, 1],
        'station5': [0, 1, 0, 0, 1, 0],
        'station6': [1, 1, 0, 1, 1, 0]}

4x rotation = 4 postions in list

Restrictions for rotations: no double station at for e.g. 1st position in each list no station following each other, and if possible Wendy can only do 2 stations, so a double change is minimum. (see at expeced result below)

I think working with list is the best way, but not sure if 4-D array is also a choice.

my prgress so far:

  1. replace 1 with 'station_'
  2. swapaxes()
  3. creat lists for each name
  4. delete 'nan's in name lists
  5. set name as list name and delete name from list (so lists have different len)
  6. ... no idea, maybe sort by length?
  7. ... maybe pic and check by column/rows?

List should be like

Wendy = ['station4','station3','station4','station3']
Mike = ['station1','station2','station5','station6']

...

Tom = ['station2','station4','station6','station2']

I know is tricky and difficult, but i have no clue how to coninue




Trying to create an application that will go to a webpage, fillout 4 boxes, submit a captcha, then close the page and restart

I am trying to automate a signup page on google chrome. The chrome URL requires information to be filled in (Name, address, email address, DOB, and few drop down menus as well. At the end of the form there is a captcha that must be submitted prior to submitting the page.

I am very new to this and have spent around 10 hours researching ideas but have made very little progress.




dimanche 19 novembre 2023

Convert sha384 to string [closed]

how to generate this type of string JhgVfmRmNL4Sg5fOB0UzfLMIcT9bLa

from a input like this sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi

well i thought that this string was generate by this sha but since the sha doesn't have an uppercase V this made me extremely curious to know how to generate string like this can be in any language




If I use random seed, will this guarantee that there will be a lot of repetition of gerated numbers?

I have a question about how Python's native random library generates pseudo-random numbers. Specifically about the repetitions of the generated numbers.

When using the random seed function from the random library, the pseudo random numbers generated on a scale from 0 to 1, if I call the function several times, will they repeat with a certain frequency?

If yes, would it be very frequent, to the point of becoming a memorable sequence? Or allow us to state that a given value between 0 and 1 would always appear several times in a range of executions?

If I use random seed, will this guarantee that there will be a lot of repetition of numbers?




How to pick a random number from a set of numbers in simulink?

I want to pick a number from a set of number, i.e [1011, 1001, 1111, 1101, 0011] once at the beginning of each simulation. But i am not getting any help from the random number generator blocks. MATLAB code works in this case, so I've used matlab fuction block to run the code in simulation. But the code keeps running and generating value. Is there any fix to this?

The code I'm using in the fuction block is:

numbers = [1011, 1001, 1111, 1101, 0011, 0101, 1100]; % Generate a random index index = randi(length(numbers)); % Display the random number data=(numbers(index));

tried many things. but either it is generating frequent random values or showing same value in every simulation from the set of numbers.




samedi 18 novembre 2023

MT19937 Generator in C++ and NumPy generate different numbers

I am trying to reproduce some C++ code in Python that involves random number generations. The C++ code uses the MT19937 generator as follows:

#include <random>
#include <iostream>

int main() {
    std::mt19937 generator(1234);
    std::uniform_real_distribution<double> distribution(0.0, 1.0);

    for (int i = 0; i < 10; ++i) {
        std::cout << distribution(generator) << std::endl;
    }

    return 0;
}

The Python version is (with NumPy 1.23.3)

import numpy as np

rng = np.random.Generator(np.random.MT19937(1234))
for _ in range(10):
    print(rng.random())

In both cases, the random seed is set to 1234. But the two produce different outputs on my machine (macOS 14.0 ARM). The C++ code outputs

0.497664
0.817838
0.612112
0.77136
0.86067
0.150637
0.198519
0.815163
0.158815
0.116138

while the Python code outputs

0.12038356302504949
0.4037014194964441
0.8777026256367374
0.9565788014497463
0.42646002242298486
0.28304326113156464
0.9009410688498408
0.830833142531224
0.6752899264264728
0.3977176012599666

Why do the two MT19937 generators produce different sequences despite the same seed? How (if possible) can I make them the same?




Are function calls that are used to initialize `thread_local` variables guaranteed to be thread-safe?

Consider the following implementation of rand_double(), in which there is a thread_local function variable seed that is initialized using std::random_device{}() in each thread:

auto rand_double(double min, double max) {
    thread_local uint64_t seed = std::random_device{}();
    // ^^ Are the calls to std::random_device guaranteed to not interleave?

    /* Generate random `double` and return it... */
}

I have learned that the initialization of static function variables is guaranteed to be thread-safe. However, I haven't found a source that states if, when using a function to initialize the static function variable, calls to that function will not interleave. Can someone confirm if using a function to initialize static (specifically thread_local - does it make a difference?) function variables is thread-safe?




Runtime of randomization algorithm to find majority element in an array?

This is for the leetcode problem 169. Majority Element. Given an array of numbers, where there is a guarantee that there is a number that exists in the array greater than floor(n/2), one can find such a number by selecting a random index and checking if it's value is the majority element or not, and repeat until it's found. This is one of the solutions provided.

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        majority_count = len(nums)//2

        while True:
            candidate = random.choice(nums)
            if sum(1 for elem in nums if elem == candidate) > majority_count:
                return candidate

What I'm confused about is the runtime analysis of this algorithm, which is based on the assertion that since the majority element is always guaranteed to occupy more than half of the array, this algorithm applied to our scenario will always be faster than if it were applied to the scenario where there existed only an element that occupied exactly half the array. Therefore the expected number of iterations EV_(itersprob) can be represented as being less than or equal to the expected number of iterations of the modified scenario EV_(itersmod)

enter image description here

What I'm confused about is how this series was put together for this problem. The variable i is the iteration number, but why are you summing for (i * (1/2^i))?

Basically the runtime for the number of iterations of the while loop is expected to be constant, making the runtime of this entire algorithm linear (due to the inner loop running n times each time)




UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor, call it in Awake or Start instead

In my Unity project, I'm trying to make a feature which every 5 seconds, a random number will be generated, and if the number equals 6, an enemy will be spawned. I tried to generate the number with UnityEngine.Random.Range(1,7) but I kept getting the following error:

UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'spawnEnemy' on game object 'enemySpawn'. This is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spawnEnemy : MonoBehaviour
{
    public GameObject enemyPrefab;
    public float spawnEnemySpeed = 5.0f;
    private float spawnTimer = 0.0f;
    int rng = 0;

    void Start()
    {
        rng = UnityEngine.Random.Range(1,7);
        Debug.Log(rng);
    }

    void Update()
    {
        spawnTimer += Time.deltaTime;
        if (spawnTimer >= spawnEnemySpeed && rng == 6)
        {
            Instantiate(enemyPrefab, transform.position, transform.rotation);
            spawnTimer = 0.0f;
            rng = UnityEngine.Random.Range(1,7);
            Debug.Log(rng);
        }
    }
}

I cannot find solution to this problem, most of the sources I found said that write the code in Start() and Awake(), but did not work for me even if I commented the code in the Update.

One of the source I found :




jeudi 16 novembre 2023

Random number generation is giving a number in a smaller range [duplicate]

I have a console program for a gacha system, which is responsible for randomly generating "skins" between 5 "qualities" with their own rarity, among one of these is the common quality which has 3 items, I programmed it to randomly generate numbers again but instead of using 0 to 101, I used 0 to 4, because there are only 3 items, when I finished the program and checked that everything was fine, I realized that the times it came out common, only the first of the 3 was shown articles, when testing with debugging, I realized that the variable in charge of indicating which option of the 3 would be shown, always had a value of 0

This is a part of my code, specifically the one that is failing, even i tried by raising the values in the Random().Next(0,4) to Random().Next(0,34) and the values were the same but instead, the values were only between 0 and 11:

int commonSkinIndex = new Random().Next(0, 34);
if (commonSkinIndex <= 11)
{
    Console.Write(" Value: " + commonSkinIndex + " Skin: 8-Bit\n");
} 
else if (commonSkinIndex > 11 && commonSkinIndex < 22)
{
    Console.Write(" Value: " + commonSkinIndex + " Skin: Gothic\n");
}
else 
{
    Console.Write(" Value: " + commonSkinIndex + " Skin: Holy\n");
}

Even I was trying changing thecommonSkinIndex <= 11 to commonSkinIndex < 11 and for the else if (commonSkinIndex >= 11 && commonSkinIndex < 22) the difference between the previus line was that random could now include the number 11, also, I don't believe that this may change the results, but above all that part, there's this:

else if (output / 100 <= commonChance && output / 100 > uncommonChance)
{
(...)
}

Also, I made sure each loop is random, so this repeats every 500ms (this loops 10 times)




How to measure time elapsed by code when we don't have access to any library in C/C++ except malloc.h? [closed]

There is internal heuristics coding contest with weird rules of not allowing any libraries except malloc.h. I wish to measure the time elapsed since start of function execution. For heuristics there are I wish to execute a certain "strategy" just till Time Limit - 0.5 seconds. Is there any way to do that? Also, I wish to generate random number between 0 and 1, since quite lot of them depends on time in C and C++, is there any good way to generate without library usage?

I know a malloc generally returns address randomly so that could be used to generate big random number.




mercredi 15 novembre 2023

Why does random.choice() return the same value almost every time? [closed]

The random.choice() method of the random module in Python returns a value randomly from a list of values passed to it. So, I would expect it to return some random value every time. However, it appears that the same value is returned multiple times. For example, the following code:

import random

print(random.choice(["apple","orange","banana"]))

when executed 5 times, returns 'orange' 3 times, 'apple' 1 time and 'banana' 1 time. Why is this so? It would be helpful if anyone could provide some insight into how random.choice() works.




Why isn't the vector print anything out? [closed]

The expected output is for the 20,000 random ints to be stored into the vector and then my the Bublesort() method in MySort will sort an print out the vector.

There are no problems with the MySort and MyVector classes just this one. I a figure out what is wrong

package lab;

import collection.MyVector;
import java.util.*;
import collection.MySort;

public class Lab5 {
    public static void test() {
        Random rand = new Random();
        rand.setSeed(20130306);
        
        MyVector testing = new MyVector();
        for(int i=0;i<20000;i++) {
            int num = rand.nextInt(100000);
            testing.append(num);
            //System.out.println(testing.elementAt(i));
        }
        long start = System.currentTimeMillis();
        MySort.bubbleSort(testing);
        System.out.println("Bubble Sort: "+testing);
        long finish = System.currentTimeMillis();
        long timeElapsed = finish - start;
        //System.out.println("The time difference is: "+timeElapsed+ " Milliseconds");
    }
}

For the vector to print out 20,000 random sorted integers




UUID uniqueness

I really just want verification as I think this is true. When I create a UUID I ge "3dc576a5-5bcc-44e4-b1c7-cbed7d3dcd4c". What I am using it for cannot contain dashes, so I remove them, "3dc576a55bcc44e4b1c7cbed7d3dcd4c". This should be unique still, right? That is, it won't create something like "3dc576a-55bcc4-4e4b1c7-cbed7d3dcd4c" or "3dc57-6a-55bcc44-e4b1c7-cbed7d3dcd4c" etc, correct? I suppose even if it did it would be extremely rare.




Why is Java Math.random() not a "real" random? How does it work?

I am trying to understand the Math.random() method from java. I've heard this term "pseudorandom" being thrown around and that an algorithm is used to generate it. However, I don't quite understand how this algorithm works.

Does this mean that it is possible to predict every Math.random() value?




Generate double including 1 in Flutter (Dart)

I've been asked a question how to add 1 in range for random.nextDouble(). The solution I came up with was generating int and applying it to decimals.

  double getRandomDouble(){
    final random = Random();

    int a = random.nextInt(10001); // generates int from 0 to 10000
    String stringValue;
    if (a == 10000) {
      stringValue = '1.0';
    } else {
      stringValue = '0.$a';
    }
    return double.parse(stringValue);
  }



Populate dataset with random amounts within nominated constraints

I am trying to create a fantasy cricket team of 11 players from a large list of players.

For the team, I have basic minimum and maximum requirements for each type of player. I have assigned values like this:

$min_wicket_keeper = 1;
$min_batsman = 3;
$min_all_rounders = 1;
$min_bowlers = 2;

$max_wicket_keeper = 3;
$max_batsman = 5;
$max_all_rounders = 5;
$max_bowlers = 4;

I have total players like this:

$total_wicket_keepers = 2;
$total_batsman = 6;
$total_all_rounders = 5;
$total_bowlers = 5;

You can see I have total 18 players. Now I want to create a team of 11 players assigning random type players -- keep in mind the minimum and maximum requirements of players.

Example 1

$wicket_keeper_limit = 1;
$batsman_limit = 4;
$all_rounder_limit = 4;
$bowler_limit = 2;
//so total 11

Example 2

$wicket_keeper_limit = 2;
$batsman_limit = 3;
$all_rounder_limit = 3;
$bowler_limit = 3;
//so total 11

I want a random number assigned for each type but total should be 11 and should not below minimum requirements and should not greater then total available players for each type followed by maximum limit.

I have tried code like this

$min_wicket_keeper = 1;
$min_batsman = 3;
$min_all_rounders = 1;
$min_bowlers = 2;

$max_wicket_keeper = 3;
$max_batsman = 5;
$max_all_rounders = 5;
$max_bowlers = 4;

$total_wicket_keepers = 2;
$total_batsman = 6;
$total_all_rounders = 5;
$total_bowlers = 5;


$total_players_match = $total_wicket_keepers+$total_batsman+$total_all_rounders+$total_bowlers;

echo $total_players_match;

if ($total_players_match > 11) {
    $remain_players = 11;
    if ($total_wicket_keepers > $min_wicket_keeper) {
        $wicket_keeper_limit = rand($min_wicket_keeper,$total_wicket_keepers);
        $remain_players = $remain_players-$wicket_keeper_limit;
    } else {
        $wicket_keeper_limit = $total_wicket_keepers;
        $remain_players = $remain_players-$wicket_keeper_limit;
    }
        
    echo "WK: ".$wicket_keeper_limit." REMAIN: ".$remain_players."<br>";
        
    if ($total_batsman>$min_batsman) {
        $batsman_limit = rand($min_batsman,$total_batsman);
        $remain_players = $remain_players-$batsman_limit;
            
        if ($remain_players > ($total_bowlers + $total_all_rounders)) {
            $batsman_limit = ($min_batsman + $remain_players) - ($total_bowlers+$total_all_rounders);
            $remain_players = $remain_players-$batsman_limit;
        }
            
    } else {
        $batsman_limit = $total_batsman;
        $remain_players = $remain_players-$batsman_limit;
    }
        
    echo "BT: " . $batsman_limit . " REMAIN: " . $remain_players . "<br>";
        
    if ($total_bowlers > $min_bowlers) {
        $bowler_limit = rand($min_bowlers, $total_bowlers);
        $remain_players = $remain_players - $bowler_limit;
            
        if ($remain_players > $total_all_rounders) {
            $bowler_limit = $total_bowlers;
            $remain_players = $remain_players - $bowler_limit;
        }

    } else {
            $bowler_limit = $total_bowlers;
        $remain_players = $remain_players - $bowler_limit;
    }
        
    echo "BOL:" . $bowler_limit . " REMAIN:" . $remain_players . "<br>";
        
    $all_rounder_limit = $remain_players;
        
    echo "ALL: " . $all_rounder_limit . " REMAIN: " . $remain_players . "<br>";
        
} else {
    $wicket_keeper_limit = $total_wicket_keepers;
    $batsman_limit = $total_batsman;
    $all_rounder_limit = $total_all_rounders;
    $bowler_limit = $total_bowlers;
}
    
echo "WK:" . $wicket_keeper_limit . "<br>";
    echo "BT:" . $batsman_limit . "<br>";
    echo "BO:" . $bowler_limit . "<br>";
    echo "AL:" . $all_rounder_limit . "<br>";

but it's failing to follow my minimum and maximum requirements. Sometimes I am getting bowler as 0 and sometimes I am getting all rounder as high as 6.

This is Online Fiddle Link

Edit: According to comments, I should clear that, I will generate multiple teams with put above code in while loops, Like 50 teams which will have different/random players in each type like some team have 5 batsman, some team will have only 3 batsman.

When I will get above code working, I will later get players from my database according to limit, I have got for each type.




mardi 14 novembre 2023

jquery random image arrays inside divs

I have this website where when you refresh it will bring up a random image from multiple JS array inside multiple divs (each div has its own JS array with different images). The problem is that my code is only using the last declared JS array and uses the same 2 pictures for all the divs.

$('.random-image-container').each(function() {
  var container = $(this)
  $('<img class="random-image" src="' + images[Math.floor(Math.random() * images.length)] + '">').appendTo(container);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/1.jpg', 'IMG/2.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/3.jpg', 'IMG/4.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/5.jpg', 'IMG/6.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/7.jpg', 'IMG/8.jpg'];
    </script>
  </div>
</article>

can someone help me with this ?




lundi 13 novembre 2023

Assigning random unique letters to numbers

I am trying to assign random letters to 8 subjects and my desire output is like this:

| ID       | Subject |
| -------- | --------|
|1001      | B       |
|1002      | C       |
|1003      | D       |
|1004      | E       |

I tried this code but I a keep getting duplicates:

rand-let=char('BCDE', rand('integer',4));

And I am note sure why this question is being marked as negative!!!




Replace numpy.array values with randomly selected values from other rows in the array only

I have the following array of shape (A, B) where A=4 and B=2 here: [[1 1] [2 2] [3 3] [4 4]] I want to modify the array so each row consists of randomly selected values from the other rows, with no repetition within the same row. An example result would be: [[3 2] [1 3] [2 4] [3 1]]

I tried to use np.random.shuffle and np.random.choice but I can't figure out how to exclude the row itself and how to replace values per value instead of per row. np.random.shuffle leads to: [[4 4] [2 2] [3 3] [1 1]] and np.random.choice gives me errors because my array is 2D and not 1D
I'm a beginner and I feel like this should be obvious but I've been racking my brain all day... Any help would be very much appreciated




samedi 11 novembre 2023

Implement nextBoolean using nextInt

Can we safely implement nextBoolean using nextInt in java?

for example as below,

   public static boolean nextBoolean(Random random) {
        return random.nextInt(2) == 0;
    }



How can I reroll repeated random outputs?

I'm trying to make a bingo sheet randomizer for a game, but I can't figure out how to reroll my repeated options.

This is my current code:

import PySimpleGUI as sg
import random, string
items = [str(a), str(b), str(c), str(d), str(e), str(f), str(g), str(h),
         str(i), str(j), str(k), str(l), str(m), str(n), str(o), str(p),
         str(q), str(r), str(s), str(t), str(u), str(v), str(w), str(x),
         str(y), str(z), str(A), str(B), str(C), str(D), str(E), str(F),
         str(G), str(H), str(I), str(J), str(K), str(L), str(M), str(N),
         str(O), str(P), str(Q), str(R), str(S), str(T), str(U), str(V),
         str(W), str(X), str(Y), str(Z)]
# ------ Some functions to help generate data for the table ------


def word():
    return ''.join(random.choice(items) for ip in range(1))
    
def make_table(num_rows, num_cols):
    data = [[ji for ji in range(num_cols)] for ip in range(num_rows)]
    data[0] = [word() for _ in range(num_cols)]
    data[1] = [word() for _ in range(num_rows)]
    data[2] = [word() for _ in range(num_rows)]
    data[3] = [word() for _ in range(num_rows)]
    data[4] = [word() for _ in range(num_rows)]
    return data

def edit_cell(window, key, row, col, justify='left'):

    global textvariable, edit

    def callback(event, row, col, text, key):
        global edit
        widget = event.widget
        if key == 'Return':
            text = widget.get()
            print(text)
        widget.destroy()
        widget.master.destroy()
        values = list(table.item(row, 'values'))
        values[col] = text
        table.item(row, values=values)
        edit = False

    if edit or row <= 0:
        return

    edit = True
    root = window.TKroot
    table = window[key].Widget

    text = table.item(row, "values")[col]
    x, y, width, height = table.bbox(row, col)

    frame = sg.tk.Frame(root)
    frame.place(x=x, y=y, anchor="nw", width=width, height=height)
    textvariable = sg.tk.StringVar()
    textvariable.set(text)
    entry = sg.tk.Entry(frame, textvariable=textvariable, justify=justify)
    entry.pack()
    entry.select_range(0, sg.tk.END)
    entry.icursor(sg.tk.END)
    entry.focus_force()
    entry.bind("<Return>", lambda e, r=row, c=col, t=text, k='Return':callback(e, r, c, t, k))
    entry.bind("<Escape>", lambda e, r=row, c=col, t=text, k='Escape':callback(e, r, c, t, k))

def main_example1():
    global edit

    edit = False
    # ------ Make the Table Data ------
    # sg.Print('Creating table...')
    data = make_table(num_rows=5, num_cols=5)
    # headings = [str(data[0][x])+'     ..' for x in range(len(data[0]))]
    headings = ["B", "I", "N", "C", "O"]
    # sg.Print('Done creating table.  Creating GUI...')
    sg.set_options(dpi_awareness=True)
    layout = [[sg.Table(values=data, headings=headings, max_col_width=25,
                        auto_size_columns=True,
                        # display_row_numbers=True,
                        justification='right',
                        num_rows=5,
                        alternating_row_color=sg.theme_button_color()[1],
                        key='-TABLE-',
                        # selected_row_colors='red on yellow',
                        # enable_events=True,
                        # select_mode=sg.TABLE_SELECT_MODE_BROWSE,
                        expand_x=True,
                        expand_y=True,
                        enable_click_events=True,  # Comment out to not enable header and other clicks
                        )],
              [sg.Text('Cell clicked:'), sg.T(k='-CLICKED-')]]


    window = sg.Window('Table Element - Example 1', layout, resizable=True, finalize=True)

    while True:
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Exit'):
            break
        elif isinstance(event, tuple):
            cell = row, col = event[2]
            window['-CLICKED-'].update(cell)
            edit_cell(window, '-TABLE-', row+1, col, justify='right')

    window.close()

main_example1()

All of the letters with strings have a corresponding string to go with them. It all works, but everything I've tried has either not worked or led to still repeating outputs.




vendredi 10 novembre 2023

Subtracting random number does not match average I should get

Suppose you organize a competition with 25 million participants. At each round, a random number from the people remaining is eliminated. How many rounds should we expect to get 5 participants or less ? Now 25M/2^22 is the closest number higher than 5 so 22 rounds on average. However, when verifying this in Python, I get that the distribution is more accumulated around 15-16 rather than 22-23. (I am not very familiar with Python so I know I should use dictionaries to count stuff etc.) Is there a mistake in my code ? Because theory cannot lie.

import random

lst=list()
for j in range(1,10000):
    i=0
    X=25000000
    while X > 5:
        i = i+1
        elim=(random.randint(0,X))
        X = X - elim
    lst.append(i)
    
for i in range(1,33):
    print( i, "appears", lst.count(i), "times")

print("22 appears", lst.count(22)*100/len(lst), "% of the time")
print("15 appears", lst.count(15)*100/len(lst), "% of the time")



jeudi 9 novembre 2023

Birthday Paradox's probability coming out to be zero,also not understanding how to use simulations

I have been trying to create a program which calculates the probability of 2 people's birthday being the same, considering there are 23 people in the room

I have made logic but the probability always comes out to be zero,it should be above 0.5,this is my first computer science class so i am not too familiar with java and coding.

I saw some programs online with multiple simulations,but i was not able to understand it.

import java.util.Random;

public class Main {
    
    public static int rand_bd() {

        Random rand = new Random();
        int x = rand.nextInt(365);
        return x;

    }
    public static void main(String[] args) {
        System.out.println("Hello world!");
        

        int h = 0;
        double count = 0.0;
        int g = rand_bd();



            for(int i = 0;i  <= 23;i++){


         h = rand_bd();
         if(g == h)
             count++;

        }
        System.out.println(count);
        System.out.println(count/23.0);
        System.out.println(rand_bd());
 
    }
}



Why does my program freeze at seemingly random moments?

I'm trying to make a small game where you move a circle and you have to avoid being hit by the enemy. I'm very new to processing and python so its a big mess but I'm at a loss. Basically, the program freezes at seemingly inconsistent intervals just before the enemy randomises its starting position. Try the program and you'll see what I mean. I couldn't find any consistencies myself for when it happens, but I just know that it is something to do with with the randomisation. I'd really appreciate any help if possible.

import random
play = False
score = 0
highscore = 0
exStartpos = -25
eyStartpos = random.randint(0, 500)
xVel = random.randint(1, 10)
yVel = random.randint(-10, 10)
difficulty = 50
sidetop = 0
leftright = 0
topdown = 0

def setup():
    size(500, 500)

def draw():
    global play, score, highscore, exStartpos, eyStartpos, xVel, yVel, difficulty, reset, sidetop, leftright, topdown
    if keyPressed == True:                                                           #Makes the game begin
        play = True
        score = 0
    background(255)
    if play == False:                                                                #If play == False I show the title screen and scores
        fill(0)
        textSize(100)
        text("Damn,", 100, 100)
        textSize(30)
        text("just missed him!", 130, 150)
        text("Score: " + str(score), 170, 300)
        text("Highscore: " + str(highscore), 150, 330)
        text("Press any key to play", 110, 400)
    
    if play == True:                                                                #If play == True the game begins here
        fill(255)
        circle(mouseX, mouseY, difficulty)
        circle(exStartpos, eyStartpos, 50)
        exStartpos = exStartpos + xVel
        eyStartpos = eyStartpos + yVel
        
        if dist(mouseX, mouseY, exStartpos, eyStartpos) < (difficulty/2)+25:                    #This checks for collision and ends the game if the circles collide
            play = False
            if highscore < score:
                highscore = score
            difficulty = 50
        
        while (exStartpos < -25) or (exStartpos > 525) or (eyStartpos < -25) or (eyStartpos > 525):     #This runs when the enemy is offscreen and the entire section is to randomise which side it reappears from and how fast it  moves
            score = score + 10
            difficulty = difficulty + 1
            sidetop = random.randint(1, 2)                                   #The best I could come up with was to first randomise between the sides or the top and bottom,
            if sidetop == 1:
                leftright = random.randint(1, 2)                             #then depending on what was chosen I randomised between the two remaining options (left and right in this case)
                print("leftright:" + str(leftright))# This print is left over from when I tried to resolve the issue myself
                if leftright == 1:
                    exStartpos = -25
                    xVel = random.randint(1, 10)
                    yVel = random.randint(-10, 10)
                elif leftright == 2:
                    exStartpos = 525
                    xVel = random.randint(-1, -10)
                    yVel = random.randint(-10, 10)
                eyStartpos = random.randint(0, 500)
            elif sidetop == 2:
                topdown = random.randint(1, 2)
                if topdown == 1:
                    eyStartpos = -25
                    xVel = random.randint(-10, 10)
                    yVel = random.randint(1, 10)
                elif topdown == 2:
                    eyStartpos = 525
                    xVel = random.randint(-10, 10)
                    yVel = random.randint(-10, -1)
                exStartpos = random.randint(0, 500)

I tried to identify if there was anything wrong with how i've randomised sidetop, leftright or topdown, but I could'nt find anything that hinted for what I should do.




mercredi 8 novembre 2023

Random selection based on weightage and previous history

I have a spring boot application for a notification system. Consider sms notifications for which I have n vendors to select from. Every vendor has been promised a certain percentage of our business, say their weightage.

During a time duration say 24 hours, a particular vendor is selected based on their weightage percentage. Due to some reason if a vendor's services are down, our system selects the next highest priority vendor for delivering the notification or if a particular sms is to be sent by a particular vendor only then that is chosen.

Currently I am generating a random number between 0 to 100 and then using its value for selecting a vendor. What I want it to do is to use last window of sms notifications and then balance the percentage of sms sent in the current time window.

Example :

Vendor 1: 20% W, Vendor 2: 30% W and Vendor 3: 50% W.

In first 24 hours I send 10 sms.

  1. Vendor 1 sent 3 sms -> 30%
  2. Vendor 2 sent 4 sms -> 40%
  3. Vendor 3 sent 3 sms -> 30%

So what I would like is if I send 20 sms by the end next time window Then

  1. Vendor 1 should have sent 3 sms -> 15%
  2. Vendor 2 should have sent 5 sms -> 25%
  3. Vendor 3 should have sent 12 sms -> 60%

Averaging over 30 sms for 2 time windows, vendor 1: 20%, vendor 2: 30% and vendor 3: 50%

The same balancing/averaging is to be done over all time windows.

My issue is how to implement this when I don't know the number of sms I will send in a day. The range is generally around a hundred thousands, but sometimes much more.

My current implementation:

if (Objects.nonNull(templateEntity.getSmsVendor())) {
      // case 1 - when vendor is specified in notification template, use that vendor
      smsNotifier.get(templateEntity.getSmsVendor()).send(notificationRequestDTO);
    } else {
      // case 2 - when vendor is NOT specified in notification template. Choose weightage wise vendor
      int totalProbability = 0;
      for (SmsNotifier notifier : smsNotifierList) {
        totalProbability += notifier.getWeightage();
      }
    
      int randomNumber = RandomUtils.nextInt(0, totalProbability);
      int currentProbability = 0;
    
      // vendor1 = 60, vendor2 = 40, Mock = 0
      for (SmsNotifier notifier : smsNotifierList) {
        if (randomNumber >= currentProbability && randomNumber < currentProbability + notifier.getWeightage()) {
          log.error("Selected vendor for sms {} is {} weightage {} current probability {}", notificationRequestDTO, notifier.getId(), notifier.getWeightage(), currentProbability);
          notifier.send(notificationRequestDTO);
          break;
        }
        currentProbability += notifier.getWeightage();
      }
    }



mardi 7 novembre 2023

How to do random BFS traversal in networkx?

I want to implement a BFS traversal algorithm on large graphs in a random order (has to be as fast as a normal BFS traversal).

Here is the code snippet that I have:

def perform_random_bfs(self, g, source):
    visited = set()
    queue = [source]
    random_dfs_list = [source]
    visited.add(source)
    while len(queue):
        curr = queue.pop(0)
        childs = []
        for child in g.neighbors(curr):
            if child not in visited:
                visited.add(child)
                childs.append(child)
                queue.append(child)
        random.shuffle(childs)
        [random_dfs_list.append(child) for child in childs]
    return random_dfs_list

Any ideas on speeding it up? I think random.shuffle is the bottleneck.




Why does Random.NextInt64 create duplicates and not distribute the values across the whole range

I have written a small C# console application to generate a million random longs

I have already included ThreadLocal to avoid creating duplicates

here if the code I am running:

var random = new ThreadLocal<Random>(() => new Random());
var numbers = new List<long>();

for (int i = 0; i < 1000000; i++)
{
    numbers.Add(random.Value.NextInt64(1, 999999999999));
}

var metrics = numbers.Select(x => x.ToString().Length).GroupBy(x => x).Select(group => new {
    NumberLength = group.Key,
    Count = group.Count()
}).OrderBy(x => x.NumberLength);

var hashSet = new HashSet<long>();
var duplicates = new List<long>();
foreach (var item in numbers)
{
    if (!hashSet.Add(item))
    {
        duplicates.Add(item);
    }
}

this code above is creating:

  • 2 duplicates
  • The numbers generated all seem to be weighted towards the higher end

enter image description here

Why has this out of the box C# method generated duplicate "random" numbers and also not distributed the longs across the whole range?




lundi 6 novembre 2023

How to Compare a few Lists[], and print the Lists that have matching items

Basically Im trying to create a Random Movie Picker from a list of My Favorite films based off of a keyword input().

I want to search "Comedy", get back a list of the Comedy Titles in a textBox, as well as, One randomly selected "Comedy Title" configured into a Label.

My approach is...

list= [["Title1", "Comedy", "Movie"],
       ["Title2", "Comedy", "Movie"],
       ["Title3", "Anime", "Movie"],
       ["Title4", "Horror", "Show"],
       ["Title5", "Comedy", "Show"],
       ["Title6", "Comedy", "Show"],
       ["Title7", "Horror", "Movie"],
       ["Title8", "Comedy", "Movie"],
       ["Title9", "Comedy", "Show"],
       ["Title10", "Anime", "Show"]] 


def picker_button():
    for item in list:
        if item[1] == textBox1.get():
            textBox2.insert(customtkinter.END, item[0] + "\n")
            label.configure(text=random.choice(item[0]))

The Goal

  1. Give an input() of "Comedy" or "Show".
  2. On command, Loop through the lists, looking for the input(keyword) in each list.
  3. insert() a list of the found "titles" into a textBox.
  4. and configure() the label to a random.choice of "title"/item[0] from list of the Comedy Titles.

The Result

  1. Takes the input() fine.
  2. Loops without Error.
  3. Successfully, insert() a list of "Comedy" related "titles"/item[0] into textBox.
  4. Failed to Get random.choice of "Title". Label Configures to a single character of the item[0]/"title" from only the last list/"title10". It changes the Label to just a: "t" or "i" or "e" or "1" --ScreenShot of GUI output when input() == "Comedy"

Question:

  1. How can I get my label to configure() to a random.choice of "title"/item[0] of the "scanned lists" that meet the "Comedy" filter.
  2. and also return the entire "Title" instead of just "t" or "i"???

Heres the actual code:

from random import choice
import customtkinter
from tkinter import *
import random
from PIL import Image, ImageTk
import tkinter

# theme and color
customtkinter.set_appearance_mode("dark")  #"system", "light", or "dark"
customtkinter.set_default_color_theme("dark-blue") #"blue", "dark-blue", or "green"

#root = Tk()
root = customtkinter.CTk()
root.geometry("600x600")
root.iconbitmap('images/codemy.ico')
root.title("Bucket Pull")

img1=ImageTk.PhotoImage(Image.open("sasa.jpg"), Image.Resampling.LANCZOS)
World=customtkinter.CTkLabel(master=root, image=img1, corner_radius=15)
World.pack(pady=20, padx=20)

Logframe = customtkinter.CTkFrame(master=World, width=320, height=360)
Logframe.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER)



# Movies
movies = [["Hitchhikers Guide to the Galaxy", "Comedy", "Movie"],
          ["Monty Python: Life of Brian", "Comedy", "Movie"],
          ["Nothing But Trouble", "Comedy", "Movie"],
          ["Planet Terror", "Action", "Movie"],
          ["Futurama", "Comedy", "Show"],
          ["Death Proof", "Suspense", "Movie"],
          ["The Machine", "Comedy", "Movie"],
          ["Spirited Away", "Anime", "Movie"],
          ["I Think You Should Leave!", "Comedy", "Show"],
          ["Kill Tony", "Comedy", "Show"],
          ["Seinfeld", "Comedy", "Show"],
          ["Barbie", "Comedy", "Movie"],
          ["Back to the Future", "Comedy", "Movie"],
          ["South Park", "Comedy", "Show"],
          ["Fruits Basket", "Anime", "Show"]]

def moodie():
    for item in movies:
        if item[1] == My_Mood.get():
            Mood_text.insert(customtkinter.END, item[0] + "\n")
            Mood_Label.configure(text=random.choice(item))
            
def clear():
    Mood_Label.configure()
    
Main_Label = customtkinter.CTkLabel(master=Logframe,text=" Bucket Pull ",font=("klee", 45),text_color="lightblue")
Main_Label.pack(pady=20, padx=20)
#Entry
My_Mood = customtkinter.CTkEntry(master=Logframe, width=200, height=40)
My_Mood.pack(pady=20, padx=20)
#Button
Mood_Button = customtkinter.CTkButton(master=Logframe, text="Mood", width=60, height=20, command=moodie)
Mood_Button.pack(pady=10, padx=10)
#Label
Mood_Label = customtkinter.CTkLabel(master=Logframe, text="A", font=("muna", 18),fg_color="transparent")
Mood_Label.pack(pady=20, padx=20)
#Textbox
Mood_text = customtkinter.CTkTextbox(master=Logframe, height=200, width=250)
Mood_text.pack(pady=20, padx=20)

#ADD Ween Button
        
        
        
root.mainloop()



dimanche 5 novembre 2023

Random number not writing to file [closed]

package ag;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.io.PrintWriter;

public class CowPath {
    
    private static String newNum;
    
    private static JTextField textField;

    private static void createAndShowGUI() throws IOException {

        JFrame frame = new JFrame("Bessie's Paths");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(400, 120));

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(2, 1, 0, 10));

        JLabel label = new JLabel("How many paths surround Bessie");
        textField = new JTextField(10);
        JButton doneButton = new JButton("Done");

        label.setHorizontalAlignment(JLabel.CENTER);
        textField.setHorizontalAlignment(JTextField.CENTER);
        doneButton.setPreferredSize(new Dimension(150, 30));

        panel.add(label);
        panel.add(textField);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(doneButton);

        doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
                    doneButtonactionPerformed(evt);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });

        frame.add(panel, BorderLayout.NORTH);
        frame.add(buttonPanel, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);



    }

    private static void doneButtonactionPerformed(ActionEvent evt) throws IOException {
        int max3 = 1000;
        int min3 = 100;
        int num2 = new Random().nextInt(max3 - min3) + min3;
        
        newNum = textField.getText();

        if (newNum != null) {
    
            int max13 = Integer.parseInt(newNum);
            int min13 = 1;
            int randInt26 = new Random().nextInt(max13 + 1 - min13) + min13;
            
            String filePath = "/Users/arnavgupta/eclipse-workspace/Q4Assesment2ArnavGuptaSoftware2023/src/ag/CowPaths" + randInt26 + ".txt";
            
            FileWriter writer = new FileWriter(filePath);

            int max = 200;
            int min = 10;
            int randInt2 = new Random().nextInt(max + 1 - min) + min;

            writer.write(String.valueOf(num2));
            
            for (int i = 1; i < Integer.parseInt(newNum); i++) {
                String filePath2 = "/Users/arnavgupta/eclipse-workspace/Q4Assesment2ArnavGuptaSoftware2023/src/ag/CowPaths" + i + ".txt";
                File myObj = new File(filePath2);
                if (myObj.createNewFile()) {
                    for (int i1 = randInt2; i1 > 0; i1--) {
                        Random rand = new Random();
                        int rand_int1 = rand.nextInt(100);
                        writer.write(String.valueOf(rand_int1) + "  ");
                        System.out.println(rand_int1);
                    }
                  } 
                BufferedReader reader = new BufferedReader(new FileReader(filePath2));
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] numberStrings = line.split("  ");
                    for (String numStr : numberStrings) {
                        double num = Double.parseDouble(numStr);
                        if (num > 100) {
                            JOptionPane.showMessageDialog(null, "Bessie found the path, in total she went through " + i + " paths and walked " + randInt2 + " Meters");
                            for (int i2 = 1; i2 < Integer.parseInt(newNum); i2++) {
                                String filePath3 = "/Users/arnavgupta/eclipse-workspace/Q4Assesment2ArnavGuptaSoftware2023/src/ag/CowPaths" + i2 + ".txt";
                                FileWriter fwOb = new FileWriter(filePath3, false); 
                                PrintWriter pwOb = new PrintWriter(fwOb, false);
                                pwOb.flush();
                                pwOb.close();
                                fwOb.close();
                            System.exit(0);
                        }
                        }
                    }
                reader.close();
            }

        }           writer.close();
        }
        
        

    }
    

    public static void main(String[] args) throws IOException {
        createAndShowGUI();
    }

}

This code is supposed to mimic the cow path problem and the way it works is that it should plant a bunch of numbers below 100 into each file, then seed a number above 100 in one of the files then find the number above 100. however, the numbers below 100 are not being added to the file. why is that the case?