vendredi 30 juin 2023

Why does it give same result (I am a beginner) [duplicate]

I kept on getting 84 in the response for some reason. C++ kept on choosing 84 randomly! Do you have a idea why this is happening. (Also, please please do not shut down this question, I need help!) Some c++ code below

#include <bits/stdc++.h>
using namespace std;

int main()
{
int choice=1+(rand()%100);
cout<<choice;
}

I kept on seeing 84! Why did it choose 84 all the time ?!




jeudi 29 juin 2023

Why does VB Random.Next appear misbehave when within an If or Case statement?

I have a snippet of code to select a string randomly from an array. It works fine, except it misbehaves when run within a select-case or If statement.

The following code gives me a random result for Petrol or Diesel, however I only ever get a return of "Electronic Injection Pump" when the randomly selected fuel is "Diesel", and I only get "Carburettor" or "Mechanical Fuel Injection" when the randomly selected fuel is "Petrol".

If I take the fuel system selection code out of the case statement it works as expected giving all the fuel system options. I have tried using an If statement but this gives the same flawed result. The .count values return their expected results of 2 and 3 respectively.

I'm really scratching my head because "Electronic Injection Pump" is second in it's array, while "carburettor" and "Mechanical Fuel Injection" are first and second in their array, so there seems no rhyme or reason to the faulty result.

Dim fuelLr = New Random()
        Dim fuelList() As String = {"Petrol", "Diesel"}
        Dim fuel = fuelList(fuelLr.Next(0, fuelList.Count))

        Dim fuelSystem
        Select Case fuel
            Case "Diesel"
                Dim dieselSystemLr = New Random()
                Dim dieselSystemList() As String = {"Mechanical Injection Pump", "Electronic Injection Pump"}
                fuelSystem = dieselSystemList(dieselSystemLr.Next(0, dieselSystemList.Count))

            Case "Petrol"
                Dim petrolSystemLr = New Random()
                Dim petrolSystemList() As String = {"Carburettor", "Mechanical Fuel Injection", "Electronic Fuel Injection"}
                fuelSystem = petrolSystemList(petrolSystemLr.Next(0, petrolSystemList.Count))

        End Select



(Roblox Studio/Lua) How do I place 2 random gears from game.Workspace.items into player.Backpack everytime they spawn or respawn?

I need a script in Roblox Studio (Lua code) that places two random gears from the folder game.Workspace.items into the player's backpack ( player.Backpack I think)

I tried this code and it did nothing:

`
    local player = game.Players.LocalPlayer
    local itemsFolder = game.Workspace.items
    local backpack = player.Backpack
    
local function getRandomItems()
        local items = itemsFolder:GetChildren()
    local selectedItems = {}

    if #items >= 2 then
        local randomIndices = {}

        while #randomIndices < 2 do
            local randomIndex = math.random(1, #items)

            if not table.find(randomIndices, randomIndex) then 
                table.insert(randomIndices, randomIndex)
            end
        end

        for _, index in ipairs(randomIndices) do
            table.insert(selectedItems, items[index])
        end
    end

    return selectedItems
end

 player.CharacterAdded:Connect(function(character)
    backpack:ClearAllChildren()

    local selectedItems = getRandomItems()

    for _, item in ipairs(selectedItems) do
        local clone = item:Clone()
        clone.Parent = backpack
    end
end)`



How do I make a random permutation function in Google Sheets

I need to generate a function on google sheets that randomly generates 8 numbers within the range of 1:8. It needs to be a permutation, so none of the 8 numbers should repeat. I am able to do this in R, but my advisor is requesting that I do it in google sheets. If you need any additional information to make this work please let me know!

I have tried using a random array function and restricted the range to 1-8 but it will generate the same number multiple times.




Session state and button reloads in Streamlit not working as expected

I have a piece of code (written in python using streamlit) that creates a random number of clickable buttons (between 2 and 5) and the number of buttons are regenerated after the user clicks on one. I've tried having a textbox that always prints what buttons was clicked last but there's an issue when the current buttonLen is longer than the previous and the final button was clicked on, the textbox doesn't print the correct button (as it somehow loops over the shorter loop instead of the loop index being the max??), why is that?

# init click info as -1
if 'lastClick' not in st.session_state:
    st.session_state.lastClick = -1

if 'buttonLen' not in st.session_state:
    st.session_state.buttonLen = random.randint(2, 5)

fake = st.button("stupid", disabled=True)

if 'buttons' not in st.session_state:
    st.session_state.buttons = [fake] * 5

for i in range(st.session_state.buttonLen):
    st.session_state.buttons[i]= st.button(str(i))

for i in range(5):
    st.write(f"{st.session_state.buttons[i]} currentButton")
    if st.session_state.buttons[i]:
        # a button was clicked on! what do we do?
        # if the button is the same as before, keep that button info as true, if not: reset it.
        if i != st.session_state.lastClick:
            st.session_state.buttons[i] = False
        # update current click info
        st.session_state.lastClick = i
        # regen n
        st.session_state.buttonLen = random.randint(2, 5)
        break  

st.write(f"{st.session_state.lastClick} last clicked")

if prompt != "":
    prompt_container.empty()
    st.info(prompt)
    sub = sub_container.subheader("Continue your story by choosing from the options below")

i tried using the session state variables as seen in the code. i used a 'fake' button that is always disabled and so has value 'False' to populate the buttons list, and rewrite the buttons as fit when generating them, this didn't fix the bug.




mercredi 28 juin 2023

I want to print a random sentecnce from my list every time i type x in input

import random
words = ["tree", "human", "city", "night", 
"falcon", "last", "first", "fruit", "animals", 
"often", "maybe", "through", "work", 
"good","random", "white"]
while True:
    sentence = input("print x: ")
    random_sentence = random.choice(words)
    print(random_sentence)

# i want it to be random sentence like this:
city last human fruit white animals often tree work through good random maybe falcon night first



Add a different random row from table A to each row in Table B

I have tow tables the one named A and the second named B, I want to add a a **different ** random row from table A to each row in Table B. There are no cummon fields between the tables.

I tried to do:

select idA,idB

from A,(select idB

        from B

        Order by dbms_random.random

        fetch first 1 row only)

But, the select in the 'from' executed only once. So, I got the same row from table B to all rows in table A.

Thanks.




mardi 27 juin 2023

Is there a way to create a 'truer' random outcome using a Gaussian normal distribution in C?

I've scoured stack overflow for some descriptions, explanations, and snippets of the std::normal_distribution<> variable(mean, stddev) function, and have found one instance in particular, listed below, that works quite effectively for my purpose, which is simply to be able to create and house a random number from a normal distribution given the mean and stddev.

#include <random>
...
std::mt19937 generator;
double mean = 100.0, stddev  = 15.0, example;
std::normal_distribution<double> normal(mean, stddev);
example = normal(generator);
cout << "Normal: " << example << endl;

credit - https://stackoverflow.com/a/11977979/14316685.

The one problem that I"ve run into, however, is that the results from this code become quite repetitive and predicatable over time. For example, I've repeatedly used a mean of 100 and a stddev of 15, which when run over 1000 instances almost assuredly, produces exactly one instance of both approximately 52.246 and 156.86 consistently, at least on my system.

Is there a way to manipulate this code snippet, or seed if I understand this correctly, so that it produces a variety of results that are different enough each time while still obeying the normal distribution?

As I'm still new to this function, I tried utilizing std::default_random_engine generator; in the place of std::mt19937 generator, and while it produced a different result, it had a similar problem of repetition over time.




Foreach loop used to assign labels

enter image description here

I have created a basic matchning game by the help of Google. The user selects cards which show different icons (using the icon scriptfont "webdings"). If the icon is paired with an identical icon, the cards remain on the screen, if not, both cards go blank again. The game is over when all pairs have been matched.

I have attached a snippet of the code which I struggle to understand. It works, but I would like to gain a better understanding. What mostly confuses me is the use of the random object and the next() method.

Can someone please attempt to describe the inner workings of this code to me?

Huge thanks.

I have tried to break it up into smaller pieces, both the foreach loop and the random method. But I still feel confused.




Random list doesn't iterate as excpected [duplicate]

I have a randoms list of names (37) and I need to pick 22 names out of it, given the condition that it can only be unique values and I need X number (22 this month) of names, the problem is that it does not gives me 22 names, it shows less. I tired this code:

random_auditores = []
for i in range(0,22):
    n = random.choice(auditores)
    if n not in random_auditores:
        random_auditores.append(n)
random_auditores



Read CLOB from Oracle using JDBC results in random ORA-17002 failure

As part of a Spring Boot application, I am attempting to query an Oracle Enterprise Edition AWS RDS table that contains CLOBs using JDBC. I am using Hakari connection pool and ojdbc8 version 23.2.0.0.

My code is:

Connection conn = null;
    ResultSet rs = null;
    try {
      conn = getConnection();
      PreparedStatement statement = conn.prepareStatement("select id, clobField from myTable");
      rs = statement.executeQuery();
      int recCount = 0;
      while (rs.next()) {
        long id = rs.getLong("id");
        String clob = rs.getString("clobField");
        res.put(id, clob);
        logger.debug("Retrieved record " + ++recCount + ");
      }
    } catch (Exception ex) {
      throw ex;
    } finally {
      if (rs != null) {
        rs.close();
      }
       if (conn != null) {
         conn.close();
       }
    }

The number of records that are successfully retrieved without erroring out is random. When it errors out, I am seeing this error:

java.sql.SQLRecoverableException: ORA-17002: I/O error: An existing connection was forcibly closed by the remote host

Any ideas why this is happening?

This was originally mapped to a spring bean using Hibernate which resulted in the same error. I am trying to isolate the problem, buy decomposing it to just use JDBC.




random.sample producing same output when iterated over inside function

I'm trying to write a poker hand evaluator with a monte carlo simulation.

When simulating game outcomes (e.g. dealing cards) inside a function using random.sample randomization works fine.

def simulate(hands, board):
# create deck
suits = ['d','s','c','h']
ranks = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']
cards = []
for r in ranks:
    for s in suits:
        cards.append(r+s)

# shuffle deck
deck = random.sample(cards,len(cards)) 
# remove board and player cards from deck
deck = list(filter(lambda x: x not in board, deck))
for hand in hands:
      deck = list(filter(lambda x: x not in hand, deck))

# deal turn and river
while len(board) < 5:
    card = deck.pop(0)
    board.append(card)
return board
for i in range(2):
    outcome = simulate([['Ah', 'Ac'], ['7s', '6s']], ['2d', '5s', '8s'])
    print(outcome)
Output:
['2d', '5s', '8s', '9s', 'Jc']
['2d', '5s', '8s', '4s', '3s']

If I run this inside a for loop it works fine but once I put this into another function randomization fails and I keep getting the same result.

def monte_carlo(hands, board, samples=5):
    for i in range(samples):
        outcome = simulate(hands, board)
        print(outcome)

monte_carlo([['Ah', 'Ac'], ['7s', '6s']], ['2d', '5s', '8s'])

Output:
Board  ['2d', '5s', '8s', '2c', '4d']
None
Board  ['2d', '5s', '8s', '2c', '4d']
None
Board  ['2d', '5s', '8s', '2c', '4d']
None
Board  ['2d', '5s', '8s', '2c', '4d']
None
Board  ['2d', '5s', '8s', '2c', '4d']

What is the reason for this behaviour?




Macro to select random row from filtered sheet?

Morning all. I have next to zero knowledge of any kind of coding so please bear with me. I've got a massive spreadsheet with hundreds of thousands of lines. I've got various macros to filter down the sheet, but once I've narrowed it down I'd like to have a macro that can select one line from the filtered results. I did find one that worked (someone else's work) but it didn't take the filtering into account and I'm not sure how to amend it to do so.

Sub Random_Selection()
Dim ColumnA As Long
Dim StartRow As Long
Dim HeaderRow As Long
Dim LastRow As Long

ColumnA = 1
HeaderRow = 5  
StartRow = 6
LastRow = Cells(Rows.Count, 1).End(xlUp).Row

Dim randomNum As Long
randomNum = WorksheetFunction.RandBetween(StartRow, LastRow)
Cells(randomNum, ColumnA).Select

End Sub

As I say - this worked well on a random selection of 'all' the rows - but I need it to only choose at random from the 'visible' rows after filtering has been applied.

Hope someone can help and I apologise for the total lack of knowledge on my part!




lundi 26 juin 2023

Probability and statistics

'''

Let X and Y are two random variables with ρ_(X,Y)=0.2, V(X)=16, V(Y)=25. You are interested to find α and β for which E[(Y-α-βX)^2] is minimum. What is the value of β? '''




dimanche 25 juin 2023

How can i link a specific array item from one list to a corresponding array item from a different array list?

So i am creating a Star Wars inspired random quote generator on vscode which gives a random quote and also gives a real life scenario in which it could be used (advice), but i have encountered an issue which should be simple enough to fix.

I have two different arrays, a 'quotes' array and a 'advice' array. When i call one of the quotes at random from 'quotes' array, i want that quote that appeared, to trigger a corresponding line from the 'advice' array so that they appear together. For example quote '1' pairs with advice '1'. I managed to get to the point where when i press the 'Get Quote' button on my site, it triggers a random quote as it should, but also a random line of advice rather than the one i would like to appear.

How can i pair a quote from one array with an advice from the other array, and when the random quote is called, also have the advice that pairs with it, also output to the page? Hope i have explained this well enough, first time posting. Thanks in advance. JavaScript Code Blow.

let btn = document.getElementById("btn");
let output = document.getElementById("output");
let quotes = [
  /*1*/ '"Its not my fault." - Han Solo',
  /*2*/ '"Your focus determines your reality." - Qui-Gon Jinn',
  /*3*/ '"Do. Or do not. There is no try." - Yoda',
  /*4*/ '"Somebody has to save our skins." - Leia Organa',
  /*5*/ '"In my experience there is no such thing as luck." - Obi-Wan Kenobi',
  /*6*/ '"I find your lack of faith disturbing." - Darth Vader',
  /*7*/ '"Ive got a bad feeling about this." - Basically Everyone',
  /*8*/ '"Its a trap!" - Admiral Ackbar',
  /*9*/ '"So this is how liberty dies...with thunderous applause." - Padmé Amidala',
  /*10*/ '"Your eyes can deceive you. Dont trust them." - Obi-Wan Kenobi',
  /*11*/ '"Never tell me the odds." - Han Solo',
  /*12*/ '"RWAAARWWR!" - Chewbacca',
  /*13*/ '"Stay on target." - Gold Five',
  /*14*/ '"This is a new day, a new beginning." - Ahsoka Tano',
  /*15*/ '"This is the way." - The Mandalorian',
];

let advice = [
  /*1*/ "Use when anything goes wrong, even if it is totally your fault.",
  /*2*/ "Use in pep talks to encourage positivity and to remind others to take control of their fate.",
  /*3*/ "Use when someone needs a little tough love.",
  /*4*/ "Use when you jump in and solve a problem without breaking a sweat.",
  /*5*/ "Use to remind others hard work pays off and sitting around waiting for chance does not.",
  /*6*/ "Use anytime others doubt your plans.",
  /*7*/ "Use when walking into a situation that could end poorly.",
  /*8*/ "Use anytime you suspect something is too good to be true.",
  /*9*/ "Use sarcastically whenever anyone institutes a new policy that looks appealing on the surface but has negative repercussions.",
  /*10*/ "Use when a friend needs to be reminded to go with his or her gut feeling.",
  /*11*/ "Use whenever you are told a task cant be done.",
  /*12*/ "Use when you move a chair",
  /*13*/ "Use to keep yourself or others focused.",
  /*14*/ "Use to cheer a pal up and remind him or her that every day brings new opportunities.",
  /*15*/ "Use when one makes the right decision",
];

// combine quote and advice
// commit changes to git
btn.addEventListener("click", function () {
  var randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
  var randomAdvice = advice[Math.floor(Math.random() * advice.length)];
  output.innerHTML = randomQuote + "<br>" + randomAdvice;
});

I tried assigning quote 1 to advice 1 like so

quote[0] = advice[0];

And so on and soforth, however this just replicated the quote twice instead of asigning advice 1 to quote 1.




how to add delay between two random choice python?

my code look like this :

import random
import time

number = '123'
items = ['one', 'two', 'three']

    n1 = str (random.choice(items ))
    n2 = str (random.choice(items ))
    n3 = str (random.choice(items ))

    choice = (n1+n2+n3)
        finalchoice = foo(choice)

how do add delay before item list value change ?

result script right now is :

one + random number 
two + random number 
three + random number 

what i want , script result is :

one + random number 
one + random number
one + random number

after 3 second, then thread change to

two + random number 
two + random number 
two + random number 
 

after 3 second, then thread change to

three + random number 
three + random number 
three + random number 

please help




jeudi 22 juin 2023

random pathway generating algo within time constraints

I wanted to understand how a random pathway generating algo with 6 data points - source value, destination value and two extreme distance points within a an enclosed time constarint might be created. meaning if we use time - 10:00 AM as start point at location A and 10 PM as finish point at B and has to reach C which can be a certain distance from A and D another point that should be reached at a specefied time total 12 hours in between being the duration to contruct the path but it also has to be at destaination time by the 10 PM time. i want to be able to give it these 4 values each time with the specefic times to reach them and also its free to wallow with in the given area of distance and i want it to generate different pattern pathways from 10:00 Am to the extereme points and then back to the destination value by 10 PM so i want it to generate random pathways to the specefied points i give it each time by varying the time interval to reach how can nodes be applied to this idea?

i dont know if this makes sense i am not a programer but i want to hear you intelligent folks ideas on this concept




How Would I Call Class1 method to Class 2 So I can Print it out on class 2

I have 2 Class here. One that creates the random number and one that prints out the random number except class 2 cannot retrieve the random number and I'm not sure why, any help?

{
    class Class1
    {
        public static void Main(string[] args)
        {
            Random random = new Random();
            int num = random.Next(33, 126);
            Console.WriteLine(num);
            Console.ReadKey();
        }
    }
    class Class2
    {
        static void Main(string[] args)
        {
                Class1 number = new Class1();
                Console.WriteLine(num);
                Console.ReadKey();
        }
    }
}




I tried creating an object for class1 in class2 but it didn't change anything.



How to assign random normal values for each cell

I have a dataset based on a 5-point Likert scale. I want to transform each cell into a normal distribution value with pregiven mean and std. My code for now is as follows.

import random
Mu={1:0.021,2:0.146,3:0.375,4:0.625,5:0.979}
std={1:0.021,2:0.104,3:0.125,4:0.125,5:0.021}

#defining the random dictionary 
rnd={1:random.normalvariate(Mu[1], std[1]),
    2:random.normalvariate(Mu[2], std[2]),
    3:random.normalvariate(Mu[3], std[3]),
    4:random.normalvariate(Mu[4], std[4]),
    5:random.normalvariate(Mu[5], std[5])}

raw_data_rnd=raw_data.copy()

for col in raw_data_rnd.columns:
    raw_data_rnd[col].mask(raw_data_rnd[col]==1,random.normalvariate(Mu[1],std[1]),inplace=True)
    raw_data_rnd[col].mask(raw_data_rnd[col]==2,random.normalvariate(Mu[2],std[2]),inplace=True)
    raw_data_rnd[col].mask(raw_data_rnd[col]==3,random.normalvariate(Mu[3],std[3]),inplace=True)
    raw_data_rnd[col].mask(raw_data_rnd[col]==4,random.normalvariate(Mu[4],std[4]),inplace=True)
    raw_data_rnd[col].mask(raw_data_rnd[col]==5,random.normalvariate(Mu[5],std[5]),inplace=True)
raw_data_rnd

The code is working. However, it gives the same value for every cell where the condition is true. What I need is for the code to somehow loop the random value assignment and put a different value in each cell. In other words, for instance every time the dataframe has the value of 1, I need the code to assign a new random value.

Can anyone help, please?

I have tried several methods. However, I am still hitting deadends.




How to get "default" random object (or seed) in Java?

I know that I can create Random object and set seed for the object like this:

Random random = new Random();
random.setSeed(seed);

But what if I can't create Random object? What if I have to use Math.random()?

I know that Math.random() creates Random object behind the scene.

So the question is there any way to get the Random object created by Math.random and set seed for the object or at least get seed that the object is using?




mercredi 21 juin 2023

When random number hits certain value h1 or button should change color

I made a random color generator and while it generates the random colors and displays the numbers, when it gets very dark on the page I wanted the h1 to become white and the button to become black if it became very bright.

const button = document.getElementById('button');
const h1 = document.getElementById('h1');

button.addEventListener('click', function (){
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    const newColor = `rgb(${r}, ${g}, ${b})`;
    document.body.style.backgroundColor = newColor;
    h1.innerText = newColor;
});

button.addEventListener('click', function (){
    if(parseFloat(r >= 150 || g >= 150 || b >= 150)) {
        document.button.style.backgroundColor = '#000';
        document.button.style.color = '#fff';
    } else if(parseFloat(r >= 60 || g >= 60 || b >= 60)) {
        document.h1.style.color = '#fff';
    }
});

I think there is an issue with my parseFloat but I am unsure. I think the issue is that the number becomes a string and isn't converted back properly?

Right now my code just does not respond to the second portion where I ask the 'if' statements.




mardi 20 juin 2023

Google sheets. Random value. How to sum values

This is a risk analysis app.
I'm not very good at sheets and looking for advice

https://docs.google.com/spreadsheets/d/1yFq7XCypJK77CBZc3x9tlEsW63mFy21nuO3I9kzGHaQ/edit?usp=drivesdk

Can anyone advise how to adjust the account balance to account for each time pnL unrealized updates? I'd like it to accumulate all the numbers that are Generated each time the page refreshes?

For example if page refreshes 3 times and the values of purple pnL unrealized happened to be -200, 500, 250

Account balance would update each time and would finally read

Account balance = $50,550.

I'm using the random number generator =RANDBETWEEN(-C6,C6) For the pnL unrealized.

https://docs.google.com/spreadsheets/d/1yFq7XCypJK77CBZc3x9tlEsW63mFy21nuO3I9kzGHaQ/edit?usp=drivesdk

Not great at these formulas and any advice would be greatly appreciated! Thank you in advance!




lundi 19 juin 2023

python weighted random sample

There is a random.choices(sequence, weights=None, cum_weights=None, k=1) function that can return weighted sublist of a list with replacement. There is a random.sample() that returns a random sublist without replacement but it does not take weights into account. Is there a functions that returns weighted sublist without replacement?




Im trying to modify a FNF mod to randomize the jumpscare that appears but simply: nothing appears?

function eventFunction(params) {
    var length:Float = Std.parseFloat(params[1]);
    var portrait:String = 'Gold';
    switch (PlayState.dadOpponent.curCharacter.toLowerCase()) {
        case 'gold-headless':
        var i = math.round(math.random(1, 3))
            switch (i) {
                case (i == 1):
                portrait = 'GoldAlt';
                break;
                case (i == 2):
                portrait = 'GoldAlt2';
                break;
                case (i == 3):
                portrait = 'GoldAlt3';
                break;
            }
    }

heres the code. i have 3 images set up and when i remove the switch thing an image does show up, but when i want 3 random different images for the game to pick from then nothing shows up. sry if this is stupid but im really bad at javascript




dimanche 18 juin 2023

Flutter: How do I access this variable within onClicked in another file? (static doesn't work)

I've only been learning flutter or programming at all for 4 days and I want to make a very basic famous quote generation app. I have a variable, currentQuote which is called under onPressed in the file that houses the button. In the below code:

import 'package:flutter/material.dart';
import 'package:daily_quotes/random_quote.dart';

class ButtonQuote extends StatefulWidget {
  const ButtonQuote({super.key});
  

  @override
  State<ButtonQuote> createState() => _ButtonQuoteState();
}

class _ButtonQuoteState extends State<ButtonQuote> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 50),
      child: Center(
        child: Column(
        children: [
          TextButton(onPressed: () {
            RandomQuote().currentQuote;
          }, 
          style: TextButton.styleFrom(
            foregroundColor: Colors.black,
            backgroundColor: Colors.red,
            textStyle: const TextStyle(fontSize:30),
          ),

          child: const Text("New Quote")
          )
        ],
          ),
      ));
  }
}


I then have another file which handles the random generation. I've just made it generate a number between 1 and 10 and print in console under setState. For testing before I add images and text that depend on what number is generated. Shown below.

import 'package:flutter/material.dart';
import 'package:daily_quotes/regen_button.dart';
import 'dart:math';


class RandomQuote extends StatefulWidget {
  const RandomQuote({super.key});

  @override
  State<RandomQuote> createState() => _RandomQuoteState();
}

class _RandomQuoteState extends State<RandomQuote> {
  static var currentQuote = 1;
  final ranNum = Random();

  void quoteGen() {
    var generation = ranNum.nextInt(10) + 1;
    setState(() {
      currentQuote = generation;
      print("$currentQuote");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          ButtonQuote(),
        ],
      ));
  }
}

The problem lies in this below. First off it seems I've got 'RandomQuote()' wrong and it should be '_RandomQuoteState().currentQuote;' However both options show an error.

          TextButton(onPressed: () {
            RandomQuote().currentQuote;
          }, 

With _RandomQuoteState I get the error The method '_RandomQuoteState' isn't defined for the type '_ButtonQuoteState'. Try correcting the name to the name of an existing method, or defining a method named '_RandomQuoteState'.




Randomly generate all unique pair-wise combination of elements between two list in set time

I have two lists:

a = [1, 2, 3, 5]
b = ["a", "b", "c", "d"]

And would like to generate all possible combinations with a python generator. I know I could be doing:

combinations = list(itertools.product(a,b))
random.shuffle(combinations)

But that one has an extreme memory cost as i would have to hold in memory all possible combinations, even if only wanted two random unique combinations.

My target is to get a python generator that has its memory cost increase with the more iterations are requested from it, getting to the same O memory cost as itertools at max iterations.

I had this for now:

def _unique_combinations(a: List, b: List):
    """
    Creates a generator that yields unique combinations of elements from a and b
    in the form of (a_element, b_element) tuples in a random order.
    """
    len_a, len_b = len(a), len(b)
    generated = set()
    for i in range(len_a):
        for j in range(len_b):
            while True:
                # choose random elements from a and b
                element_a = random.choice(a)
                element_b = random.choice(b)
                if (element_a, element_b) not in generated:
                    generated.add((element_a, element_b))
                    yield (element_a, element_b)
                    break

But its flawed as it can theoretically run forever if the random.choice lines are unlucky.

I'm looking to modify that existing generator so it generates the indexes randomly within a fix set of time, it will be okay to keep them track of as this will be linear increase in memory cost and not exponential.

How could i modify that random index generator to be bound in time?




samedi 17 juin 2023

why my image keeps appearing on the same place when I try to animate it

I want to make an image move from right to left and make the image appear on the right side of my pane randomly.The problem is that the image appears in the same place over and over again.

import javafx.animation.KeyFrame;

import javafx.animation.KeyValue;

import javafx.animation.Timeline;

import javafx.geometry.Rectangle2D;

import javafx.scene.image.ImageView;

import javafx.stage.Screen;

import javafx.util.Duration;

import java.util.Random;

public class Comet {

private static final int paneWidth = 1100;

private static final int paneHeight = 780;

private static final int cometWidth = 100;

private static final int cometHeight = 100;

private static final int duration = 3000;
private static final int delay = 1000;
private static final Random random = new Random();




public static void animateComet(ImageView imageView) {
    imageView.setFitWidth(cometWidth);
    imageView.setFitHeight(cometHeight);

    double y = random.nextDouble() * (paneHeight - cometHeight);
    imageView.setLayoutX(1100);
    imageView.setLayoutY(y);
    Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
    double rightBound = screenBounds.getWidth() - cometWidth;

    Timeline timeline = new Timeline();
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.setAutoReverse(false);

    KeyFrame startKeyFrame = new KeyFrame(Duration.ZERO, new KeyValue(imageView.translateXProperty(),                     screenBounds.getWidth()));
    KeyFrame endKeyFrame = new KeyFrame(Duration.millis(duration), new KeyValue(imageView.translateXProperty(), -paneWidth));

    timeline.getKeyFrames().addAll(startKeyFrame, endKeyFrame);

    timeline.setOnFinished(event -> {
        double newPosition = random.nextDouble() * rightBound;
        imageView.setTranslateX(newPosition);
        timeline.playFromStart();
    });

    timeline.setDelay(Duration.millis(delay));
    timeline.play();
    }
}

I am basically stuck here.Whatever I try,it is the same problem.I tried changing the duration,changed the random function boundaries.I am not that good with coding.So I would appreciate if someone would help me.




Python 3: using yield generator with random.randint to generate random integers in range (0-40) that do not duplicate for a range of 6

hi i am trying to use the yield generator to generate 6 random numbers that do not duplicate with the random modules random.randint function in a range of (0-40) this is most of the code for the program but not all of it to save space.

# Imports
from colorama import init, Fore
init()

# variables
cor = 0
no = 0
acceptable_values = list(range(0, 41))
acceptable_values_15 = list(range(0, 16))
unacceptable_values = list()
unacceptable_values2 = list()

    # user input for 6 non duplicate integers

    while True:
        try:
            user1 = int(input(Fore.LIGHTRED_EX + 'Input your first number between 0-40: ' + Fore.RESET))
            if user1 in acceptable_values:
                print(Fore.LIGHTGREEN_EX + '   Input accepted!' + Fore.RESET)
                unacceptable_values.append(user1)
                break
            else:
                print(Fore.LIGHTYELLOW_EX + '  Number entered must be between 0-40!' + Fore.RESET)
                continue
        except ValueError:
            print(Fore.LIGHTRED_EX + 'Invalid input!' + Fore.RESET)

(x6 for vars user1 though user6)


    # the 7th number is a lucky number between 0-15

    while True:
        try:
            user7 = int(input(Fore.LIGHTYELLOW_EX + 'Input your bonus seventh number between 0-15: ' + Fore.RESET))
            if user7 in unacceptable_values:
                print(Fore.LIGHTYELLOW_EX + "Input value has been entered before please select another number!" + Fore.RESET)
                continue
            elif user7 in acceptable_values_15:
                print(Fore.LIGHTGREEN_EX + '   Input accepted!' + Fore.RESET)
                break
            else:
                print(Fore.LIGHTYELLOW_EX + '  Number entered must be between 0-15!' + Fore.RESET)
                continue
        except ValueError:
            print(Fore.LIGHTRED_EX + 'Invalid input!' + Fore.RESET)

 # returns 6 random numbers between 0 and 40 with no duplicates. 

 def lottery():
        import random
        for i in range(6):
                yield random.randint(0, 41)
                unacceptable_values2.append(random_number)
                if random_number in unacceptable_values2:
                    continue

    # checks random numbers against user inputs 1-7 to see if they match and tallies the results

    for random_number in lottery():
        print(Fore.LIGHTCYAN_EX + "\nAnd the next number is... %d!" % random_number + Fore.RESET)

        if random_number == user1:
            print(Fore.LIGHTGREEN_EX + ' Input #1 number %s was correct!' % user1 + Fore.RESET)
            cor += 1
        elif random_number == user2:
            print(Fore.LIGHTGREEN_EX + ' Input #2 number %s was correct!' % user2 + Fore.RESET)
            cor += 1
        elif random_number == user3:
            print(Fore.LIGHTGREEN_EX + ' Input #3 number %s was correct!' % user3 + Fore.RESET)
            cor += 1
        elif random_number == user4:
            print(Fore.LIGHTGREEN_EX + ' Input #4 number %s was correct!' % user4 + Fore.RESET)
            cor += 1
        elif random_number == user5:
            print(Fore.LIGHTGREEN_EX + ' Input #5 number %s was correct!' % user5 + Fore.RESET)
            cor += 1
        elif random_number == user6:
            print(Fore.LIGHTGREEN_EX + ' Input #6 number %s was correct!' % user6 + Fore.RESET)
            cor += 1
        elif random_number == user7:
            print(Fore.LIGHTYELLOW_EX + ' Input #7 number %s was correct!' % user7 + Fore.RESET)
            cor += 1
        else:
            print(Fore.LIGHTRED_EX + ' None of your inputs match this selected number!' + Fore.RESET)
            no += 1

    # printing # of correct and wrong

    print(Fore.LIGHTGREEN_EX + '\n\nYou got %s numbers correct!' % cor + Fore.RESET)
    print(Fore.LIGHTRED_EX + '\nYou got %s numbers wrong!' % no + Fore.RESET)

the block of code i am having trouble with is this block:

 def lottery():
        import random

        # returns 6 numbers between 0 and 40 with no duplicates.

        for i in range(6):
                yield random.randint(0, 41)
                unacceptable_values2.append(random_number)
                if random_number in unacceptable_values2:
                    continue

I have several ideas as to what this code will actually do but i dont know what the actual outcome will be when a duplicate is found

my first guess is that the code will just generate 6 random numbers and display them regardless of if the number is a duplicate (not the desired outcome but probably the most likely outcome)

my second guess is that because of the continue it will just keep regenerating the 6 numbers if a duplicate is found until it gets 6 numbers with no duplicates and move on to the next block (desirable outcome but inefficient as it will keep regenerating all 6 number over and over until it has no duplicates)

my third guess is that it will generate random numbers tell it comes across a duplicate and simply regenerate that one duplicate number tell it is no longer a duplicate and then move to the next block (my desired outcome as it is probably the most efficient outcome but also an unlikely outcome)

my forth guess is that it will generate 6 numbers find a duplicate and discard it and continue leaving me a outcome with 5 random non repeating numbers instead of 6 (not a desired outcome as i need a range of 6 random non-duplicating numbers for this to work that being said i think this outcome is really unlikely as it probably wont discard the duplicate if found)

what i would like it to do is the third option where when it finds a duplicate number it just discards the duplicate and re-yields a new non-duplicate number in its place

i am trying to do this as readable as possible while using the yield function and random.randint without RE or partial or any convoluted methods as i want it to be as simple as possible for a friend who is new to python to easily be able to read and comprehend the code




vendredi 16 juin 2023

Fill shaped(sized) pandas Dataframe with values randomly by stat count value. Reverse action for .count()

I need a DataFrame with r rows and dynamic number of columns(based on groups). Input count column specifies how many True values are expected in the new DataFrame. My current implementation creates a temporary DataFrame with a single row containing a True value for each group in df, and then explode()'s that temporary dataframe. Finally, it groups by count and aggregates to result df

input

--

| group | count | ... 
|   A   |   2   |     
|   B   |   0   |     
|   C   |   4   |     
|   D   |   1   |     

And i need to fill new DataFrame with this values randomly (c-(columns) value is dynamic same as names)

expected output

--

A B C D
NaN NaN True True
True NaN True NaN
NaN NaN NaN NaN
NaN NaN True NaN
True NaN True NaN

I think it's possible to add a randomized set of length from 1 to r and after expanding and etc. just agg(sum) by this values.

my code

--

inputs = [
    {"group": "A", "count": 2},
    {"group": "B", "count": 0}, 
    {"group": "C", "count": 4}, 
    {"group": "D", "count": 1}, 
    ]
df = pd.DataFrame(inputs)

def expand(count:int, group: str) -> pd.DataFrame:
    """expands DF by counts"""
    count = int(round(count))
    df1 = pd.DataFrame([{group: True}])
    # I'm thinking here i need to add random seed
    df1 = df1.assign(count = [list(range(1, count+1))])\
             .explode('count')\
             .reset_index(drop=True)
    return df1

def creator(df: pd.DataFrame) -> pd.DataFrame:
    """create new DF for every group value(count)"""
    dfs = [expand(r, df['group'].values[0]) for r in list(df['count'].values)]
    df = pd.concat(dfs, ignore_index=True)
    return df
    
df.groupby('group', as_index=False)\
    .apply(creator)\
    .drop('count', axis=1)\
    # and groupby my seed
    .groupby(level=1)\
    .agg(sum)

I tried to declare my questions if it will be helpful:

  1. Is there any method in pandas to make this easy/better?
  2. How can I make random counts and assign them in the expand() function?
  3. Is it a way to create sized DataFrame with NaN and then just drop there my values randomly(like pd.where or something)?

PS: This is my first time asking a question, so I hope I have provided enough information!




How to generate a random number with likelihoods that follow a modified (squished) cosine curve?

I am trying to generate a number that follows a cosine curve with an increased period. The goal is to generate a number between 0 and 1, but be able to supply an amplitude/factor and a period/interval.

For example, given the following:

10_000.times.map do
  num = randcos(factor: 5, intervals: 3)
  (num * 13).floor # Group in 12 groups for graphing visibility
end

And then graphing those points based on frequency, I would want a chart that looks something like this:

desired graph

Because we set intervals: 3, we have 3 "spikes" where those groups of numbers are more likely. The low points still occur, but are approximately 1/5 as likely because we set factor: 5.

I've been trying to use Math.cos to do this, but I'm getting stuck when trying to map those higher numbers to a likelihood of generating a new set. I can get it to show the one "spike" just using Math.sin/Math.cos, but I want to be able to customize how many of them show up.

Here is an example of my most recent iteration, although it just has a descending chart:

def randcos(factor:, intervals:)
  max_scale = intervals*Math::PI
  min_scale = -max_scale

  # Grab a random index and apply it to the squished cos
  x = min_scale + (2 * max_scale * rand) 
  num = (Math.cos(x)+1)/2 # Normalize 0..1 instead of -1..1

  # Trying to use the `num` from above to then multiply by the factor to give us 
  # more likely high numbers when the cos is nearer to 1
  rand * num * factor 
end



How can I create 1000 columns of random variables using each row's mean and SD

My dataframe looks like this:

City Mean SD
Newcastle 60 0.81
Liverpool 62 0.91
Cardiff 65 0.87
Glasgow 59 0.86

I want to add column 'n' which contains new random values using the Mean and SD column values. I've done this before using:

df['n'] = np.random.normal(df['Mean'], df['SD'])

I then want to add a second column which generates a quintile rank based on the value in 'n'. I've done this using:

df['q'] = pd.qcut(df['n'], 5, labels = False)

City Mean SD n q n+1 q+1
Newcastle 60 0.81 57 5 55 5
Liverpool 62 0.91 61 1 57 4
Cardiff 65 0.87 60 1 61 1
Glasgow 59 0.86 55 3 58 3

I would like to loop these two steps to add 2000 columns, 1000 'n' columns (named 'n+1') and a 1000 'q' columns (named 'q+1').




jeudi 15 juin 2023

Find the prime numbers according to the following conditions

I am working on a project related to DSA signature and need to generate two random primes in C#. The parameters I have are:

  • P (1024 bits)
  • Q (160 bits)
  • The condition that (P-1) must be a multiple of Q.

I am not sure how to generate these primes as when I tried some normal algorithms, my program froze due to the large parameters. I would appreciate any help.

Thank you.




mercredi 14 juin 2023

Key generation in verilog for AES

I want to generate different key each time I run the code in vivado for AES . How can this be written in verilog?

I tried using $random in verilog and using seed value as $time with it. But this could generate different key for different clock cycles in the same run. But I want only one key for each simulation but different key when I re-run the code.




mardi 13 juin 2023

Stratified Random Sample

I have a large population of vouchers. I need to stratify the random sample according to dollar amounts. There are four categories of dollar amounts with percentage of population to be 1%, 2%, 3%, 4%. $0-$500, $500-$2000, $2000-$5000, and greater than $5000.

In Python: How do I

  1. Create code that can identify which category the voucher amount belongs
  2. Return/print selected samples from each of those categories reflective of the required percentage of population.

I searched for "Stratified random sample" or something like that and have not found what would work.




What does rand() % 2 mean?

I've come across this program but I can't seem to figure out this part. Please help me understand what is the use of rand() % 2 and how is it a condition to determine whether it's credit or debit?

#include<stdio.h>
#define NUM_TRANS 400
void * transactions(void * args) {
  int v;
    
  for(int i = 0; i < NUM_TRANS; i++) {
    v = (int) rand() % NUM_TRANS;
  
    if (rand() % 2) {
      // Crediting to user
      
     
      pthread_mutex_lock(&balance_lock);
      balance = balance + v;
      pthread_mutex_unlock(&balance_lock);
      
      pthread_mutex_lock(&credits_lock);
      credits = credits + v;
      pthread_mutex_unlock(&credits_lock);
      
    } else {
      // Debiting from user

      pthread_mutex_lock(&balance_lock);
      balance = balance - v;
      pthread_mutex_unlock(&balance_lock);
      
      pthread_mutex_lock(&debits_lock);
      debits = debits + v;
      pthread_mutex_unlock(&debits_lock);
    }
  }
}



Random Sample data based on other columns using python

I have a dataframe with 1lakh rows contains Country, State, bill_ID, item_id, dates etc... columns I want to random sample 5k lines out of 1lakh lines which should have atleast one bill_ID from all countries and state. In short it should cover all countries and states with atleast one bill_ID.

Note: bill_ID contains multiple item_id

I am doing testing on a sampled data which should cover all unique countries and states with there bill_IDs.




lundi 12 juin 2023

Good hashing algorithm for integer vector?

I am trying to come up with an algorithm that takes N 32 bit integers and computes a set of N pseudo random floating point values from 0 to 1 by scrambling the bits of the integers.

I am trying to search this up but all I get are hashing algorithms for cryptography or for data structures like hashtables.

The main challenge I am facing atm is that merely casting a large bit sequence into floats is very unpredictable so trying to get a normalized floating point value is proving tircky.

The final use case is to have a consistent way to generate a random vector for a given set of integer coordinates.

i.e. a mathematical map from a tuple of natural numbers N^n to a tuple of floating point coordinates sampled from the unit hyper cube. I am using this to generate "random" vector fields in a grid.




Julia gives "MethodError: rand!" when trying to optimize over a certain manifold using Manopt

My goal is to find the minimum of a certain function over the manifold of doubly stochastic matrices. I use the package Manopt (https://manoptjl.org/stable/) for this. The relevant part of my code looks like this:

using Random
using Graphs
using Manopt
using Manifolds
using LinearAlgebra

n = 8
G = DiGraph(n)
for i = 1:n
    add_edge!(G, i%n +1, (i+1)%n +1)
    add_edge!(G, (i+1)%n +1, i%n +1)
end

A = adjacency_matrix(G)
P_0 = A / 2
M = MultinomialMatrices(n, n)
f(M, p) = 0 #sum((P_0 - p).^ 2)

particle_swarm(M, f)

Of course I need to change f to a more complex function, however, the code is not even working in this case of f=0. I also tried using the Nelder Mead Method instead of the partical swarm, yielding the same error. The error is the following: "MethodError: rand!(::TaskLocalRNG, ::AbstractManifold, ::SubArray{Float64, 1, Matrix{Float64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}) is ambiguous. Candidates: [...]" and it keeps on listing 50-70 candidates.

Does anyone know what I am doing wrong?

I tried using different manifolds to optimize over and the problem didn't occur in the case of "simpler" one (eg. the sphere). I tried using other methods for optimizing, none of them worked.




Issue with Separating Combinations into Vectors in C+

I have a vector of 16 pairs of symbols and colors, where there are 4 different colors and 4 different symbols. I need to separate these combinations into 4 different vectors, with the following conditions:

A symbol cannot have the same color as another symbol in the same vector. A color cannot have the same symbol as another color in the same vector. A combination of symbol and color can only be used once in the 4 vectors. I have tried implementing the separation logic in C++, but I'm encountering an issue where sometimes, some combinations are not being assigned to any vector, even though it should be possible to assign them.

I have already tried shuffling the combinations randomly using random_shuffle and have checked the logic for validity. However, the problem still persists, and I'm unable to identify the cause.

Could someone please help me identify the issue and provide a solution to ensure that all combinations are assigned to the vectors while satisfying the given conditions? I appreciate any guidance or suggestions. Thank you!

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

vector<char> symbols = {'&', '#', '%', '$'};
vector<char> colors = {'R', 'G', 'B', 'Y'};
vector<pair<char, char>> combinations;

void separateVectors() {
    // Shuffle the combinations randomly
    srand(time(0));
    random_shuffle(combinations.begin(), combinations.end());

    vector<vector<pair<char, char>>> vectors(4); // Store the four separate vectors

    for (const auto& combination : combinations) {
        bool assigned = false; // Flag to indicate if the combination has been assigned

        // Iterate over the vectors to find a suitable one for the current combination
        for (int i = 0; i < 4; i++) {
            bool valid = true;

            // Check if the symbol or color already exists in the current vector
            for (const auto& pair : vectors[i]) {
                if (pair.first == combination.first || pair.second == combination.second) {
                    valid = false;
                    break;
                }
            }

            // If the combination satisfies the conditions, add it to the current vector and update the flag
            if (valid) {
                vectors[i].push_back(combination);
                assigned = true;
                break;
            }
        }

        // If the combination couldn't be assigned to any vector, print a warning
        if (!assigned) {
            cout << "Warning: Combination (" << combination.first << ", " << combination.second << ") couldn't be assigned." << endl;
        }
    }

    // Print the four separate vectors
    for (int i = 0; i < 4; i++) {
        cout << "Vector " << i << endl;
        for (const auto& pair : vectors[i]) {
            cout << "Symbol: " << pair.first << " Color: " << pair.second << endl;
        }
        cout << endl;
    }
}

int main() {
    // Generate all possible combinations
    for (const auto& symbol : symbols) {
        for (const auto& color : colors) {
            combinations.push_back(make_pair(symbol, color));
        }
    }

    separateVectors();

    return 0;
}

Expected Output: The expected output should be four separate vectors, each containing four combinations of symbol and color, satisfying the given conditions. Example:

Vector 0
Symbol: # Color: Y
Symbol: $ Color: R
Symbol: & Color: B
Symbol: % Color: G

Vector 1
Symbol: # Color: R
Symbol: & Color: Y
Symbol: % Color: B
Symbol: $ Color: G

Vector 2
Symbol: # Color: G
Symbol: % Color: Y
Symbol: & Color: R
Symbol: $ Color: B

Vector 3
Symbol: & Color: G
Symbol: # Color: B
Symbol: $ Color: Y
Symbol: % Color: R

Current Output: The current output is not assigning some combinations to any vector, even though it should be possible to assign them. Example:

Warning: Combination ($, Y) couldn't be assigned.
Warning: Combination (&, B) couldn't be assigned.
Vector 0
Symbol: # Color: G
Symbol: $ Color: B
Symbol: % Color: R
Symbol: & Color: Y

Vector 1
Symbol: # Color: B
Symbol: & Color: G
Symbol: % Color: Y
Symbol: $ Color: R

Vector 2
Symbol: % Color: G
Symbol: & Color: R
Symbol: # Color: Y

Vector 3
Symbol: % Color: B
Symbol: $ Color: G
Symbol: # Color: R

Additional Notes:

I have verified the logic for checking validity and assigning combinations to vectors, but the issue still persists. The issue only occurs like 50% of the time, most of the time, the combinations are missing from the vector 2 and 3, rarely from 0 and 1. Sometimes there are up to 5 combinations not assigning but most of the time it's only one or two.

I would greatly appreciate any insights, suggestions, or solutions to resolve this problem. Thank you in advance for your help!




dimanche 11 juin 2023

Unsure why the following C++ code is giving me error C2280

I am learning C++ and trying to get out of tutorial hell, so I wanted to try my hand at a basic BlackJack game. I'm currently running into trouble with my shuffle function and I'm not sure why the code isn't compiling. I keep getting the following error:

"'Deck &Deck::operator =(const Deck &)': attempting to reference a deleted function BlackJack E:\Visual Studio Projects\BlackJack\Deck.cpp 43"

When I comment out the below lines, the program compiles normally. I just don't understand what is happening with the two lines that are making it not compile.

deck.cards.erase(deck.cards.begin() + index);

deck = shuffledDeck;

Here is my Deck.h file:

#ifndef DECK_H
#define DECK_H
#include <vector>
#include "Card.h"
using namespace std;

class Deck : public Card
{
    private:
        // Empty vector of cards to be filled by initializeDeck
        vector<Card> cards;

        // Stores cards after they have been in the Player or Dealer's hand
        vector<Card> spentCards;

    public:
        short int deckSize {52};
        short int numDecks = 1;
        Deck();

        // Takes in a Deck object (which contains a vector of cards) and creates a vector with all the required cards,
        // and creates duplicates if you want more than 1 deck;
        void initializeDeck(Deck& deck, short int numDecks);

        // Creates a new vector and pulls random cards from the original vector until the original vector is empty
        void shuffle(Deck& deck);

        // Prints out the entire vector of cards created, one card at a time. It calls on the printCard() function inside the card class
        void printDeck(const Deck& deck);

};
#endif


Here is the Deck.cpp file:

#include <iostream>
#include <vector>
#include <cstdlib>
#include "Deck.h"
#include "Card.h"
using namespace std;

Deck::Deck()
{
}

void Deck::initializeDeck(Deck& deck, short int numDecks)
{
    for (int i = 0; i < numDecks; i++)
    {
        for (int suit = 0; suit < numSuits; suit++)
        {
            Card card;
            for (int rank = 1; rank <= numRanks; rank++)
            {
                card.setSuit((Suit)suit);
                card.setRank(Rank(rank));
                deck.cards.push_back(card);
            }
        }
    }
}



void Deck::shuffle(Deck& deck)
{
    Deck shuffledDeck;

    srand(time(nullptr));

    while (!deck.cards.empty())
    {
        int index = rand() % deck.cards.size();
        shuffledDeck.cards.push_back(deck.cards[index]);
        deck.cards.erase(deck.cards.begin() + index);
    }
    deck = shuffledDeck;
}

void Deck::printDeck(const Deck& deck)
{
    for (Card card : deck.cards)
    {
        printCard(card);
    }
}

Here is the Card.h file:

#ifndef CARD_H
#define CARD_H
#include <string>
using std::string;

// This is not assigning value, just setting the numerical constants that represent each card
const enum Rank : short int
{
    ACE_LOW = 1,
    TWO = 2,
    THREE = 3,
    FOUR = 4,
    FIVE = 5,
    SIX = 6,
    SEVEN = 7,
    EIGHT = 8,
    NINE = 9,
    TEN = 10,
    JACK = 11,
    QUEEN = 12,
    KING = 13,
    ACE_HIGH = 14
};

// Constant values representing the Suits
const enum Suit : short int
{
    SPADE = 0,
    HEART = 1,
    CLUB = 2,
    DIAMOND = 3
};

class Card
{
    public:

        // Constant values representing the total number of suits and ranks
        const short int numRanks{ 13 };
        const short int numSuits{ 4 };

        // Constructors of cards
        Card();
        Card(Rank rank, Suit suit);
        
        // setters for private data members
        void setRank(Rank rank);
        void setSuit(Suit suit);

        // Getters for private data members
        Rank getRank() const;
        Suit getSuit() const;

        // Printing the member variables of a card object
        void printCard(const Card& card);

        // Retrieving the actual names of the enums instead of their consta
        string whatSuit() const;
        string whatRank() const;

    private:
        Rank rank;
        Suit suit;
};

#endif

Here is Card.cpp

#include "Card.h"
#include <iostream>
using namespace std;


// Initializing an empty card for Rank and Suit to be specified later
Card::Card()
{
    suit = SPADE;
    rank = ACE_LOW;
}

// Constructor for creating a card with the specified Rank and Suit
Card::Card(Rank rank, Suit suit)
{
    this->rank = rank;
    this->suit = suit;
}

// Rank setter
void Card::setRank(Rank rank)
{
    this->rank = rank;
}

// Suit setter
void Card::setSuit(Suit suit)
{
    this->suit = suit;
}

// Rank getter
Rank Card::getRank() const
{
    return rank;
}

// Suit getter
Suit Card::getSuit() const
{
    return suit;
}

string Card::whatSuit() const
{
    switch (suit)
    {
        case 0:
            return "Spades";
            break;
        case 1:
            return "Hearts";
            break;
        case 2:
            return "Clubs";
            break;
        case 3:
            return "Diamonds";
            break;
        default:
            return "Invalid";
            break;
    }
}

string Card::whatRank() const
{
    switch (rank)
    {
        case 1:
            return "Ace Low (1)";
            break;
        case 2:
            return "Two";
            break;
        case 3:
            return "Three";
            break;
        case 4:
            return "Four";
            break;
        case 5:
            return "Five";
            break;
        case 6:
            return "Six";
            break;
        case 7:
            return "Seven";
            break;
        case 8:
            return "Eight";
            break;
        case 9:
            return "Nine";
            break;
        case 10:
            return "Ten";
            break;
        case 11:
            return "Jack";
            break;
        case 12:
            return "Queen";
            break;
        case 13:
            return "King";
            break;
        case 14:
            return "Ace High (11)";
            break;
        default:
            return "Invalid";
            break;
    }
}

void Card::printCard(const Card& card)
{
    cout << card.whatRank() << " of " << card.whatSuit() << endl;
}

I have tried making the function return a Deck object instead of void by using the line "return shuffledDeck". I have also tried to change it so that I am instead setting the "cards" data members of both Deck objects to be equal, with the same problem.

I was expecting the function to grab a random index in the original deck.cards vector, adding that to the shuffledDeck vector, and then delete the card with the generated index from the original vector.

It may be something super simple, but I have been banging my head against a wall for hours. Thanks for your help!




How do I randomize 3 specific colors in a shape (circle) whenever I click the verify button?

I'm 3 months into coding and I'm working on a little and quick game for school while using Javascript. Bare with me If I'm can't grasp anything :(.

Here's the scenario: I have 6 circles, 3 on top (all black), 3 at the bottom (whenever I click each circle, it switches color between yellow, red and blue). To win the game, I have to pick different colors from the bottom circles so it matches the top circles when I click the button "Verify". As I click the button "Verify" the top 3 (black circles) will have to randomize colors between yellow, red and blue. I already figured out how to switch colors with onClick for the bottom circles. I just have no clue have to randomize 3 specific colors (yellow, red and blue) when I click the "Verify" button.

Please help :|.

I tried making an array but I got confused afterwards.




GetRandom avg O(1) (leetcode 381) code showing wrong answer. 28/32 test cases passed [closed]

The question link - https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/

The code has 2 multisets, S1 takes insertion and deletion into account, S2 only takes deletion into account and vector a only takes insertion into account.

In insertion, the element is added into S1 and a. It returns true or false depending if element already present in S1 or not.

In deletion, the element if present in S1, is inserted into S2 and deleted from S1. It returns true or false, depending on whether if already present in S1 or not.

In random function, we get the index of range [0, a.size()-1]. A new multiset s3 is assigned equal to S2. We check if the element is present in s3 and if it is, we delete from there. If it's not and it's not present in s1, we loop again. If it is present in s1, we return the val.

class RandomizedCollection {
public:
    multiset<int> s1, s2; // s2 contains all the deleted elements
    vector<int> a; // a contains all the elements pushed till now
    RandomizedCollection() { // initialization function 
    }
    
    bool insert(int val) {
        if(s1.find(val) == s1.end()) {
            s1.insert(val);
            a.push_back(val);
            return true;
        }
        s1.insert(val);
        a.push_back(val);
        return false;
    }
    
    bool remove(int val) {
        auto it = s1.find(val);
        if(it == s1.end()) {
            return false;
        }
        s1.erase(it);
        s2.insert(val); // adding the deleted value to s2
        return true;
    }
    
    int getRandom() {
        multiset<int> s3 = s2; // assigning s3 to s2
        while(1) {
            int id = rand()%(a.size());
            auto it = s3.find(a[id]);
            if(it!=s3.end()) { // if the random value is present in s3, delete from there
                s3.erase(it);
            } else if(s1.find(a[id])!=s1.end()){ 
                return a[id];
            }
        }
    }
};



vendredi 9 juin 2023

Is there a way to use python 3.9 to emulate default rng from python 2.7?

I have a program which is implemented in Python 2.7 that I want to migrate to Python 3.9.

I want to use regression testing to check if the migration is successful and confirm that the new version is performing the same calculation as the old version.

However...

The program uses random.Random(seed) which the previous developer unwisely decided to seed with floating point numbers.

The code ports to python 3.9 easily but unfortunately it produces different random numbers (apart from instances where the float happens to be an integer). Fiddling around with the generators it looks like this is a consequence of the two versions using a different hash() method. It is not a consequence of changes in float point representation.

Is there a way to generate the same set of random numbers in Python 3.9 that would have been generated by that particular line of code in Python 2.7? i.e. How can I generate the result that legacy code random.Random(1.01) would produce without using a legacy interpreter?




Segment extraction in QGIS for roadkill sampling

I need to conduct a survey along a road network to sample roadkill occurrences. I want to sample 5% of the total road network extent for feasibility reasons. I divided the road network by road type (primary, secondary, tertiary and neighborhood) and road number. Each type is a proxy of traffic flow and represent a different percentage of the total road network. I would like to extract segments of a fixed length at random along each road type. Is there any way to select random segments along a single line vector ?

I tried the basic methods of random extract within subsets but it only extracts features, and I'm struggling to put equidistant points along the lines. I thought by doing so I could then select a random set of segments delimited by said points.




Python Date Generation And Random Date Generation

All though, it may not look like it, they do the exact same thing, and I don't know which one is more reliable (Error handling and simplicity):

    def gen_date(self):
        start_date = simpledialog.askstring("Set Date Range", "Enter start date (MM/DD/YYYY):")
        end_date = simpledialog.askstring("Set Date Range", "Enter end date (MM/DD/YYYY):")
        if start_date and end_date:
            start_date = datetime.strptime(start_date, "%m/%d/%Y")
            end_date = datetime.strptime(end_date, "%m/%d/%Y")
            delta = (end_date - start_date).days
            random_days = random.randint(0, delta)
            random_date = start_date + timedelta(days=random_days)
            random_date = max(random_date, start_date)
            random_date = min(random_date, end_date)

Or

    def date_range(self):
        start = simpledialog.askstring("Set Date Range", "Enter start date (MM/DD/YYYY):")
        if start:
            try:
                start = datetime.strptime(start, "%m/%d/%Y")
                end = simpledialog.askstring("Set Date Range", "Enter end date (MM/DD/YYYY):")
                if end:
                    end = datetime.strptime(end, "%m/%d/%Y")
                    if start > end:
                        raise ValueError("Start date must be earlier than end date")
                    delta = (end - start).days
                    random_days = random.randint(0, delta)
                    gen_date = end - timedelta(days=random_days)
                    self.text.insert("insert", gen_date.strftime("%B %d, %Y"))
                else:
                    messagebox.showerror("Error", "End date is required")
            except ValueError as e:
                messagebox.showerror("Error", str(e))

The first one is shorter, but it looks too good to be true. If they both have good error handling, then it should be the one that is shorter. the first one is 932 characters, the second one is 632. Character amount matters to me, because I want it to be as little characters as possible, taking up less storage, meaning a larger audience can reach it.

I have tried to remove the question from 1, because I know that 2 will definitely NOT work if just remove the question. The error I get is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\[NAME]\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\[NAME]\Downloads\CandelX\CandelX.py", line 203, in gen_date
    start_date = datetime.strptime(start_date, "%m/%d/%Y")
                                   ^^^^^^^^^^
UnboundLocalError: cannot access local variable 'start_date' where it is not associated with a value

I have tried AI, which it didn't understand what I was asking.




jeudi 8 juin 2023

How to create a random name picker wheel app

I have a random name picker which I’ve made in PowerPoint however I’d like to do this in an app with xCode but I’m not sure how to get the random wheel like it is in this PowerPoint file. I need it to have a list where the user can enter player names with say a maximum of 100 entries and once the names are entered then go to the wheel and have a button to spin through the names like in this PowerPoint file and randomly select a name from the list of names entered and display it then once this is done show a button to remove that chosen name from the list or just leave it there and prevent the app from selecting the same name again until the app is reset. Any help here would be hugely appreciated. Thanks.

https://1drv.ms/p/s!AqV2LEz7-FE63zyRC3chH7PYpPKK?e=g9WF8f

I have tried searching for solutions online but unsure where to start with this one.




What does "nextcord.errors.ApplicationInvokeError: Command raised an exception:TypeError:object of type 'SlashApplicationCommand' has no len()" means?

I'm using random library to choose the link randomly in my command. It worked perfectly, but then I wasn't able to use it anymore. Here is my code:

import nextcord
import random
from nextcord.ext import commands
from nextcord import Interaction, SlashOption, ChannelType
from nextcord.abc import GuildChannel
from nextcord.ext import commands

intents = nextcord.Intents.default()
intents.message_content = True 
client=commands.Bot(command_prefix='!')
serverID= 1115682153087385691

rep=['Meow!', ':3', 'Nyaa~', 'UwU', 'OwO', 'ヾ(•ω•`)o', ':cat2:', 'ヾ(≧▽≦*)o', '(p≧w≦q)']
image=['link 1', 'link2', 'link3', 'link4']

@client.slash_command(name = 'ping', description="Replies with pong!", guild_ids=[serverID])
async def ping(interaction: nextcord.Interaction):
    await interaction.response.send_message("Pong!")

@client.slash_command(name = 'meow', description="Meow!", guild_ids=[serverID])
async def ping(interaction: nextcord.Interaction):
    await interaction.response.send_message('{}'.format(random.choice(rep)))

@client.slash_command(name = 'image', description="Random image.", guild_ids=[serverID])
async def image(interaction: nextcord.Interaction):
    image_embed=nextcord.Embed(title="Meow!", description="ヾ(≧▽≦*)o", color=0xff9eb1)
    image_embed.set_image('{}'.format(random.choice(image)))
    await interaction.response.send_message(embed=image_embed)

@client.slash_command(name = 'about', description="About this bot", guild_ids=[serverID])
async def about(interaction: nextcord.Interaction):
    about_embed=nextcord.Embed(title="Meow!", description="ヾ(≧▽≦*)o", color=0xff9eb1)
    about_embed.set_author(name="Owner: Minh#6284")
    about_embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/1116376164433395742/1116376184368930948/48dbf3be4ac93bcf67243f3fcbfc50a4.png")
    about_embed.add_field(name="About this bot:", value="A fun bot for everyone, with some mini games and cute cats images (catgirls too)!", inline=False)
    about_embed.add_field(name="Support server:", value="https://discord.gg/cAS6E4NhZD", inline=False)
    about_embed.set_footer(text="UwU")
    await interaction.response.send_message(embed=about_embed)

@client.slash_command(name = 'suggest', description="Suggest us!", guild_ids=[serverID])
async def suggest(interaction: nextcord.Interaction, your_idea:str):
    await interaction.response.send_message('Thanks for your ideas!', ephemeral=True)
    print(your_idea)

And this is the Error message:

Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x000001E4CD1CC910>:
Traceback (most recent call last):
  File "C:\Users\Minh\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\application_command.py", line 890, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Users\Minh\Desktop\Miko\main.py", line 28, in image
    image_embed.set_image('{}'.format(random.choice(image)))
                                      ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Minh\AppData\Local\Programs\Python\Python311\Lib\random.py", line 372, in choice
    if not len(seq):
           ^^^^^^^^
TypeError: object of type 'SlashApplicationCommand' has no len()

The above exception was the direct cause of the following exception:

nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: object of type 'SlashApplicationCommand' has no len()

How can I fix it? Is it a problem from random library? I tried to rewrite it using the older code which worked perfectly, but it still had the same error messages.




Issues with randomly generating instance of object in 2d array [duplicate]

I have a 2d array and I want to randomly generate one of two objects in each spot arr[r][c]. However when I tried my code, instead of generating a random object at the spot, it generates the same object for all indexes on the same column.

This is my current code:

    def generateBoard(self, r, c):
        for row in range(len(self.board)):
            for col in range(len(self.board[row])):
                if ((r - 2 < row < r + 2) and (c - 2 < col < c + 2)):
                    self.board[row][col] = obj1()
                else:
                    rand = random.randint(0, 1)
                    if (rand == 1):
                        self.board[row][col] = obj2()
                    else:
                        self.board[row][col] = obj1()

So for example, if row = 1, col = 2, and rand = 1, my method would not only generate an instance of obj2 at board[1][2], but also do so for [2][2], [3][2], [4][2]....... and I'm not sure why. Does anyone know what I'm doing wrong or if there is a better way to do what I want to do?




Most efficient way to select samples from pandas dataframe

I have a simple dataframe shape: (10000,8). (you may take this for test)

I need to extract 100 sample without replacement in each itteration of loop (think 100K itterations)

The first approach that comes to mind is using DataFrame.sample() but after some test it seems the process time is high


import timeit

print(timeit.timeit('df_sample = df.sample(100, replace=False)', 
                    setup="import pandas; df = pandas.read_csv('Free_Test_Data_500KB_CSV-1.csv')",
                    number=100_000))


print(timeit.timeit('df_sample = df.iloc[random.sample(range(len(df)),100)]', 
                    setup="import pandas; import random; df = pandas.read_csv('Free_Test_Data_500KB_CSV-1.csv')",
                    number=100_000))

and this is the reult:

25.144644900006824
8.81066109999665

If I set "replace=True" the process time would be close to the second snippet, but this is not what I want. (I tested and think random.sample would return sampling without replacement)

Is there any better/more efficient approach for small number of samples?

P.S. I also noticed that if I increase the number of samples from 100 to 1000, the result would be totally different, but my usecase is for small number of samples

28.4684341000102
37.28109739998763



mercredi 7 juin 2023

Problem with brownian motion simulation in Python

I'm trying to make a simple animation of brownian motion for some particles on a box, and although I think I'm not far away from achieving it, I keep getting the same error: 'FuncAnimation' object has no attribute '_resize_id'. I don't know if I'm doing something wrong with the dimensions or if it's something form the animation function.

# Set random seed for reproducibility
np.random.seed(0)

num_particles = 80
box_size = 10
total_steps = 200

# Initialize particle positions and velocities
positionX = np.random.uniform(low=1, high=box_size-1, size=(num_particles, 1))
positionY = np.random.uniform(low=1, high=box_size-1, size=(num_particles, 1))

# Initialize figure and axis
fig, ax = plt.subplots()
ax.set_xlim(0, box_size)
ax.set_ylim(0, box_size)


# Initialize particles as scatter plot objects
particles = ax.scatter(positionX[:,0], positionY[:,0])

def update(frame, positionX,positionY):
    # Random displacements for particles
    displacementX =  np.random.normal(loc=0, scale=0.1, size=(num_particles, 1))
    displacementY =  np.random.normal(loc=0, scale=0.1, size=(num_particles, 1))
    
    # Update particle positions
    positionX += displacementX
    positionY += displacementY
    
    # Ensure particles stay within the box
    positionX = np.clip(positionX, 0, box_size)
    positionY = np.clip(positionY, 0, box_size)

    
    # Update scatter plot
    particles.set_offsets(positionX,positionY)
    
    return particles,

# Animation
ani = animation.FuncAnimation(fig, update, frames=total_steps, fargs=(positionX,positionY), interval=100, blit=True)

ani.save("brownian_mot.gif", writer="pillow")

plt.show()

I've tried to change the way I define the positions but I keep doing it wrong.




Difference between random, cycle graph, bipartite, lattice, real netwrok, configuration model

What is the difference between random, cycle graph, bipartite, lattice, real netwrok, configuration model

Random Graph: A random graph is a type of mathematical object known as a graph, which is composed of vertices (or nodes) and edges (lines connecting the vertices). In a random graph, the presence of an edge between any two nodes is determined randomly. The most common type of random graph is the Erdős–Rényi model. In an Erdős–Rényi graph, each edge has a fixed probability of being present or absent, independently of the other edges. Cycle Graph: A cycle graph is a graph that consists of a single cycle - a path of edges and vertices wherein a vertex is reachable from itself. So, all the vertices and edges form a closed loop with no loose ends. An example of a cycle graph would be a circular graph where each node is connected to two other nodes, forming a ring-like structure. Bipartite Graph: A bipartite graph is a type of graph that has its vertices divided into two disjoint sets. All edges in the graph connect a vertex from the first set to a vertex in the second set. In other words, no edge within the same set of vertices exists. An example would be a graph representing people and their hobbies, where an edge connects a person to a hobby they enjoy, but people don't directly connect to other people, and hobbies don't connect to other hobbies. Lattice Graph: A lattice graph is a graph that can be drawn in the Euclidean space such that all its vertices are in a regular grid. The most common examples of lattice graphs are the square grid graph and the triangular grid graph. Real Network: Real networks, or real-world networks, refer to graphs that represent actual systems in our world. These could be the internet (nodes as webpages, edges as links), social networks (nodes as people, edges as friendships), transportation networks (nodes as locations, edges as roads), and more. These networks often exhibit complex and interesting properties that aren't necessarily seen in simpler types of graphs. For example, they may exhibit "small-world" properties (most nodes can be reached from others in a small number of steps), or they may have a "scale-free" degree distribution (most nodes have few connections, but a few nodes have many connections). Configuration Model: The configuration model is a method of generating random graphs with a specified degree sequence. In other words, you can specify how many edges you want each node in your graph to have, and the configuration model will generate a random graph with that property. Note that this model doesn't necessarily generate simple graphs; it can sometimes produce graphs with multiple edges between the same pair of nodes, or nodes with an edge to themselves.




mardi 6 juin 2023

Cannot get random color generator in Kotlin to work

Trying to generate a random color hexadecimal...Here's my code so far

import android.graphics.Color
import kotlin.random.Random
import kotlin.random.nextInt

fun main(){
    val rnd = Random.Default //kotlin.random
    val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
    }

This is the error I'm getting

Exception in thread "main" java.lang.RuntimeException: Stub!
    at android.graphics.Color.argb(Color.java:137)
    at com.example.functionexample.FunctionExampleKt.main(FunctionExample.kt:12)
    at com.example.functionexample.FunctionExampleKt.main(FunctionExample.kt)

Process finished with exit code 1

Tried searching for this error online but can't find anything. Theres no error messages on my actual code but when I run it I get that




Randomize An array based on a Given seed [duplicate]

Given a array A and a seed S(number), how do I make an algorithm to randomize the array A with the seed S? (Array A is fixed but then it should rearrange the elements of A based on the seed)
Initial Attempt:

function shuffleArrayWithSeed(array, seed) {
  var getRandom = Math.floor(Math.sin(seed++) * 100)
  for (var i = 0;i<array.length;i++){
    function lowerqw(i,getRandom){
      if (Math.floor(getRandom * i)>=array.length){
        return lowerqw(i,getRandom/2);
      }else{
        return Math.floor(getRandom * i)
      }
      }
    var temporaryValue, randomIndex;
    randomIndex = lowerqw(i,getRandom);
    // Swap current element with a randomly selected element
    temporaryValue = array[i];
    array[i] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  console.log(array)
  return array;
}

But this doesn't randomize the array at all. Could you please find any flaws? Or come with a better algorithm, which is not that time consuming as size of array A increases? Note: This Question doesn't help me as the answers here, deal with those randomizing the array at complete random.




PowerPoint random name picker with imported list of names

I have made a random name picker which I have currently just added a text box in each of 20 slides and put the macros code to randomize once cursor is hovered over a box which works fine however I'd like to have a list of names that I can just type into and edit and have each text box in each slide read from that list rather than manually editing each text box each time its used. Is this possible? Thanks.

I have tried searching online for this but found things different to what I'm looking for.




Different random strings of numbers for text fields in Robot Framework using a variable

I'm testing a web application using Robot Framework/Selenium. I need to input numerical values to several text fields on a page, and I'm wondering if there's a way I can use a variable to get different random values for each of the fields.

I'm already using this keyword as suite setup:

    Random Values
        ${RANDOM_VALUE} =    Generate Random String    3    [NUMBERS]100-200
        Set Global Variable    ${RANDOM_VALUE}

And then these in the test case:

    Input Text    ${TEXT_FIELD_1}    ${RANDOM_VALUE}
    Input Text    ${TEXT_FIELD_2}    ${RANDOM_VALUE}
    Input Text    ${TEXT_FIELD_3}    ${RANDOM_VALUE}

and it works, but it gives me the same string for each text field I call the ${RANDOM_VALUE} variable to. Is there some way to generate a different random string for every text field on the page by using the same variable for all of them?

I'm still a total newbie in the world of automated testing, and I'm not at all well-versed in Python... I have a feeling that the solution involves using Python in some way, but I have no idea how to actually do that. I've tried searching for the answer or tutorials or something to help me, but I haven't been able to figure it out. Maybe the answer is just so simple that nobody else is having the same problem?

Thank you!




Python sketch to sketch microstructure

Microstructure image

Hi guys, I have to use Python code to generate a random sketch like the picture attached. The objects inside represent particles in a rectangular matrix. Does anyone have any ideas on how such a sketch can be generated? I haven't started working, but looking for ideas.




lundi 5 juin 2023

Using random.choice in a loop

I'm new to learning Python, currently learning Modules. I'm stuck on this:

  1. Randomly choose an element until you choose "yellow", incrementing flips each time
  2. Print a message each time including how many flips have been executed and what the result was
import random 

flips = 0
sides = ["blue", "blue", "blue", "blue", "yellow", "blue"]

side = random.choice(sides) 

for side in sides:
    if side == "blue":
        print("you flipped a blue")
        flips += 1
    elif side =="yellow":
        print("you flipped a yellow!")
        flips += 1
        break

the output i got for this was:

you flipped a blue
you flipped a blue
you flipped a blue
you flipped a blue
you flipped a yellow!
5

I can see here that it's just iterating through my sides list till it gets to "yellow". How do I fix this to actually be random??




dimanche 4 juin 2023

Mean, variance of normal distribution for each seed in Python

I am using numpy.random.seed() to get different normal distribution. But I want to have the mean,var to remain constant for each seed. How can I achieve this? I present the current and expected output.

from scipy.stats import truncnorm
import numpy as np
import os
import csv 
import pandas as pd
import random
import matplotlib.pyplot as plt

for i in range(0,2): 
    
    np.random.seed(i)
    mu, sigma = 49.925, 0.996 # mean and standard deviation
    Nodes=220
    r = (1e-6)*np.random.normal(mu, sigma, Nodes)

    sort_r = np.sort(r)
    r1=sort_r[::-1]
    r1=r1.reshape(1,Nodes)
    r2 = r.copy()
    np.random.shuffle(r2.ravel()[1:])
    r2=r2.reshape(1,Nodes)
    maximum = r2.max()
    indice1 = np.where(r2 == maximum)

    r2[indice1] = r2[0][0]
    r2[0][0] = maximum

    r2[0][Nodes-1] = maximum 

    mean=np.mean(r)
    print("Mean =",mean*1e6)
    var=np.var(r)
    print("var =",var*1e12)

    r=pd.Series(r*1e6)
    r.hist()
    plt.xlabel("Pore throat size [\u03BCm]",size=15)
    plt.ylabel("Count",size=15)
    plt.title(rf"var={round(var*1e12,1)}",size=25)
    plt.savefig(rf"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\220 nodes_1\var_1\Histogram_0.png")

The current output is

Mean = 49.99989488440971
var = 1.0009790234390512
Mean = 50.00911322245587
var = 0.8709906144821978

The expected output is

Mean = 50.000
var = 1.000
Mean = 50.000
var = 1.000



Rust deterministic, uniform distribution

I am looking at the rand crate and I am not sure how to sample from a distribution such that the resulting samples are uniform and deterministic.

Deterministic means that you get the same numbers on 2 distinct program invocations.

The main issue I am facing is that rand by default is not deterministic. Id does have rand_pcg for determinism, but then I don;t know how to make the distribution uniform.




Why is my code exiting as soon as I start it?

I have a pygame project where I need to display a button according to a randomly generated sequence. It is currently just exiting as soon as I start it

import pygame
import os
import random

# Initialize pygame starts 
pygame.init()

# Set the dimensions of the screen
screen_width = 1275
screen_height = 750


# Set the colors
white = (255, 255, 255)
black = (0, 0, 0)

# Set the font
font = pygame.font.SysFont('Arial', 20)

# Set the button properties
button_radius = 70
button_x_spacing = 400
button_y_spacing = 200

# Set the flower image
flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", "flower.jpg"))
flower_rect = flower_image.get_rect()
flower_rect.center = (screen_width//2, screen_height//2)

# Set the button positions
button_positions = [
    (button_x_spacing, button_y_spacing),
    (button_x_spacing, button_y_spacing + 200),
    (button_x_spacing, button_y_spacing + 400)
]

# Initialize the screen
screen = pygame.display.set_mode((screen_width, screen_height))

# Set the caption
pygame.display.set_caption("Marmoset Buttons")

# Set the clock
clock = pygame.time.Clock()

# Set the loop variable
running = True

# Set the timer
timer = 0

# Draw the buttons on the screen
#def draw_buttons():
    #for i, pos in enumerate(button_positions):
    #for i in sequence:
        #pygame.draw.circle(screen, white, button_positions[i], button_radius)
        #text_surface = font.render(f"Button {i}", True, black)
        #text_rect = text_surface.get_rect(center=button_positions[i])
        #screen.blit(text_surface, text_rect)

# Generating sequence of numbers
sequence = []
for i in range(0,10):
    n = random.randint(0,2)
    sequence.append(n)

# Main game loop
#while running:
    # Set the frame rate
    #clock.tick(60)

    for i in sequence:
    # Check for events
        screen.fill(black)
        pygame.draw.circle(screen, white, button_positions[i], button_radius)
        text_surface = font.render(f"Button {i}", True, black)
        text_rect = text_surface.get_rect(center=button_positions[i])
        screen.blit(text_surface, text_rect)
        pygame.display.update()

        for event in pygame.event.get():
            #if event.type == pygame.QUIT:
                #running = 1
            if event.type == pygame.MOUSEBUTTONDOWN:
                distance_button = pygame.math.Vector2(button_positions[i]) - pygame.math.Vector2(pygame.mouse.get_pos())
                flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", f"flower{i}.jpg"))
                #distance_button2 = pygame.math.Vector2(button_positions[1]) - pygame.math.Vector2(pygame.mouse.get_pos())
                #distance_button3 = pygame.math.Vector2(button_positions[2]) - pygame.math.Vector2(pygame.mouse.get_pos())
                if distance_button.length() < button_radius:
                    screen.blit(flower_image, flower_rect)
                    #timer = pygame.time.get_ticks()
                    #flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", "flower.jpg"))
                #elif distance_button2.length() < button_radius:
                    #timer = pygame.time.get_ticks()
                    #flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", "flower1.jpg"))
                #elif distance_button3.length() < button_radius:
                    #timer = pygame.time.get_ticks()
                    #flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", "flower2.jpg"))
                #else:
                    #timer = pygame.time.get_ticks()
                    #flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", "flower3.jpg"))
    


                
   
    # Fill the screen with black
    #screen.fill(black)
   
    # Draw the buttons on the screen
    #draw_buttons()
   
    # Check the timer
    #if timer != 0:
        #current_time = pygame.time.get_ticks()
        #if current_time - timer < 3000:
            #screen.blit(flower_image, flower_rect)
        #else:
            #timer = 0
   
    # Update the screen
    #pygame.display.update()

# Quit pygame
#pygame.quit()

I tried commenting some previous unnecessary code I had but nothing is changing. I had it working before where I displayed all 3 buttons at once but when I tried changing it to randomly show one it didn't work.




Why am I running into stack overflows when calling the shuffle method on large usize arrays within structs in Rust?

I'm new to Rust and i've ran into a problem using the shuffle() method on a usize array like so:

self.rand_list.shuffle(&mut rand::thread_rng());

Using the method sometimes results in a stack overflow (but not always) when the array gets too big (i've started noticing the problem for sizes close to 20 000 elements).

Since i'm not yet very familiar with the language i'm having a hard time reading through the documentation to understand why this is happening and why the amount of items pushed on the stack varries between executions. Note that I cannot replicate this error when the array is not part of a struct.

The point of rand_list is to contain a list of indexes that my code is meant to modifiy, one at a time. the struct containing rand_list also possesses a field used as a counter that is incremented each time I read an index from rand_list.

I was initially generating random indexes one at a time with a thread_rng() and was met with the same problem. So i tried to switch to this solution instead.

The struct used here uses 3 other arrays of similar size, so even combined they should be about 10 times smaller than the default stack size on windows which i've come to understand is around 1Mb long. So i don't believe the issue lies here.




samedi 3 juin 2023

Why does my code keep exiting before it has the chance to display?

I have python code that keeps exiting for no reason. Im trying to get the for loop to keep running for the length of the sequence but it just exists as soon as it opens

I tried removing the quit part but that didn't do much. Im trying to have to code display a button that is randomly generated (0,1,2) and then recognize if it is pressed. Once it's pressed it goes trough again and displays another button.




How can I improve my Python code for getting the least likely positions in a 5x5 array using probability weights?

I'm working on code that deals with probabilities. The error occurs on line 95. Here is the code in python

import numpy as np
from collections import Counter
from sklearn.linear_model import LogisticRegression

# Criar matriz 5x5
matriz = np.zeros((5, 5))

# Adicionar o histórico das últimas 10 jogadas
historico = [(1, 4, 4, 3), (0, 3, 1, 3), (3, 0, 4, 4), (2, 0, 2, 3), (0, 1, 3, 0), (3, 3, 4, 2), (0, 1, 2, 0), (3, 3, 2, 2), (3, 1, 4, 3)]

# Excluir a primeira posição se o histórico tiver mais de 10 jogadas
if len(historico) > 10:
    historico = historico[1:]

for jogada in historico:
    x, y, x2, y2 = jogada
    if x >= 1 and x <= 5 and y >= 1 and y <= 5:
        matriz[x - 1, y - 1] = 1

# Definir parâmetros
prob_min = 0.04  # Probabilidade mínima de 4.0%
prob_max = 0.056  # Probabilidade máxima de 5.6%
num_options = 10
max_excluded_positions = 8
min_adjacent_bombs = 2

# Criar matriz de probabilidades
probabilidades = np.zeros((5, 5))

# Contar a repetição das posições e das somas das posições
posicoes_repetidas = Counter(historico)
somas_repetidas = Counter([sum(posicao) for posicao in historico])

# Atualizar as probabilidades com base no histórico e nas repetições
for linha in range(5):
    for coluna in range(5):
        posicao = (linha+1, coluna+1)
        soma = linha+1 + coluna+1

        # Atribuir peso proporcional à repetição da posição e das somas
        peso_posicao = posicoes_repetidas[posicao]  # Peso proporcional à repetição da posição
        peso_soma = somas_repetidas[soma]  # Peso proporcional à repetição da soma da posição

        # Verificar se a posição ocorreu mais de duas vezes no espaço amostral de dez jogadas
        if posicoes_repetidas[posicao] > 2:
            peso_posicao = 0  # Zerar o peso da repetição para evitar que ocorra mais de duas vezes

        # Atribuir probabilidade com base nos pesos e nas condições
        if matriz[linha, coluna] == 1:
            probabilidade = prob_max  # Probabilidade alta para posições que já tiveram bombas
        elif linha >= 1 and linha <= 3 and coluna >= 1 and coluna <= 3 and np.sum(matriz[linha-1:linha+2, coluna-1:coluna+2]) > 0:
            probabilidade = prob_max  # Probabilidade alta para posições adjacentes a posições que já tiveram bombas
        elif linha % 2 == 0 and coluna % 2 == 0:
            probabilidade = prob_max - peso_posicao * prob_min - peso_soma * prob_min  # Probabilidade média para posições pares
        else:
            probabilidade = prob_max - peso_posicao * prob_min + peso_soma * prob_min  # Probabilidade média para posições ímpares

        probabilidades[linha, coluna] = probabilidade

# Obter as coordenadas das posições disponíveis
posicoes_disponiveis = np.argwhere(matriz == 0)

# Verificar se há jogadas disponíveis suficientes
num_posicoes_disponiveis = len(posicoes_disponiveis)

if num_posicoes_disponiveis < num_options:
    print("Não há jogadas disponíveis suficientes de acordo com as restrições atuais.")
else:
    # Criar rótulos para as classes
    rótulos = np.zeros(num_posicoes_disponiveis)
    rótulos_adjacentes = np.ones(num_posicoes_disponiveis)

    # Ajustar o modelo de regressão logística para classificação
    regression = LogisticRegression(solver='liblinear', random_state=42, multi_class='auto')

    # Juntar as posições e rótulos
    dados = np.concatenate((posicoes_disponiveis, posicoes_disponiveis))
    rótulos_completos = np.concatenate((rótulos, rótulos_adjacentes))

    regression.fit(dados, rótulos_completos)  # Ajustar o modelo com os dados completos

    # Prever as probabilidades para todas as posições disponíveis
    probabilidades_previstas = regression.predict_proba(posicoes_disponiveis)[:, 1]

    # Ordenar as jogadas disponíveis com base nas probabilidades previstas
    jogadas_ordenadas = [(*coordenada, prob) for prob, coordenada in sorted(zip(probabilidades_previstas, posicoes_disponiveis), key=lambda x: x[0])]

    # Substituir a lista de jogadas adversárias pelo histórico
jogadas_adversario = historico

# Ajustar as probabilidades com base nas jogadas adversárias
for jogada_adv in jogadas_adversario:
    x_adv, y_adv, _, _ = jogada_adv
    for i in range(len(jogadas_ordenadas)):
        x1, y1, _, _ = jogadas_ordenadas[i]
        distancia = np.linalg.norm(np.array([x_adv, y_adv]) - np.array([x1, y1]))
        if distancia <= min_adjacent_bombs:
            x2, y2, prob = jogadas_ordenadas[i]
            jogadas_ordenadas[i] = (x1, y1, x2, y2, prob_min * (min_adjacent_bombs + 1 - distancia))



# Selecionar as próximas jogadas com menor probabilidade de haver bombas
coordenadas_jogadas = [(x1 + 1, y1 + 1, x2 + 1, y2 + 1) for (x1, y1, x2, y2, _) in jogadas_ordenadas[:num_options]]

# Imprimir a matriz
print("Matriz:")
print(matriz)

# Imprimir as próximas jogadas
print("Próximas jogadas com menor probabilidade de haver bombas:")
print(coordenadas_jogadas)


ValueError                                Traceback (most recent call last)
<ipython-input-40-38fbf6639a05> in <cell line: 92>()
     93     x_adv, y_adv, _, _ = jogada_adv
     94     for i in range(len(jogadas_ordenadas)):
---> 95         x1, y1, _, _ = jogadas_ordenadas[i]
     96         distancia = np.linalg.norm(np.array([x_adv, y_adv]) - np.array([x1, y1]))
     97         if distancia <= min_adjacent_bombs:

ValueError: not enough values to unpack (expected 4, got 3) 

The error is that the values ​​that the code returns are different from those that were placed. I need the code to return a list with 10 coordinates in the format (x1,y2,x2,y2) where the lowest probabilities of having been chosen by the computer are shown