I need to run a drawing which I would like to seed with (say) 32 bits of public (pseudo)randomness. Ideally the random seed is drawn at about midnight ET daily and is simple to find (e.g. a trusted third-party site posts a random immutable 32-bit number every day). I know that random.org has third-party drawing functionality, but ideally there is a free alternative. Are there any services that provide this? Thanks in advance.
mercredi 31 août 2022
adding more then one string of games [duplicate]
I want to add a list of strings into a randomizer be need help putting them into on variable
Here is the code
import java.util.Random;
public class pickgame {
public static void main(String[] args){
//The random games
string GenshinImpact;
string CodeVain;
string ScarletNexus;
string TalesOfArise;
string GodEater3;
string NeoTheWorldEndsWithYou;
string FinalFantasy15;
string FinalFantasy7;
string DevilMayCry;
String game =
Random random = new Random(); //make a random
System.out.println(game);
}
}
mardi 30 août 2022
Can't figure out program for dice rolls, rerolls, and printing number of successes
Fairly new to coding. Trying to program a way to roll bulk dice, reroll certain numbers once, and then print how many dice were equal to or above the value needed. I can't find any examples to work off of or understand if I'm on the right track. Any assistance is appreciated. Thank you!
import random
while True:
user_amount = int(input("Roll how many dice?: "))
user_reroll = int(input("Reroll what numbers? (Put 0 for no reroll): "))
user_value = int(input("Keep what value and above?: "))`
dice = random.randint(1,6) #dice
roll = (dice, range(user_amount))
for dice in roll:
if user_reroll == 0:
break
else:
if user_reroll == dice:
dice
break
for dice in roll:
if dice >= user_value:
success = str(roll)
print(len(success))
while True:
answer = str(input('Roll again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("The Emperor protects")
break
Run a function at a random time in Python
I want to be able to be able to run a function at a random time as long as the program is running.
Let's say I have this function:
def sample_func:
print("Function is running.")
and some other code running. As long as the program is being run, I want this function to run at a random amount of time between 5 to 10 minutes while other code is being run. Is this possible?
How to generate random numbers between 0 and 0.01 in python?
I want to generate a set of 300 random numbers between 0 and 0.01 , the random numbers should includes 0 and 0.01 as well
I can't find the issue in my simple password generater, written in c#
So i just wrote the code for the c# random password generator, tried to compile but it didn't work in the end. I just started as I would do it normal, but after a while many issues showed up that i didn't understand. I already did another password genrater, but in javascript. I started c# a year ago or smth, i'm not that good. I really can't find the issue i made. Maybe somebody else could help me and correct it. Thank you. Here's the code:
namespace WorkingCode.CodeProject.PwdGen
{
using System;
using System.Security.Cryptography;
using System.Text;
public class PasswordGenerator
{
public PasswordGenerator()
{
this.Minimum = DefaultMinimum;
this.Maximum = DefaultMaximum;
this.ConsecutiveCharacters = false;
this.RepeatCharacters = true;
this.ExcludeSymbols = false;
this.Exclusions = null;
rng = new RNGCryptoServiceProvider();
}
protected int GetCryptographicRandomNumber(int lBound, int uBound)
{
// Assumes lBound >= 0 && lBound < uBound
// returns an int >= lBound and < uBound
uint urndnum;
byte[] rndnum = new Byte[4];
if (lBound == uBound-1)
{
// test for degenerate case where only lBound can be returned
return lBound;
}
uint xcludeRndBase = (uint.MaxValue -
(uint.MaxValue%(uint)(uBound-lBound)));
do
{
rng.GetBytes(rndnum);
urndnum = System.BitConverter.ToUInt32(rndnum,0);
} while (urndnum >= xcludeRndBase);
return (int)(urndnum % (uBound-lBound)) + lBound;
}
protected char GetRandomCharacter()
{
int upperBound = pwdCharArray.GetUpperBound(0);
if ( true == this.ExcludeSymbols )
{
upperBound = PasswordGenerator.UBoundDigit;
}
int randomCharPosition = GetCryptographicRandomNumber(
pwdCharArray.GetLowerBound(0), upperBound);
char randomChar = pwdCharArray[randomCharPosition];
return randomChar;
}
public string Generate()
{
// Pick random length between minimum and maximum
int pwdLength = GetCryptographicRandomNumber(this.Minimum,
this.Maximum);
StringBuilder pwdBuffer = new StringBuilder();
pwdBuffer.Capacity = this.Maximum;
// Generate random characters
char lastCharacter, nextCharacter;
// Initial dummy character flag
lastCharacter = nextCharacter = '\n';
for ( int i = 0; i < pwdLength; i++ )
{
nextCharacter = GetRandomCharacter();
if ( false == this.ConsecutiveCharacters )
{
while ( lastCharacter == nextCharacter )
{
nextCharacter = GetRandomCharacter();
}
}
if ( false == this.RepeatCharacters )
{
string temp = pwdBuffer.ToString();
int duplicateIndex = temp.IndexOf(nextCharacter);
while ( -1 != duplicateIndex )
{
nextCharacter = GetRandomCharacter();
duplicateIndex = temp.IndexOf(nextCharacter);
}
}
if ( ( null != this.Exclusions ) )
{
while ( -1 != this.Exclusions.IndexOf(nextCharacter) )
{
nextCharacter = GetRandomCharacter();
}
}
pwdBuffer.Append(nextCharacter);
lastCharacter = nextCharacter;
}
if ( null != pwdBuffer )
{
return pwdBuffer.ToString();
}
else
{
return String.Empty;
}
}
public string Exclusions
{
get { return this.exclusionSet; }
set { this.exclusionSet = value; }
}
public int Minimum
{
get { return this.minSize; }
set
{
this.minSize = value;
if ( PasswordGenerator.DefaultMinimum > this.minSize )
{
this.minSize = PasswordGenerator.DefaultMinimum;
}
}
}
public int Maximum
{
get { return this.maxSize; }
set
{
this.maxSize = value;
if ( this.minSize >= this.maxSize )
{
this.maxSize = PasswordGenerator.DefaultMaximum;
}
}
}
public bool ExcludeSymbols
{
get { return this.hasSymbols; }
set { this.hasSymbols = value;}
}
public bool RepeatCharacters
{
get { return this.hasRepeating; }
set { this.hasRepeating = value;}
}
public bool ConsecutiveCharacters
{
get { return this.hasConsecutive; }
set { this.hasConsecutive = value;}
}
private const int DefaultMinimum = 6;
private const int DefaultMaximum = 10;
private const int UBoundDigit = 61;
private RNGCryptoServiceProvider rng;
private int minSize;
private int maxSize;
private bool hasRepeating;
private bool hasConsecutive;
private bool hasSymbols;
private string exclusionSet;
private char[] pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFG" +
"HIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<" +
".>/?".ToCharArray();
}
}
How to mix a list of strings randomly and add it to a text file without duplicates?
I know this question might be already here on the site but all of them are not what I need. I have a list of strings in python like this
my_list = ["word1", "word2", "word3"]
now I want these words to be randomly mixed in a text file like this
word1word3word2
word2word3word1
word2word1word3
without any spaces and also using all the possible combinations and without any duplicates. Is this possible in python or not, if yes, then how ?
dimanche 28 août 2022
Do popular compressors skip attempting to compress random data?
Do popular compressors such as gzip, 7z, or others using deflate, detect random data strings and skip attempting to compress said strings for sake of speed?
If so, can I switch off this setting?
Otherwise, how can I implement deflate to attempt to compress a random data string?
samedi 27 août 2022
Exclude value out of Rand gen_range
I would like to have a random number between -max
and max
where max is some i32
value, but I would like to exclude zero. I am using rand
version 0.8.5
.
I would like to have a code something like
let mut rng = rand::thread_rng();
rng.gen_range(-max..max);
But this code has zero included. Is there an idiomatic way to exclude it?
Random string generator without repeating a combination
I have tried to implement that the combinations are not repeated. in the image you can see how "sd" is repeated twice.
const characters ='qwertyuiopasdfghjklzxcvbnm0987654321';
function generateString(length) {
let result = ' ';
const charactersLength = characters.length;
for ( let i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function captura(){
lon=2;
can=600;
for (let i = 0; i < can; i++) {
document.write(i+1 + ".- " + generateString(lon) + "<br>");
}
}
captura();
Any help please?
Randomize Elements Positions Defined between "<" and ">" Symbols Using Regular Expressions
I am trying to randomize elements positions that are defined between "<" and ">" brackets, eg. from this
<id:1 s= red>
<id:2 s= blue>
<id:3 s= green>
to this
<id:3 s= green>
<id:1 s= red>
<id:2 s= blue>
I put them in a list but can't match back the randomized list with the regex results. Here is what I got so far:
import re
from random import shuffle
a = open('data.txt', 'r')
s= a.read()
x = re.findall(r'\<([^>]+)', s)
shuffle(x)
f = re.sub(r'\<([^>]+)', x[0], s)
print(f)
Getting a random array position in batari basic (atari 2600)
I need to random a new specific position for the player each N cycles of game loop. So my idea was use a ROM array (data) and a rand function using (&) operator for fast processing following the random terrain documentation : https://www.randomterrain.com/atari-2600-memories-batari-basic-commands.html#rand
However it doesn't work. It is like the response is the same array position always and it returns strange positions randomly haha.. It is more random than I want lol.
I'm using Standard Kernel, with these options below and basic logic for this example :
;***************************************************************
;
; Initializes the batari Basic compiler directives.
set kernel_options pfcolors player1colors no_blank_lines
set tv ntsc
set romsize 32k
set optimization speed
set smartbranching on
set optimization noinlinedata
set optimization inlinerand
;***************************************************************
;
; Debug. The rem below is removed when I want to check to see
; if I'm going over cycle count during tests.
;
; set debug
;***************************************************************
;
; Variable aliases go here (DIMs).
;```````````````````````````````````````````````````````````````
; _Animation_Frame.
;
dim _Player_Animation_Frame = a
dim _PlayerPosition = b
dim p1posx=player0x.d
dim p1posy=player0y.e
__GameStart
COLUPF = $0E
_Player_Animation_Frame = 0
drawscreen
;***************************************************************
;
; Road Section Positions X for Spawn Enemies
;
data _Road_Pos
49,77,105
end
__MAIN_LOOP_STAGE1
COLUPF = $0E
; Change position each 15 cycles
if _Player_Animation_Frame = 0 then temp1 = (rand&3)
if _Player_Animation_Frame = 15 then temp1 = (rand&3)
if _Player_Animation_Frame = 30 then temp1 = (rand&3)
; GETTING RANDOM ARRAY POSITION
if _Player_Animation_Frame < 10 then gosub __Player_Sprite : COLUP0 = $84 : p1posx = _Road_Pos[temp1] : p1posy = 50
if _Player_Animation_Frame > 9 && _Player_Animation_Frame < 20 then gosub __Player_Sprite : COLUP0 = $34 : p1posx = _Road_Pos[temp1] : p1posy = 50
if _Player_Animation_Frame > 19 then gosub __Player_Sprite : COLUP0 = $0E : p1posx = _Road_Pos[temp1] : p1posy = 50
_Player_Animation_Frame = _Player_Animation_Frame + 1
if _Player_Animation_Frame = 30 then _Player_Animation_Frame = 0
drawscreen
goto __MAIN_LOOP_STAGE1
__Player_Sprite
player0:
%01111110
%01111110
%11111111
%11111111
%11111111
%01111110
%01111110
end
return thisbank
How to find the average weight of a specific gender between 12 people with their own gender, height and weight
The question is implementing that I need to find the average weight of males from a list of 12 people that are males and females. I am not sure what to use since I can't use any other external additions like panda or tables to make it easier. I need to write it in a basic python edition, the 12 people don't have to be random, but I'm not sure if I can use the equations and how do I state multiple arrays with multiple statistics that are merged together, so I used random number, but I can again with the same problem on how do I know which random number is generated to which gender. What I had in mind that I want 12 people with their gender, height and weight and after the make a calculation of the average weight of males in the calculation the people can be input normally in a range or randomly both work, but I'm just not sure how to use the different stuff with each other to find their average weight of males. Here is the code I'm working on It's nothing, but it's maybe an idea to explain in details what I want exactly to do
import random
ranlistgend = []
n = 10
for i in range(n):
ranlistgend.append(random.randint(1, 2))
print(ranlistgend)
ranlisthei = []
n = 10
for i in range(n):
ranlisthei.append(random.randint(140, 190))
print(ranlisthei)
ranlistwei = []
n = 10
for i in range(n):
ranlistwei.append(random.randint(60, 100))
print(ranlistwei)
`
Why do 2 histograms overlap in matplotlib?
In this python script is an attempt to create two histogram in one figure but the second histogram overlaps the first one
from random import randrange
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(50,50))
ids = [str(randrange(10000, 99999)) for i in range(1000)]
ids2 = [str(randrange(10000, 99999)) for i in range(1000)]
def fun1():
ax = fig.add_subplot(1, 1, 1)
n, bins, patches = ax.hist(x=ids, bins=range(500))
ax.grid(axis='y', alpha=0.6)
fig.tight_layout(pad=3.0, w_pad=2.0, h_pad=2.0)
def fun2():
ax2 = fig.add_subplot(2, 1, 2)
n, bins, patches = ax2.hist(x=ids2, bins=range(500))
ax2.grid(axis='y', alpha=0.6)
fun1()
fun2()
Although I used tight_layout
this does not help with the overlapping of the two histograms.
vendredi 26 août 2022
Python Library for Finding the Most Optimal Combination of Words
I was working on a project because I was bored. Most people have heard of Wordle, but I like to play Quordle, which is the same thing, except you play 4 words at once. You can play it here if you would like (there's also octordle which is even more fun). I was getting bored with easily beating the puzzle with my normal starting guesses, and wanted to make it more interesting for myself.
Anyway, I made a list of every possible 5 letter word, then removed all the words that contained repeat letters (e.g. teeth). So now I'm only left with words that have 5 different letters.
I then randomize the list, and brute forced through the entire 6k+ word list to find a set of starting guesses that have no overlapping letters. Then I use the guesses that appear as my starting guesses. Since it's randomized, it could be 2, 3, or 4 words. Technically, it could be 5, but I've yet to see that through random chance. This makes the game more fun for me.
I like what I've done, but I was wondering if there was a way to find the most optimal 5 word combination, which would result in 5 guesses with 25/26 letters of the alphabet used. I'm sure there's some ML libraries I could use to approach this problem, but I have no idea where to start with the 100,000+ libraries to chose from.
Here is the code to the randomizer. I'm also open to suggestions on improving my existing code, I'm sure there's a more pythonic way of doing things.
jeudi 25 août 2022
How do I avoid duplicate Cartesian coordinates in my dynamically generated array? numpy.arange python 3.10
I am working to generate a list of Cartesian coordinates in python3.10. The problem is, that of the 16 individual coordinates generated, the second 8 coordinate sets are identical to the first 8 coordinate sets. How do I ensure that all 16 coordinate sets are unique? My solution needs to scale up to 1,024 coordinate sets. I coupled numpy.arange() with a random number generator to get the desired array size. The duplication only seems to occur after I perform matrix multiplication to reduce the matrix from 4 dimensions to 3. Here is the code I currently have, and it's outputs:
import numpy as np
dims = 4 # User can enter a value between 4 and 10.
magnitude = 1 # User can enter any number here.
verticesMatrix = magnitude * (2*((np.arange(2**dimensions)[:,None] & (1 << np.arange(dimensions))) > 0) - 1)
rows = int(0)
cols = int(0)
projectionMatrix = np.ndarray(shape=(dimensions-1, dimensions), dtype=np.int32)
for rows in range(dimensions-1):
for cols in range(dimensions):
if cols == rows:
projectionMatrix[rows, cols] = 1
else:
projectionMatrix[rows, cols] = 0
myProjection = matrices.projectionMatrix(dims)
myProjectionRows, myProjectionCols = np.shape(myProjection)
myVerticesRows, myVerticesAxes = originalVertices[0].shape
if myProjectionCols != myVerticesAxes:
logging.error("# of Columns in Projection Matrix must be the same as the # of axes in
each coordinate set from the Vertices Matrix.")
else:
myFlattenedHypercube = np.empty((myVerticesRows, myProjectionRows))
row = 0
while row <= vertices - 1:
myFlattenedHypercube[row] = np.matmul(myProjection, originalVertices[0][row])
row += 1
The output that I get in my log is as follows:
('Orginal VerticesMatrix Generated:', array(
[[-1, -1, -1, -1],
[ 1, -1, -1, -1],
[-1, 1, -1, -1],
[ 1, 1, -1, -1],
[-1, -1, 1, -1],
[ 1, -1, 1, -1],
[-1, 1, 1, -1],
[ 1, 1, 1, -1],
[-1, -1, -1, 1],
[ 1, -1, -1, 1],
[-1, 1, -1, 1],
[ 1, 1, -1, 1],
[-1, -1, 1, 1],
[ 1, -1, 1, 1],
[-1, 1, 1, 1],
[ 1, 1, 1, 1]]))
('Projection Matrix:', array(
[[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]]))
("Returned flattened vertices:", array(
[[-1., -1., -1.],
[ 1., -1., -1.],
[-1., 1., -1.],
[ 1., 1., -1.],
[-1., -1., 1.],
[ 1., -1., 1.],
[-1., 1., 1.],
[ 1., 1., 1.], # This is the 8th coordinate set
[-1., -1., -1.],
[ 1., -1., -1.],
[-1., 1., -1.],
[ 1., 1., -1.],
[-1., -1., 1.],
[ 1., -1., 1.],
[-1., 1., 1.],
[ 1., 1., 1.]])) # This is the 16th coordinate set, and is identical to the 8th.
I am just a poor fool subject to the laws of matrix multiplication yielding such an unfortunate result?
Quicktime Error opening random files using simple apple script
I'm getting the following error: "The file isn’t compatible with QuickTime Player."
When using this script:
tell application "Finder"
set random_file to some file of entire contents of folder "Movies" of home
open result
end tell
However, I am able to open the file from the finder manually and once I do the script works on just that file. The problem is I have thousands of files and don't want to open each one manually for the script to work again. Have not had this problem with the script in the past.
mercredi 24 août 2022
PowerShell output random numbers to csv. CSV full of empty lines
Actually 2 part question here. The code below outputs nothing but 1000 blank lines to the csv. I'm just trying to output a random range of numbers to a csv and I actually need to follow up with 4 more columns of randomly generated numbers like this first attempt so the second part of this is after getting this first issue resolved how would I direct the next ranges to the other columns?
Get-Random -Count 998 -InputObject (8000..8999) | Export-Csv -Path SingleColumn.csv -NoTypeInformation
mardi 23 août 2022
Fetch the next strategy based on the old strategies in MySQL. Example 4,2,9,14 and find 11
I have the following doubt:
I have a table with 4 thousand records with the following columns, id, strategy, option and data.
The numbers are random, line by line.
I needed to check if the previous 3 records are part of my pattern and search for the next 2 numbers, line by line.
Example,
my previous strategies are for the search:
strategy: 4 strategy: 2 strategy: 9 current: 14
Now I need to look for the next strategy, which in this case would be 11, so I needed to consult the last 4 strategies and check if they match the ones I'm looking for.
I would need to fetch 4,2,9,14 and find 11, and it would have to be in ID order.
Below is an example print of my table.
Hangman game, whenever I try to put the same alphabet twice it takes 2 lives instead of just taking one
I am a beginner in Python and I am making Hangman game project
So whenever I try to put the same alphabet twice it takes 2 lives instead of just taking one because both conditions are getting true. My code is running fine but output is coming wrong due to both conditions in if statement given is satisfied
here is my code below
import time #importinf random module
#from hangman_art import logo #importing logo which i have in my PC, you ignore.
print("Welcome to HANGMAN")
#print(logo) #printing the logo which imported
user = input("\nWhat's Your Name : ") # take input for user name
print(f"\nHello {user}! Best Of Luck") #just for code to feel good.
x = (input("\nReady to play??? : ")) #input from user weather he/she wants to play or no.
if x == "yes" or x =="YES" or x =="Yes" or x == "y" or x == "Y": print("\nGame Loading in
3..2..1")
else:
print("\nOk Sadly ending the game!! BYE BYE")
exit()
#time.sleep(3)
print("\nGame Start!!")
#time.sleep(1)
print("\nRules as follows :-\n1. Guess the right word letter by letter.\n2. You only got 6
lives.\n3. Do not repeat the same alphabet entry it will reduce your life.\n4. Enjoy the game.")
#time.sleep(3)
import random #importing random module for code to choose any random number.
word_list=["TIGER","ELEPHANT","LION","CAT","DOG","HORSE"] #you can add n numbers of words.
chosen_word = random.choice(word_list) #giving variable to chosen random word.
length = len(chosen_word) #variable to find length of chosen word.
display=[] #creating an empty list.
in_game = True #for while loop to run continously
lives = 6 #user get 6 lives.
display=[]
duplicate=[] #creating an empty list to store duplicate values.
for _ in range (length):
display += "_"
#here looping for guess and game
while in_game:
guess = input("\nCome On Guess a word letter by letter : ").upper()
#make a list called duplicate
#add guess letter to duplicate list
#check if the entered letter is already present in that list
#if present then show msg stating already used word
#else follow the normal process
#duplicate=[]
if guess in display:
print("\nYou guessed",guess)
for position in range(length): #for getting length of number to be guessed
letter = chosen_word[position]
if letter == guess:
print("\nYou guessed",guess,"which is right aplhabet!!")
display[position] = letter
print(" ".join(display)) #joiningdisplay
if guess in duplicate:
lives -= 1 #this condition for taking life if duplicate entry.
print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to continues same
alphabet entry.") #here condition gets true and then goes to another if statment there also it gets true and code takes 2 life.
if lives == 0:
in_game = False
print(f"\n{user} You lost all your life, YOU LOSE.")
duplicate.append(guess)
#here 2 conditions are getting true so code is taking 2 lives please help
if guess not in chosen_word:
print("\nYou guessed", guess, "which is not the alphabet, life lost.")
lives -= 1
if lives == 0:
in_game = False
print(f"\n Try next
time {user}, You lost all your life, YOU LOSE.")
if not "_" in display:
in_game = False
print(f"\n Congrats {user} You WIN.")
from hangman_art import stages
print(stages[lives])
lundi 22 août 2022
How to assign multiple variables on a single line?
class Color {
constructor(red, green, blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
generateColor(){
// this.red, this.green, this.blue = this.randomColor() ???
return (`Random Color : \n Red : ${this.red}\n Green : ${this.green}\n Blue :
${this.blue}`)
}
randomColor() {
return Math.floor(Math.random() * 256);
}
}
How can i make this kind of multiple assignment without using arrays ?
Re arrange randomly a string type of array of 8 words [closed]
Im trying to re-arrange the positions in an array I created with the words "paprika", "licantropo", "soperutano","sopa","solfeo","cuba","espejo","codigo" and take each position in the array and make the order of the letters random, but I ran into a wall and can't figure out a way. Any ideas? I checked some code online on github, but its not working on my code. Any help would be greatly appreciated.
Uncorrelated random variables python
I am trying to create a random vector whose components are uncorrelated standard normal variables with zero mean and unit variance. I am using the function
np.random.uniform(0,1,size=n)
Are these random variables uncorrelated? Because when I am trying to find covariance coefficient:
np.cov(np.random.uniform(0,1,size=n), y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None)
Also, Python is not giving me exactly zero coefficient of covariance (my result is close to 0.08).
is there a way to generate positive random numbers with fixed mean and SD, and sd > mean?
I want to generat a veusing R. Is there a way to generate a sequence of POSITIVE numbers that satisfy specific constraints
- a mean of 13,
- a standard deviation of 30.96 , and
- a sample size of 6.
Thank you guys.
dimanche 21 août 2022
How to get 10000 random numbers from chainlink VRF V2?
I want to generate 10000 random numbers by using chainlink VRF V2,but the max NUM_WORDS is 500 in one request,and it fails every time! What should I do? My account has enough LINK,but what I have done below does't work!
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol";
import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
contract VRFCoordinatorTest is VRFConsumerBaseV2 {
// Chainlink VRF Variables
address vrfCoordinatorV2 = 0x6168499c0cFfCaCD319c818142124B7A15E857ab;
uint64 subscriptionId = 14422;
bytes32 gasLane = 0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc;
uint32 public callbackGasLimit = 2500000; //already max gaslimit
//network coordinator
VRFCoordinatorV2Interface private immutable _vrfCoordinator;
// The default is 3, but you can set this higher.
uint16 public REQUEST_CONFIRMATIONS = 10;
// retrieve NUM_WORDS random values in one request.
uint32 public NUM_WORDS = 500;
//keep the randomWords from fulfillRandomWords() function.
uint256[][] public _randomWords = new uint256[][](0);
//uint256[] public _randomWords;
event RequestedRandomWords(uint256 requestId ,address requester);
constructor() VRFConsumerBaseV2(vrfCoordinatorV2) {
_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinatorV2);
}
function fulfillRandomWords(uint256, uint256[] memory randomWords) internal override{
_randomWords.push(randomWords);
// _randomWords = randomWords;
}
function requestRandomWords()public{
uint256 requestId = _vrfCoordinator.requestRandomWords(
gasLane,
subscriptionId,
REQUEST_CONFIRMATIONS,
callbackGasLimit,
NUM_WORDS
);
emit RequestedRandomWords(requestId, msg.sender);
}
function set_REQUEST_CONFIRMATIONS(uint16 comf)public{
REQUEST_CONFIRMATIONS = comf;
}
function set_NUM_WORDS(uint32 num)public{
NUM_WORDS = num;
}
function set_gasLimit(uint32 gasl) public{
callbackGasLimit = gasl;
}
function getMaxLengthAndNum()public view returns(uint256,uint256){
uint256 lth = _randomWords.length;
uint256[] memory tmpArray = _randomWords[lth-1];
uint256 lastNum = tmpArray[tmpArray.length-1];
//uint256 maxNum = _randomWords[_randomWords.length-1];
return (lth,lastNum);
}
}
Tomar una lista con números en Python y cambiar sus valores sin repeticiones
tengo un array o lista en Python con 9 números (lista=[1,1,1,1,3,5,6,7,9]), necesito un código que tome esos números los recorra y que cuando encuentre uno repetido me genere aleatoriamente un nuevo numero para remplazarlo; la idea es que al final se arroje un nuevo array o lista con nueve números sin repetir.
Escribí este código tratando de controlar el valor del bucle con la variable j con el fin que no se salga del mismo hasta que no encuentre un valor aleatorio adecuado. ¿Qué me estará fallando? Agradezco su feedback.
import random
lista=[1,1,1,1,3,5,6,7,9]
#0,1,2,3,4,5,6,7,8
for i in range(len(lista)):
aux=i
for j in range(1, len(lista)):
if lista[j]==lista[i]:
aleatorio=random.randint(0,9)
if aleatorio not in lista:
lista[i]=aleatorio
else:
aux=i
j=j-1
How to use call the random function
I have a code which has functions, which should be called randomly. However, when I am running the code:
def print1():
print(1)
def print2():
print(2)
def print3():
print(3)
l=(print1(), print2(), print3())
x=random.choice(l)
x()
it doesn't work properly. It is outputting everything (1,2,3) and gives an error:
''NoneType' object is not callable'
How to fix that?
samedi 20 août 2022
(READ COMMENTS) Python temporarily changes my variable, how do i stop that?
So i have this code:
from random import randint
for i in range(9999999):
a=input("press any key to roll the wheel: ")
money=0
money2=randint(0, 400)
money+=money2
print(money)
And while i was testing the program, i found that it isn't doing what i expected it to do (for example: add 382 with 196), i wanna ask, whats wrong? Everything looks to be working just fine, just that it seems to change the "money" variable temporarily, after that it resets. What happens when you press enter multiple times
Randbetween until a specific day?
I want to have the randbetween function only return a random number until a specific day, then stop changing. Is there a way to accomplish this in googlesheets?
=IF(today()<F1,randbetween(1,10),)
I tried something like this, but it would just go blank if it's false.
Fill a NA matrix using apply functions
I want to fill an empty matrix using the apply function. For example, my purpose is to simplify the following code
tmp <- matrix(NA, 10, 10)
tmp[, 1] <- sample(1:500, 10)
tmp[, 2] <- sample(1:500, 10)
...
tmp[, 10] <- sample(1:500, 10)
Is it possible to make the code above just one line using the apply
function? If it is not, recommendation of any kind of simpler code may be helpful for me:)
vendredi 19 août 2022
How to generate vector of vectors of random sizes having random number of uint8_t type within range? [duplicate]
I want to create vector of vectors of random sizes having random number of uint8_t type within range eg 0 to 19.
This is my function for generating the same it works for int type but fails for uint8_t.
#include <cstring>
#include <sstream>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <vector>
#include <time.h>
void generate_random_vectors(const int num_of_rand_vectors, std::vector<std::vector<uint8_t>> &vec)
{
for (int j = 0; j < num_of_rand_vectors; ++j)
{
// the vector size will be randomal: between 0 to 19
int vec_size = (rand() % 20);
std::vector<uint8_t> rand_vec(vec_size);
for (int k = 0; k < vec_size; ++k)
{
// each vec element will be randomal: between 1 to 20
rand_vec[k] = 1 + (rand() % 20);
}
// each vector will be sorted if you want to
// push each of the 'num_of_rand_vectors'-th vectors into vec
vec.push_back(rand_vec);
}
}
Usage
std::vector<std::vector<uint8_t>> vec;
generate_random_vectors(3, vec);
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
std::cout << vec[i][j] << " ";
}
std::cout << "\n";
}
Error output:
♥ ♫ ♠ ♠ ♣ ♥ ♥
♫ ♂ ‼ ☻ ☼ ☻
♀ ♀ ♀
♠ ☻ ♂ ♫ ☼ ‼ ¶
How could I correctly implement it?
How can i create a list of 50 random numbers where the even numbers are twice the odd numbers?
can you help me with this problem please? I have to create a list of 50 random numbers from 1 to 10 where the odd numbers frequency is aproximately twice the even number frequency.
How to make a deductive logic game of guessing a three degit number?
The question is: In Bagels, a deductive logic game, you must guess a secret three-digit number based on clues. The game offers one of the following hints in response to your guess: “Pico” when your guess has a correct digit in the wrong place, “Fermi” when your guess has a correct digit in the correct place, and “Bagels” if your guess has no correct digits. You have 10 tries to guess the secret number.
I am new in Python. Any suggestions are appreciated:
#Generating a random 3-digit number
import random
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
random_number=random_with_N_digits(3)
print(random_number)
#Making a dictionary From the integers of the number
#Indexes as Keys and integers as values
rand_list = [int(x) for x in str(random_number)]
rand_dictionary=dict(zip(range(len(rand_list)),rand_list))
#rand_dictionary
#For loop for 10 tries
for i in range(10):
input_num = int(input('Please guess that three digit number : '))
#Validating the input
if input_num < 999 and input_num > 100:
#Making dictionary for the inputted number in similar way like the random number
input_list = [int(x) for x in str(input_num)]
input_dictionary = dict(zip(range(len(input_list)), input_list))
if random_number == input_num:
print("Your answer is correct!!")
break
elif [i for (i, j) in zip(rand_list, input_list) if i == j]:
print("Fermi")
if set(rand_list) & set(input_list):
print("Pico")
elif set(rand_list) & set(input_list):
print("Pico")
else:
print("Bagels")
else:
print("This is not a valid three digit number. Please try again.")
print("The test is finished.")
jeudi 18 août 2022
I have a python script that generates both letters and numbers combinations of a certain length that can be selected in the settings
I need to make sure that the first character does not change and the others change, help me with this
from random import randrange
from multiprocessing import Process, cpu_count, Value
###################################################################
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
cores = cpu_count()
###################################################################
def gen(l):
return ''.join([alphabet[randrange(0, len(alphabet))] for i in
range(l)])
res = open('result.txt', 'a')
def work():
while True:
res.write('{0}\n'.format(gen(18)))
###################################################################
if __name__ == '__main__':
workers = []
for r in range(cores):
p = Process(target=work)
workers.append(p)
p.start()
for worker in workers: worker.join()
res.close()
###################################################################
Add 1 to a random value in a column using dplyr
I have the following dataframe, in tibble format:
> Colours_and_numbers
# A tibble: 10 × 2
colours numbers
<chr> <dbl>
1 Yellow 7
2 Red 19
3 Orange 8
4 Blue 10
5 Green 5
6 Black 9
7 Purple 9
8 White 13
9 Grey 11
10 Brown 9
I would like to add 1 to a randomly chosen row from the numbers
column using dplyr
. For that purpose I tried using
Colours_and_numbers %>%
mutate(colours = replace(colours, sample((1:10), 1), colours[sample((1:10), 1)] + 1))
However, this is not working, as first sample()
and second sample()
will hardly ever refer to the same element of the numbers
column.
Is there a way I can make sure both sample()
refer to the same element without creating a specific variable to store the value generated by the first sample()
and then using it in the last part of the replace()
function? If you come up with a simpler way to add 1 to a random row, it would also appreciate that.
mercredi 17 août 2022
Is there a method to sample number of rows randomly while two of those rows are constant
I want to select a certain amount of rows randomly while the first and last samples are always selected. Suppose I have a row of numbers df
as
| A | B |
| -------- | -------------- |
| 1 | 10 |
| 2 | 158 |
| 3 | 106 |
| 4 | 155 |
| 5 | 130 |
| 6 | 154 |
| 7 | 160 |
| 8 | 157 |
| 9 | 140 |
| 10 | 158 |
| 11 | 210 |
| 12 | 157 |
| 13 | 140 |
| 14 | 156 |
| 15 | 160 |
| 16 | 135 |
| 17 | 102 |
| 18 | 150 |
| 19 | 120 |
| 20 | 12 |
From the table, I want to randomly select 5 rows. While selecting 5 rows I want the row 1 and row 20 to be always selected, while the rest of 3 rows can be anything else.
Right now I'm doing the following thing, but don't know if there is a way to do it in the way I want.
n <- 5
shuffled= df[sample(1:nrow(df)), ] #shuffles the entire dataframe
extracted <- shuffled[1:n, ] #extracts top 5 rows from the shuffled sample
I need to do this because I will further analyze the results.
Lagged auto-correlations of numpy.random.normal not nul
I am struggling with an unexpected/unwanted behavior of the function random.normal of numpy.
By generating vectors of T elements with this function, I find that in average the lagged auto-correlation of those vectors in not 0 at lags different than 0. The auto-correlation value tends to -1/(T-1).
See for example this simple code:
import numpy as np
N = 10000000
T = 100
invT = -1./(T-1.)
sd = 1
av = 0
mxlag = 10
X = np.random.normal(av, sd, size=(N, T))
acf = X[:,0:mxlag+1]
for i in range(N):
acf[i,:] = [1. if l==0 else np.corrcoef(X[i,l:],X[i,:-l])[0][1] for l in range(mxlag+1)]
acf_mean = np.average(acf, axis=0)
print('mean auto-correlation of random_normal vector of length T=',T,' : ',acf_mean)
print('to be compared with -1/(T-1) = ',invT)
I have this behavior with both those version of Python: v2.7.9 and v3.7.4. Also, codding this in NCL gives me the same result.
The problem I am referring to might seem tiny. However, it leads to larger biases when those vectors are used as seeds to generate auto-regressive time series. This is also problematic in case one uses this function to create bootstrap statistical tests.
Someone would have an explanation about this? Am I doing something obviously wrong?
Many thanks!
C language Hangman game, how do i link the scanf with the masked word and have a counter inc for each incorrect input?
I am making a hangman game, I created a randf to select from a batch of words, aswell as masked the words in order for the guesser to guess the letter of the random word. The issue lies in that I have no idea how to connect the two. I already made the loop but without actually connecting them it will always print when counter = 0 because I have not made the condition for when
for(int counter; answer != word; counter++;)
But then I get the error:
operand types are incompatible, ("char" and "char(*)[200]").
Any solutions?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include <time.h>
#include <string>
#define ARRAY_SIZE 10
int main()
{
//randomwordgenerator
char word[ARRAY_SIZE][200] = { "tiger", "lion", "elephant", "zebra", "horse", "camel", "deer", "crocodile", "rabbit", "cat" };
int x = 0;
srand(time(0));
x = rand() % ARRAY_SIZE;
system("pause");//will pause the rand function
//masking and unmasking word
char m = strlen(word[x]);//will count the number of letters of the random word
int mask[200]{};
for (int i = 0; i < m; ++i) //loop until all leters are masked
{
mask[i] = 0;
}
//Introduction
printf("Hey! Can you please save me? \n");
printf(" O\n/|\\ \n/ \\ \n");
//Ask for answer
printf("\nType a letter to guess the word and save me. The letter is case sensitive so please pick lower case or I might die\n");
char answer;
scanf_s("%d", &answer);
//loop w counter
for (int counter = 0; counter++;) {
if (counter == 0)
{
printf("\n");
}
else if (counter == 1)
{
printf("\n=========");
}
else if (counter == 2)
{
printf("\n+\n|\n|\n|\n|\n|\n=========");
}
else if (counter == 3)
{
printf("\n+---+\n| |\n|\n|\n|\n|\n=========");
}
else if (counter == 4)
{
printf("\n+---+\n| |\n| O\n|\n|\n|\n=========");
}
else if (counter == 5)
{
printf("\n+---+\n| |\n| O\n| |\n|\n|\n=========");
}
else if (counter == 6)
{
printf("\n+---+\n| |\n| O\n| |\n| / \\ \n|\n=========");
}
else if (counter == 7)
{
printf("\n+---+\n| |\n| O\n| /| \n| / \\ \n|\n=========");
}
else if (counter == 8)
{
printf("\n+---+\n| |\n| O\n| /|\\ \n| / \\ \n|\n=========");
}
else if (counter == 9)
{
printf("\nReally left me hanging there buddy");
return 0;
}
else
{
printf("\nThanks for saving me!");
}
return 0;
}
}
Random sampling in R without direct repetition and exact quantity of each number
How can I randomly sample the color order of 368 images using 4 colors that
- should not be repeated directly ("red" "red" "blue" would not be ok, but "red" "blue" "red" would be)
- should each appear with an equal quantity (each 92 times because 368/4 = 92)?
Based on this, I have already managed the sampling without direct repetition:
library("dplyr")
set.seed(340)
values <- c("blue", "red", "green", "yellow")
len <- 368 # number of samples
samp <- sample(values, 1) # initialise variable
cols <- sapply(2:len, function(i) samp[i] <<- sample(setdiff(values, samp[i-1]), 1, replace = TRUE))
table(cols) # colors appear 94, 92, 88, 93 times
I tried building a for-loop that samples until the exact numbers are reached with if(table(cols)[1:4] == 92)
, but it didn't work and after doing a lot of research, I still don't know how to proceed. I would be really thankful for tips and help!
mardi 16 août 2022
How to generate the same random sequence from a given seed in Delphi
I am wanting to generate the same random sequence (of numbers or characters) based on a given "seed" value.
Using the standard Randomize
function does not seem to have such an option.
For example in C# you can initialize the Random function with a seed value (Random seed c#).
How can I achieve something similar in Delphi?
Assigning a weighted random variable to a new column in an R dataframe
I have a Dataframe that looks like this in R:
df1 |date|location|daytype| |----|---|---| |2022-9-1|NT|Thur| |2022-9-2|NT|Fri| |2022-9-3|AP|Sat| |2022-9-4|AP|Sun| |2022-9-5|NT|Mon|
I want to create a new column for either a morning or an afternoon shift based on random weight sampling:
df2 |shift|weight| |---|---| |Morning|0.8| |Evening|0.2|
Is there a way to do this?
df1$shift <- sample(df2, prob = df$weight)
Weighted random number generation with seed and modifiers
I try to implement a generation of a complex object based on a weighted elements list.
ListEnum.kt
enum class Elements(weighting:Int){
ELEM1(15),
ELEM2(20),
ELEM3(7),
ELEM4(18)
// function to get weighted random element
companion object{
fun getRandomElement(seed:Long): Elements{
var totalSum = 0
values().forEach {
totalSum += it.weighting
}
val index = Random(seed).nextInt(totalSum)
var sum = 0
var i = 0
while (sum < index) {
sum += values()[i++].weighting
}
return values()[max(0, i - 1)]
}
}
}
MyClass.kt
class MyClass{
fun getRandomElement():RandomElement{
val seed = Random.nextLong()
val element = Elements.getRandomElement(seed)
return RandomElement(element, seed)
}
}
I can persist the seed and recreate the same object with the same seed.
Now I want to modify the weighting in the Elements enum at runtime.
Elements.kt
enum class Elements(weighting:Int){
ELEM1(15),
ELEM2(20),
ELEM3(7),
ELEM4(18)
// function to get weighted random element
companion object{
fun getRandomElement(seed:Long, modifiers:Mods): Elements{
var totalSum = 0
values().forEach {
var modifiedWeighting =it.weighting
if(modifiers.modifier[it] != null){
modifiedWeighting= modifiers.modifier[it].times(modifiedWeighting).toInt()
}
totalSum += modifiedWeighting
}
val index = Random(seed).nextInt(totalSum)
var sum = 0
var i = 0
while (sum < index) {
var newSum = values()[i].weighting
if(modifiers.modifier[values()[i]] != null){
newSum = newSum.times(modifiers.modifier[values()[i]]).toInt()
}
sum += newSum
i++
}
return values()[max(0, i - 1)]
}
}
}
That works for generating random elements with modified weightings, but now I can't recreate the object because the seed does not consider the modifiers.
How can I generate such an object based on modified weightings that I can recreate just from the seed?
Select random cell from non-adjacent cells/columns
I got multiple columns with information. I want to pick a random sentence from 'Mehrzahl' for every row involved. Is it possible to do this with a formula? In the case of Mehrzahl I want to select either E2 or N2 randomly, either E3 or N3 randomly, et cetera.
lundi 15 août 2022
How can I print out more than one random result without possible duplicates in any print statements
I am doing a basic random number generator which prints out the fist 6 numbers in a range up to 45 which works fine but I need it to print out a second time with 2 numbers up to 45, these two numbers can not be the same as any of the 6 numbers either.
enter code here
import random
nums = range(1, 45)
supps = range(1,45)
print(random.sample(nums,6))
print(random.sample(supps,2))
enter code here
Pygame Else Statement has a Pylance Error without Suggestion
else:
print('Goodbye, looks like the password was incorrect')
pygame.quit
If I need to show more, Ill do that, the error says that " Expected Expression Pylance "
I'm new to python, so sorry If I'm asking this weirdly.
How I can add random tag to multiple files for sorting by tag in file explorer
I have a folder with over 5,000 artistic reference images that are all meticulously named. I want to send them to https://mymind.com/ which is a platform that stores all your references and that allows research using an AI to find what's in the photo. Unfortunately, the service is still young and does not have the means of sorting randomly. It depends on how the imported files are sorted, i.e. how they are sorted in Windows Explorer.
My problem, which is that I would like to have a way to randomize my 5000 images in my folder without adding a number as a prefix to each filename, but rather a random tag.
I thought to myself that Windows offers the possibility of sorting by tag, so I started looking for a script to add a random tag (number, letter, symbol, etc.) to each file, but without result.
I therefore come to you, because I have no knowledge of scripting. Maybe a simple batch script would do?
How to get a random number in C++? [duplicate]
I'm new in C++I want to creat a Guess the Number game with it. But I ran into trouble when I was trying to create a random number. I think I need to include a package or something. Can anyone tell me what should I do?
How do I get a Different Random Choice When People Decided to Play Again? Python
I'm basically trying to get a different enemy every single time that people play/runs the code. For now, If I decided to play again the code keeps using the same values as before and I really want them to be different. Please help me. I'm New to using Python!
I left you the whole code of the program in case It helps you to help me. Thanks! I hope I will help others soon.
import random
items = []
enemy = random.choice(["Troll", "Pirate", "Gorgon", "Monster"])
weapons = random.choice(["Bow", "Axe", "Bazooka", "Sword"])
def print_pause(message_to_print):
print(message_to_print)
time.sleep(1)
def intro():
print_pause("You find yourself standing in an open field, "
"filled with grass and yellow wildflowers.")
print_pause(f"Rumor has it that a {enemy} is somewhere around here, and "
"has been terrifying the nearby village.")
def choice():
while True:
choice = input("Enter 1 to knock on the door of the house.\n"
"Enter 2 to peer into the cave.\n"
"What would you like to do?\n"
"Please enter 1 or 2.\n")
if choice == '1':
house()
elif choice == '2':
cave()
else:
print("Please enter 1 or 2.\n")
def fight():
print_pause(f"The {enemy} attacks you!")
fight = input("Would you like to (1) fight or (2) run away?\n")
if fight == '1':
if ({weapons}) in items:
print_pause(f"As the {enemy} moves to attack, you unsheath "
f"your new {weapons}.")
print_pause(f"The {weapons} of Ogoroth shines brightly in your "
"hand as you brace yourself for the attack.")
print_pause(f"But the {enemy} takes one look at your shiny new "
"toy and runs away!")
print_pause(f"You have rid the town of the {enemy}. "
"You are victorious!")
play_again()
else:
print_pause(f"You feel a bit under-prepared for this, "
"what with only having a tiny dagger.")
print_pause(f"You do your best...")
print_pause(f"but your dagger is no match for the {enemy}.")
print_pause(f"You have been defeated!")
print_pause(f"G A M E O V E R")
play_again()
elif fight == '2':
print_pause("You run back into the field. Luckily, "
"you don't seem to have been followed.")
choice()
def house():
print_pause("You approach the door of the house.")
print_pause(f"You are about to knock when the door "
f"opens and out steps a {enemy}.")
print_pause(f"Eep! This is the {enemy} house!")
fight()
def cave():
if ({weapons}) in items:
print_pause("You've been here before, and gotten all "
"the good stuff. It's just an empty cave now.")
print_pause("You walk back out to the field.")
else:
print_pause(f"You peer cautiously into the cave.")
print_pause(f"It turns out to be only a very small cave.")
print_pause(f"Your eye catches a glint of metal behind a rock.")
print_pause(f"You have found the magical {weapons} of Ogoroth!")
print_pause(f"You discard your silly old dagger and take "
f"the {weapons} with you.")
print_pause(f"You walk back out to the field.")
items.append({weapons})
choice()
def play_again():
while True:
choice = input("Play again? [y|n]\n")
if choice == 'y':
play_game()
elif choice == 'n':
print('Thanks for playing! Goodbye!')
exit(0)
else:
print("(Please enter y or n.")
def play_game():
intro()
choice()
play_game()
dimanche 14 août 2022
Add random tag to multiple files
I need to randomly sort my files inside a folder, but without changing the names of the files.
I thought to myself that Windows offers the possibility of sorting by tag, so I started looking for a script to add a random tag (number, letter, symbol, etc.) to each file, but without result.
I therefore come to you, because I have no knowledge of scripting. Maybe a simple batch script would do?
How do I grab a random item from a JSON file in Python? [closed]
I am using a "quotes.json" file to store a list of quotes for a program and I need to select a random item from it. The list is structured like this:
[
{
"text": "Genius is one percent inspiration and ninety-nine percent perspiration.",
"author": "Thomas Edison"
},
{
"text": "You can observe a lot just by watching.",
"author": "Yogi Berra"
},
{
"text": "A house divided against itself cannot stand.",
"author": "Abraham Lincoln"
}
]
What is a simple way to grab a random text and author with a python script?
Newbie question. Guess a number - code not working
import random
def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
guess = int(input(f"Guess a number between 1 and {x}: "))
if guess > random_number:
print(f"{guess} is incorrect, try lower!")
elif guess < random_number:
print(f"{guess} is incorrect, try higher!")
print(f"congratulations, you have guessed {random_number} correctly!")
Please help with this code, I have no idea why it's just not working. Been trying for a few hours. I see no issue with it, but then again, I am a newbie.
Randint and random not generating a num in python
I have random and randint imported and did what is shown in a small tutorial i read but it still says it is not working anyone knows what is the issue. I am sorry if the code is a little messy but i am kinda new to pygame
import pygame
import math
import random
from random import randint
import sys
pygame.init()
fps = 30
fpsclock=pygame.time.Clock()
window = pygame.display.set_mode((600, 600))
x = 275
y = 275
xr = randint(30,270)
yr = randint(30,270)
color = (255,0,0)
color2 = (0,0,255)
# main application loop
run = True
while run:
# limit frames per second
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# clear the display
window.fill(0)
# draw the scene
key_input = pygame.key.get_pressed() #key imputs
pygame.draw.rect(window, color, pygame.Rect(x,y,30,30))
pygame.draw.rect(window, color2,pygame.Rext(xr,yr,30,30))
pygame.display.flip()
if key_input[pygame.K_LEFT]:
x -= 5
if key_input[pygame.K_RIGHT]:
x += 5
if key_input[pygame.K_DOWN]:
y += 5
if key_input[pygame.K_UP]:
y -= 5
pygame.display.update()
fpsclock.tick(fps)
# update the display
pygame.display.flip()
pygame.quit()
exit()
What happens when you use srand with no arguments?
The question is pretty straightforward. What exactly happens when you use "srand" with no arguments? What is the expected behavior?
srand();
my $x1 = int(rand(65536)) % 65536;
my $x2 = int(rand(65536)) % 65536;
print "$x1\n";
print "$x2\n";
samedi 13 août 2022
How to sample mixed data samples given pdf
Assume I have a pdf p(x), where x has both categorical and continuous features, how can I sample from this distribution p(x)?
Limit number of Array.filter() and randomise results
I have an App where you can select a muscle and a number of exercices for this muscle. It will generate a program for the gym.
Here is my code after the visitor selected a muscle and a number of exercices he wishes.
const generateProgram = () => {
if (program) {
for (let i = 0; i < program.length; i++) {
const muscle = Object.keys(program[i])[0];
const numberOfExercices = Object.values(program[i])[0];
const dataAsker = exercices.filter(
(exercice) => exercice.id === muscle
);
console.log(dataAsker);
}
}
};
The console.log returns this Array :
So this works fine. Now, I'd like to get from this filter only the number of items corresponding to numberOfExercices
and randomly.
I tried to make another for (let j = 0; j < numberOfExercices; j++
but I still got the 10 objects.
How is this possible please ?
PS : program
is just a state containing the muscle to work and the number of exercices based on visitor selection. For this exemple, program is {Abdominaux, "0"}
.
Method that returns a weighted random value based on input [closed]
I am struggling to think of a way to implement a method that takes a number ranging from [0,100] and returns a number ranging from [0,10]. Such that it is more likely to return a high value if the input value is high and vice versa. I also want the PDF of the method to be continuous, so an input of 11 should give you slightly different odds than an input of 12. Any tips/tricks on how to logically implement such a method will be greatly appreciated.
Random value generator in VHDL
I am trying to generate some random values (only 1 and 0) for a VHDL testbench. I've tried the following code:
impure function rand_int(min_val, max_val : integer) return integer is
variable r : real;
variable seed1, seed2 : integer := 999;
begin
uniform(seed1, seed2, r);
return integer(round(r * real(max_val - min_val + 1) + real(min_val) - 0.5));
end function;
but it only seems to be giving 1, and never 0. I can't understand where I'm doing wrong, any help would be greatly appreciated.
How to store the number in a secure way? using Chainlink VRF generator
So i manage to run ChainLink VRF generator on my contract which stores a numbers in a public array. How can i use it in a secure way? Im not an expert, just started with solidity but to my understanding basically everything from the contract can be read.
To be more specific. ChainLink VRF gives me nice big random number as bytes32 stored in array. Is storing it already reveal the number to a potential hacker? or in what way could i manipulate the data to make it unreadable from the outside.
The thing i am trying to do is to make a simple contract with guessing the number function. In order to make it less predictable i want to use ChainLink VRF to generate a number for the contract, but if you could read the generated number stored in a contract and then have what ever syntax is written for the function, you should be able to know the number, right? even if keccak is used, you can just run it outside of the contract and compare results, right?
would appreciate a big mind to bless me with its wisdom!🙇
vendredi 12 août 2022
how to find identical bitposition in a string in python
create a circuit of 5 qubits
qr = QuantumRegister(5, "qr") # quantum bit register
cr = ClassicalRegister(5, "cr") # classical bit register
circuit = QuantumCircuit(qr, cr)
# all qubits in superposition (50%:50% chance to be in |0> or |1>) and independent of each other
#The circuit is a superposition of 5 qubits.
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
circuit.measure(qr, cr)
circuit.draw(output='mpl', scale=1)
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend, shots=128, memory=True).result()
# get all experiments (number of shots)
rawvalues_sim = result.get_memory()
print(rawvalues_sim)
counts = result.get_counts()
print(counts)
plot_histogram(counts)
print("Length of data:", len(rawvalues_sim))
binarybytes = []
combinedbytes=[]
mainstring = 0
# for each qubit
for round in range(0, 5):
# construct sequence of 0s & 1s, creating a Byte for each sequence of 8 bits
rawvalues_sim_str = "".join(rawvalues_sim)
startindex = 0
endindex = 128
for i in range(0, len(rawvalues_sim_str),128): #rawvalues is storing 5 bits per index
b=rawvalues_sim_str[startindex:endindex]
startindex = endindex
endindex += 128
print(b)`
the b
here prints the random 128 sequence of bits. Now I want to find the identical bits in sequence of 128 bits. But I don't understand how.
jeudi 11 août 2022
Generate a random number that meets a given predicate
I would like to be able to generate random numbers that all meet a given predicate, for example only generate random numbers that are even or prime. Is there an algorithm to do this in a relatively efficient way? The way I have found to do this is to go brute-force:
let randIntSatisfy (randGenerator: System.Random) (satisfy: int -> bool) =
// The maximum number of tries before returning `None`
let maxTry = 100
let rec inner i =
function
| num when satisfy num -> Some num
| num when not (satisfy num) && (i < maxTry) -> inner (i + 1) (randGenerator.Next())
| _ -> None
inner 0 (randGenerator.Next())
let example =
let randGen = new System.Random()
seq { for _ = 0 to 10 do
yield randIntSatisfy randGen (fun x -> x % 2 = 0) }
This code will not loop forever but will not guarantee to find a number that satisfies the given predicate (assuming such a number exists of course, if I ask for a negative number, then the function will return None
all the time for example). Is there a way to do a little better than that?
PS: I've used F# here, but I'm not specifically asking for a language-specific answer.
Random number generator with different numbers
I am currently working on one of my first projects in C#. Right now i want to create something like a lottomachine. It should output 6 numbers all different from each other in the range of 1-49.
private void random()
{
Random rnd = new Random();
z1 = rnd.Next(1, 49);
z2 = rnd.Next(1, 49);
if (z1 == z2)
{
z2 = rnd.Next(1, 49);
}
z3 = rnd.Next(1, 49);
if ((z1 == z3) || (z2 == z3))
{
z3 = rnd.Next(1, 49);
}
z4 = rnd.Next(1, 49);
if ((z1 == z4) || (z2 == z4) || (z3 == z4))
{
z4 = rnd.Next(1, 49);
}
z5 = rnd.Next(1, 49);
if ((z1 == z5) || (z2 == z5) || (z3 == z5) || (z4 == z5))
{
z5 = rnd.Next(1, 49);
}
z6 = rnd.Next(1, 49);
if ((z1 == z6) || (z2 == z6) || (z3 == z6) || (z4 == z6) || (z5 == z6))
{
z6 = rnd.Next(1, 49);
}
}
The code is working for me currently, but I think there is a better, much shorter way what my code does. That's why I am asking for advice or for an idea, how to do it better than me.
Thanks in advance.
SQL Update Query in ACCESS: Generate individual random numbers within an interval for each record in a group
I want to generate some random values for a column (PreisLager) in a table (tblProdukte) using an Update query in MS ACCESS. I want the update query to populate column fields if they are NULL only. I want the updated values to be randomly generated within some interval. I want that Interval to differ by grouping (GroupID). And I want the random numbers to be drawn individually for each item in a group in sequence (or using different starting seeds for each item, not sure how the Rnd function works internally), meaning all records in the group get potentially different random numbers all drawn using the same group based interval. So, the interval for random number generation differs between groups, but not within them. Each item within a group receives a different draw, using the same interval. I have tried out some stuff using SQL but I am only able to get the interval be different between groups. The random numbers within those groups are all identical as I cannot figure out a way to use SQL to randomly "re-draw" the number each record in a group. I am imagining some type of group based for loop, not sure if that can be done in SQL, I have not really been using it much at all. Obviously I could group by individual recordID, but that would be a colossal mess. So far I was not able to find a way to do it in SQL. Ideally I would like to do it in SQL though. If that is not possible maybe there is a way using vba after the fact?? I am not looking for external libraries or other third party content, just basic ms access.
Here the code I have so far, which, as I mentioned, does not function the way I would like. If there is a cleaner way to write it that would also be welcome since it is a bit messy looking.
UPDATE tblProdukte
SET PreisLager = SWITCH(
[GroupID]=1, Int ((130 - 55 + 1) * Rnd + 55),
[GroupID]=2, Int ((650 - 400 + 1) * Rnd + 400),
[GroupID]=3, Int ((160 - 88 + 1) * Rnd + 88),
[GroupID]=4, Int ((850 - 550 + 1) * Rnd + 550),
[GroupID]=5, Int ((950 - 600 + 1) * Rnd + 600),
[GroupID]=6, Int ((1200 - 750 + 1) * Rnd + 750),
[GroupID]=7, Int ((300 - 80 + 1) * Rnd + 80),
[GroupID]=9, Int ((200 - 25 + 1) * Rnd + 25))
WHERE (((tblProdukte.PreisLager) Is Null));
Not sure Kolmogorov Smirnov Test is working as it should
So I have some data, Bequerels from Cs-137 decay from some samples. I have to check if the chosen data belongs to normal distributed sample values. Q-Q-plots suggest they do, Anderson Darling test too. Kolmogorov gives strange values. The Dataframe looks something like this:
Z79V0001 Z79V0003_1 Z790003_2
0 5.3738e+09 2.5241e+09 3.2927e+09
1 . . .
2 . . .
Code is like this:
for col in columns:
print([col])
print(stats.kstest(df[[col]].dropna().values, 'norm', args=(min(df[col]),max(df[col]))))
print(min(df[col]))#just to check
The output is something like
['Z79V0001']
KstestResult(statistic=0.62697, pvalue=1.23716e-17)
As I understood the p-value should be large for normal distributed data.
Do I have to normalize my data first? I am afraid I am comparing the Gauss CMD with the wrong scale?
Every help is appreciated.
How to make the number go up when a sword is upgraded?
I am working on my batch file game, and I was thinking that every time you upgrade the sword, the more you gain money.
But I tried to and it's not working!
For example:
You upgrade your sword and you gain a random damage number to defeat the enemies.
(Sword Upgraded! Your new upgraded damage: %damage%)
Could you please help me?
Select random option from dropdown in cypress
i run a script and want to select the random option on every run.
type Url = string
it('random_option', () => {
cy.visit(url)
const count = $options.length
const random_option = Math.floor(Math.random() * count)
cy.get('selector').select (random_option);
})
mercredi 10 août 2022
Generating Number from a given set with given probability in Matlab
I need to generate 5 integer number which must be from a given set of numbers {1,2,4,8,16}.
I need different values to have different probabilities of generating eg.
0.10 chance of 1
0.15 chance of 2
0.30 chance of 4
0.25 chance of 8
0.20 chance of 16
How can I do this in Matlab?
Generate 1000 sample based on a criteria [closed]
I have 3 numbers selected randomly from 3 different distribution (Exponential, Weibull, Normal) such that sum of all these numbers is always equal to 13.
Now I want to generate 1000 sample for such combinations
error in SRE pseudo absences selection in biomod2
I run BIOMOD_FormatingData from package "biomod2" in R to get pseudo absences data. It works for other methods such as "random" and "disk", but not for "are".
I got the error and warnings:
SRE pseudo absences selection Error in pa.data.tmp$xy[which((pa.data.tmp$sp != 1 | is.na(pa.data.tmp$sp)) & : subscript out of bounds
In addition: Warning messages:
1: In pa.data.tmp$sp == 1 & as.data.frame(pa.data.tmp$pa.tab)[, pa] : longer object length is not a multiple of shorter object length
2: In (pa.data.tmp$sp != 1 | is.na(pa.data.tmp$sp)) & as.data.frame(pa.data.tmp$pa.tab)[, : longer object length is not a multiple of shorter object length
Does anyone know this? Below is my code:
Anneslea.pa <- BIOMOD_FormatingData(resp.var = species.sp$Anneslea,
expl.var = bio.crop,
resp.xy = coordinates(species.sp),
resp.name = 'Anneslea',
#eval.resp.var = species.sp.ex.tst$pco,
#eval.expl.var = env,
#eval.resp.xy = coordinates(species.sp.ex.tst),
PA.nb.rep = 10,
PA.nb.absences = dim(species.sp)[1],
PA.strategy = 'sre',
PA.dist.min = NULL, # for 'disk' strategy
PA.dist.max = NULL, # for 'disk' strategy
PA.sre.quant = 0.1,
PA.table = NULL,
na.rm = TRUE)"
Random signls and clocktime in Simulink
I have a problem in understanding a simple matlab property. If you have this simple model with the clock, a matlab function and a scope. Why does the fuction is just run every 0.2 seconds in the simulation time? Same when you use 100 as Stop time. Then the function will be run every 2 seconds. In between the random values generated by the funtion, Simulink connects the values linearzed. Next question is why is simulink generating alwys the same "random"signal? I want to implement a random noise signal in a bigger model, but i think i did not understand how it works.
function y = fcn(u)
y =rand;
end
mardi 9 août 2022
Python random setState and getState to file
I am trying to save the current random generator state of application to replicate a lot of random action taken during the process.
import random
import pickle
from Model import Resnet
def main():
fileName = "09-08-2022T200803"
with open("data/" + fileName + ".txt", "rb") as rb:
data = pickle.load(rb)
random.setstate(data[0][0])
#data[0][0] is some saved seed object, the file is only appended, it is always the same object
myNetwork = Resnet.Network()
model = myNetwork.getModel()
playGame(model, 4, fileName)
Turn: 14, Action:251
Turn: 15, Action:33
Turn: 15, Action:186
Turn: 15, Action:16
GAME_FINISHED
However, when I close the program and run it again, the results differ:
Turn: 13, Action:251
Turn: 14, Action:29
Turn: 14, Action:251
Turn: 15, Action:33
GAME_FINISHED
Can it be done so I will keep the random generator state in file so I can debug the particular game that didn't work? (Game is 100% random as for now)
I have already tried to random.setstate()
just before game and run it several times in the same application(in a loop) and it did play exactly the same games, however - when I rerun(stop->run) the program, it did not work, results differed between application runs (probably because it was after Resnet.Network()
initialization)
The different approach which gave me exact the same results in one application run, but still different in between runs:
def main():
myNetwork = Resnet.Network()
model = myNetwork.getModel()
fileName = "09-08-2022T200803"
with open("data/"+fileName+".txt", "rb") as rb:
while True:
data = pickle.load(rb)
playGame(model, 4, fileName, data[0][0])
#data[0][0] is same object each time I read the file(that's how its saved), therefore it works in single application run
def playGame(model, simulations, fileName, seedObject = None):
if seedObject != None:
random.setstate(seedObject)
# ... game
Randomize Working Days of 24 workers for a Roster [closed]
I have the following problem:
I want to create a roster for a hospital where there are 24 doctor residents which have to decide who works which nights in a month. The idea is to randomize the solution with some constraints.
- There has to be at least "3" residents each night
- A resident must work at least "2" nights in the month
I have no idea how to create randomness, I want to build the code in Python as EXCEL doesn't accept more than 200 variables
Other ideas:
Giving different scores to days of the week or holiday nights and adding another constraint to SUM(score_Resident)
resampling dataframe/survey troubleshoot
I am having trouble resampling my dataframe. Need some help?
I have a household survey in country X. Country X is divided into 3000 counties of different population sizes. The % of sampled households varied by county size. Smaller counties were sampled at close to 100%. As the county grew in population the NUMBER of households increased but the PROPORTION dropped.
I want to readjust the proportion of sampled households to be the same across all counties (1.45%). I calculated how many households I need to include in my final dataframe.
household.prop <- data.frame(county.id=c(1001,1002,2001,2003),
total.households=c(201071,10007,12834,3465),
new.households=c(2916, 145, 186, 50))
county.id
is the county id; total.households
is the total number of households in the county; new.households
is the number of households I want to randomly sample from that county.
My second dataframe contains the household id for each household in the county. Note how ids are repeated across counties. Below is an example of what my dataframe looks like (there would be 201071 rows for county 1001, 10007 for 1002, 12834 for 2001, and 3465 for 2002).
household.ids <- data.frame(county.id=c(1001,1001,1001,1002,1002,1002),
household.id=c(100001,100002,100003,100001,100002,100003))
What is an efficient way to randomly sample the specified number of households from each county? In other words, I need to extract 2916 household ids from county 1001, 145 from 1002, 186 from 2001, and 50 from 2002.
Ideally, I would like a vector with unique ids (resampled.ids
) that I could use to filter my original dataset. As in:
total.data <- total.data %>%
filter(household.id %in% resampled.ids)
IMPORTANT: My dataset contains 10 million rows grouped in 3000 counties. The code needs to be efficient otherwise my PC will crash.
Thanks a bunch!
Pytorch: How to generate random vectors with length in a certain range?
I want a k
by 3
by n
tensor representing k
batches of n
random 3d vectors, each vector has a magnitude (Euclidean norm) between a
and b
. Other than rescaling the entries of a random kx3xn
tensor to n
random lengths in a for loop, is there a better/more idiomatic way to do this?
How do restrict the number of inputs and turn int into lists Python
I am trying to restrict the user input for the lottery tickets to seven characters and for it to only accept integers, when I use the int(input) it gives me a ValueError. When I remove the int before the input it works fine. I then go onto change the input into a list by using split method. How do I do restrict the inputs?
import random
number_choice = int(input("Input 7 lottery numbers between 1 and 100"))
lottery_ticket = number_choice.split()
print(type(lottery_ticket))
random_nums = random.sample(range(1, 100), 7) # generate a list of random numbers
print(lottery_ticket)
print(random_nums)
matches = set(lottery_ticket).intersection(random_nums) # set.intersection matches the elements that are similar
print("The matching numbers are", matches)
def matchingNumber():
countMatches = sum(i in random_nums for i in lottery_ticket)
print(countMatches)
if countMatches == 2:
print("You have won £5")
elif countMatches == 3:
print("you have won £20")
elif countMatches == 4:
print("you have won £40")
elif countMatches == 5:
print("you have won £100")
elif countMatches == 6:
print("you have won £10,000")
elif countMatches == 7:
print("you have won £1000000")
else:
print("You have won nothing!")
matchingNumber()
Generating "Non-Random" Numbers in R?
I know how to generate 100 random numbers in R (without replacement):
random_numbers = sample.int(100, 100, replace = FALSE)
I was now curious about learning how to generate 100 "non random" numbers (without replacement). The first comes to mind is to generate a random number, and the next number will be the old number + 1 with a probability of 0.5 or an actual random number with probability 0.5. Thus, these numbers are not "fully random".
This was my attempt to write this code for numbers in a range of 0 to 100 (suppose I want to repeat this procedure 100 times):
library(dplyr)
all_games <- vector("list", 100)
for (i in 1:100){
index_i = i
guess_sets <- 1:100
prob_i = runif(n=1, min=1e-12, max=.9999999999)
guess_i = ifelse(prob_i> 0.5, sample.int(1, 100, replace = FALSE), guess_i + 1)
guess_sets_i <- setdiff(guess_sets_i, guess_i)
all_games_i = as.list(index_i, guess_i, all_games_i)
all_games[[i]] <- all_games_i
}
all_games <- do.call("rbind", all_games)
I tried to make a list that stores all guesses such that the range for the next guess automatically excludes numbers that have already been guessed, but I get this error:
Error in sample.int(1, 100, replace = FALSE) :
cannot take a sample larger than the population when 'replace = FALSE'
Ideally, I am trying to get the following results (format doesn't matter):
index_1 : 5,6,51,4,3,88,87,9 ...
index_2 77,78,79,2,65,3,1,99,100,4...
etc.
- Can someone please show me how to do this? Are there easier ways in R to generate "non-random numbers"?
Thank you!
Note: I think an extra line of logic needs to be added - Suppose I guess the number 100, after guessing the number 100 I must guess a new random number since 100+1 is not included in the original range. Also, if I guess the number 5, 17 then 4 - and after guessing 4, the loop tells me to guess 4+1, this is impossible because 5 has already been guessed. In such a case, I would also have to guess a new random number?
lundi 8 août 2022
How to ensure that all rows or columns are shifted while shuffling the tensor?
Now I need to randomize an existing tensor of m*m and make sure all rows or columns will not stay in the original position, the shuffle() function provided by python can only achieve the randomization function, but can not guarantee that all elements are moved. Alternatively, a diagonal matrix can be randomly disordered to ensure that there are no zeros on the diagonal and that element 1 appears only once in each row and column, and multiplying this matrix with the original matrix will also achieve the above function, but how to generate such a matrix is also a problem. If anyone knows how to solve this problem, please reply to me, I would be very grateful!
how to display image randomly inside for loop in php
i have a simple webpage where i am trying to echo multiple images, my code is like below
<?php for($l=1;$l<=45;$l++){?>
<div class="thumb" style="background-image: url(l<?=$l?>.jpg);"></div>
<?php } ?>
so here the images are displayed fine in an order from 1 to 45, but what i want is images to display randomly everytime the page is loaded, can anyone please tell me how to accomplish this, thanks in advance
dimanche 7 août 2022
Actual random numbers in JS
I'm probably missing something here, and I'd like to know what, but it seems to me that generating unique numbers in JS is about the easiest thing in the world. Honestly I expect to get punked hard on this, but doesn't this generate an irrefutably unique number (of reasonable length)?
function getRandom() {
let date = new Date(),
time = date.getTime();
console.log(time * Math.random());
}
How can I create a random 2d array in Haskell?
I am fairly new to Haskell and I'm always confused when it comes to dealing with random values. This time I'm trying to create a 5x5 2d-array in which every cell contains a random value between 4 options.
data Content = Bomb | One | Two | Three deriving (Eq, Show)
data Board = Array (Int, Int) Cell
data Cell = Cell {
content :: Content,
state :: CellState,
notes :: Notes
}
type Notes = [String]
type CellState = Bool
then in the main function I typed
main :: IO()
main = do
let cellMatrix = createMatrix
print cellMatrix
How can I create a function that creates a Board, and where do I need to do all the g<-newStdGen stuff?
Any advice would be greatly appreciated!
Android studio: how to create a random number just once?
I'm a beginner and I can't find a java tutorial, I want my application to generate sentences and some random line of code that executes only once.
Random generator = new Random();
int number = generator.nextInt(5) + 1;
switch (number) {
case 1:
....
break;
case 2:
....
break;
....
}
Replicating MATLAB's `randperm` in NumPy
I want to replicate MATLAB's randperm()
with NumPy.
Currently, to get randperm(n, k)
I use np.random.permutation(n)[:k]
. The problem is it allocates an array of size n
then takes only k
entries of it.
Is there a more memory efficient way to directly create the array?
Why is my code generating enemies above the enemy count limit? [closed]
I am making a game, and I've set the game to generate two enemies at a random y position and once they are shot, regenerate them but in a different y position, but my code sometimes generates a third enemy, and after that a fourth, and it continues, but there is no specific pattern I can notice that might be causing that issue. I will show you my code, please point out any issues / improvements that could fix this issue.
import pygame
pygame.init()
pygame.mixer.init()
import random
gunshot = pygame.mixer.Sound("audio/gunshot.wav")
music = pygame.mixer.music.load("audio/music.mp3")
click = pygame.mixer.Sound("audio/click.wav")
hit = pygame.mixer.Sound("audio/hit.wav")
deathsound = pygame.mixer.Sound("audio/deathsound.wav")
pygame.mixer.music.set_volume(0.05)
gunshot.set_volume(0.07)
click.set_volume(0.3)
hit.set_volume(0.1)
deathsound.set_volume(0.3)
pygame.mixer.music.play(-1)
sw = 400
sh = 400
screen = pygame.display.set_mode((sw,sh))
pygame.display.set_caption("gonnagiveanamelater")
running = True
bg = pygame.image.load("graphics/bg.png")
player = pygame.image.load("graphics/player.png")
clock = pygame.time.Clock()
bullets = []
enemies = []
enemyy = 50
enemy2y = 350
pygame.display.set_icon(player)
score = 0
class enemy():
def __init__(self, x, y, sid):
self.x = x
self.y = y
self.id = sid
self.enemysurf = pygame.image.load("graphics/enemy.png")
self.enemyrect = self.enemysurf.get_rect(center=(self.x, self.y))
def draw(self):
screen.blit(self.enemysurf, self.enemyrect)
class bullet():
def __init__(self, sp):
self.x = 30
self.y = sp
self.bulletsurf = pygame.image.load("graphics/bullet.png")
self.bulletrect = self.bulletsurf.get_rect(center=(self.x, self.y))
def draw(self):
screen.blit(self.bulletsurf, self.bulletrect)
while running:
clock.tick(60)
pos = pygame.mouse.get_pos()
screen.blit(bg, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if len(bullets) <= 4:
bullets.append(bullet(event.pos[1]))
gunshot.play()
else:
click.play()
for bulllet in bullets:
bulllet.bulletrect.x += 3
bulllet.draw()
if bulllet.bulletrect.midright[0] >= 365:
bullets.remove(bulllet)
if len(enemies) <= 2:
if enemyy - enemy2y <= 100:
enemyy = random.randint(50,350)
else:
enemies.append(enemy(370, enemyy, 1))
enemies.append(enemy(370, enemy2y, 2))
else:
pass
for bllet in bullets:
for enmy in enemies:
if bllet.bulletrect.colliderect(enmy.enemyrect):
hit.play()
score += 1
enemies.remove(enmy)
if enmy.id == 1:
enemyy = random.randint(50, 350)
if enmy.id == 2:
enemy2y = random.randint(50, 350)
playerrect = player.get_rect(center=(30, pos[1]))
screen.blit(player, playerrect)
for enmy in enemies:
enmy.draw()
pygame.display.update()
Java Library for JasperReports - Random font size and styling issue in massive report generation
I am using JasperReport in my recent Java project for PDF generation purpose. It's working perfectly most of the time, but somehow in a few of the output PDFs(maybe 1 out of 5000), we saw that some of the contents are having weird font size and style (sometime smaller, sometime missing and sometime losing all the added text styles).
We've built multiple services in parallel for the huge amount of PDFs creation, and will generate roughly 150 PDFs per minute in one single service.
Also, we've already checked the output .jrxml files and the data parameters in debug mode. The abnormal PDFs look just the same with the normal one. The behaviors seems completely random and non-sense to me.
I've spent lots of time on it but still no lucks... Does anyone face the same issues with jasper reports or have any clues, and please let me know if there's anything unclear, I will be very appreciated for any help, thanks so much!!!!!
samedi 6 août 2022
Keying either individual letters or an entire word into hangman game
I am currently creating a hangman game for a project. I have managed to code where a user can enter individual letters to guess the secret word. However, I am having trouble adding an additional feature where the user can guess the entire word upfront.
below is my code attempt, may I know what to write to have this new feature in my game?
def game_play():
word = random.choice(WORDS)
# Dashes for each letter in each word
current_guess = "-" * len(word)
# Wrong Guess Counter
wrong_guesses = 0
# Used letters Tracker
used_letters = []
while wrong_guesses < MAX_WRONG and current_guess != word:
print (HANGMAN[wrong_guesses])
print ("You have used the following letters: ", used_letters)
print ("So far, the word is: ", current_guess)
guess = input ("Enter your letter guess:")
guess = guess.upper()
# Check if letter was already used
while guess in used_letters:
print ("You have already guessed that letter", guess)
guess = input ("Enter your letter guess: ")
guess = guess.upper()
# Add new guess letter to list
used_letters.append(guess)
# Check guess
if guess in word:
print ("You have guessed correctly!")
# Update hidden word with mixed letters and dashes
new_current_guess = ""
for letter in range(len(word)):
if guess == word[letter]:
new_current_guess += guess
else:
new_current_guess += current_guess[letter]
current_guess = new_current_guess
else:
print ("Sorry that was incorrect")
# Increase the number of incorrect by 1
wrong_guesses += 1
# End the game
if wrong_guesses == MAX_WRONG:
print (HANGMAN[wrong_guesses])
print ("You have been hanged!")
print ("The correct word is", word)
else:
print ("You have won!!")
game_play()
How to print each item in the dictionary randomly without repeating? [duplicate]
How could I print each question from the dictionary randomly without repeating?
Every time I run this command, I get repeated questions.
import random
capitals = {
"Canada": "Toronto",
"Spain": "Madrid",
"Germany": "Berlin",
"Belgium": "Brussels",
"Australia": "Sydney",
}
for country, capital in capitals.items():
country = random.choice(list(capitals.keys()))
capital = capitals[country]
question = input(f"What is the capital of {country}? : ")
if question == capital:
print("Congratulations!\n")
else:
print(f"Wrong! The correct answer: {capital}\n")
The questions of the quiz game not appearing [closed]
I have made a scratch quiz game. There I included 5 backdrops as questions. I have incorporated the random block in my code. But out of all 5 only 4 questions appear when I play and the other question that is the last one that is supposed to appear, does not. Instaed i see the starting page with my options for each question(they have been added as sprites)
Random matrix with sum of values by column = 1 in python
Create a matrix like a transtision matrix How i can create random matrix with sum of values by column = 1 in python ?
vendredi 5 août 2022
Best way to fill a vector with random 0 and 1 in C++ [closed]
I'm trying to fill a vector of (UserInputSize)
with random 0 and 1. I found so many ways to generate random numbers but I'm not really sure which one is best and functional for my case. It sounds like a silly question but it ended up being more complicated than i anticipated. I tried using rand()%2
or std::generate
and std::generate_n
but i couldn't really figure it out (I'm new to C++ i tried looking up some doc but didn't manage to make it work).
i tried :
std::vector<int> GridAsList(GridSizeValue*GridSizeValue);
std::generate_n(std::back_inserter(GridAsList), (GridSizeValue*GridSizeValue), rand()%2);
but i get a "'__gen' cannot be used as a function" error which seems to come from the compiler ? I'm not really sure
jeudi 4 août 2022
How to improve Thompson Sampling algorithm?
The below works when the only two values for the data being sampled are 0 and 1. How do I change the code so that it works for normal distributions with different means?
import random
import pandas as pd
import matplotlib.pyplot as plt
data = {}
observations = 200
data['B1'] = [random.randint(0,1) for x in range(observations)]
data['B2'] = [random.randint(0,1) for x in range(observations)]
data['B3'] = [random.randint(0,1) for x in range(observations)]
data['B4'] = [random.randint(0,1) for x in range(observations)]
data['B5'] = [random.randint(0,1) for x in range(observations)]
data = pd.DataFrame(data)
data.head(10)
machines = 5
machine_selected = []
rewards = [0] * machines
penalties = [0] * machines
total_reward = 0
for n in range(0, observations):
bandit = 0
beta_max = 0
for i in range(0, machines):
beta_d = random.betavariate(rewards[i] + 1, penalties[i] + 1)
if beta_d > beta_max:
beta_max = beta_d
bandit = i
machine_selected.append(bandit)
reward = data.values[n, bandit]
if reward == 1:
rewards[bandit] = rewards[bandit] + 1
else:
penalties[bandit] = penalties[bandit] + 1
total_reward = total_reward + reward
print("Rewards By Machine = ", rewards)
print("Total Rewards = ", total_reward)
plt.bar(['B1','B2','B3','B4','B5'],rewards)
plt.show()
I tried changing the code segment
if reward == 1:
rewards[bandit] = rewards[bandit] + 1
else:
penalties[bandit] = penalties[bandit] + 1
to rewards[bandit] = rewards[bandit] + reward
, but that did not work. Any help would be greatly appreciated.
Are there any java.util.random seeds with bad/weird properties?
I'm curious if there are seeds for java.util.random which have weird/surprising properties. This has little practical use, but I'm still curious.
PHP add css class to element randomly using php
let's say I have a array with e.g. 3 css class names - I also have a loop of e.g. 50 items and I'd like to randomly assign one of the three classes to an element - however, most of the items should not get any class at all - is there a way to do this?
to make it more clear - I'd like to set up a tiled gallery in Wordpress using css grid - every few picture I'd like to either add a class: big, wide, or tall - a gallery can have any number of pictures. thank you in advance for your input.
Why can I not use the MAX and MIN values of f32 and f64 in a call to rand::rngs::ThreadRng::gen_range() in Rust
I have a utility I've written to generate dummy data. For example, you might write:
giveme 12000 u32
... to get an array of 12000 32-bit unsigned integers.
It is possible to set a maximum and/or minimum allowed value, so you might write:
giveme 100 f32 --max=155.25
If one or the other is not given, the programme uses type::MAX
and type::MIN
.
With the floating point types, however, one cannot pass those values to rand::rngs::ThreadRng::gen_range()
.
Here is my code for the f64:
fn generate_gift(gift_type: & GiftType,
generator: &mut rand::rngs::ThreadRng,
min: Option<f64>,
max: Option<f64>) -> Gift
{
match gift_type
{
...
GiftType::Float64 =>
{
let _min: f64 = min.unwrap_or(f64::MIN);
let _max: f64 = max.unwrap_or(f64::MAX);
let x: f64 = generator.gen_range(_min..=_max);
Gift::Float64(x)
},
}
}
If one or both of the limits is missing for floating point, 32 or 64-bit, then I get this error:
thread 'main' panicked at 'UniformSampler::sample_single: range overflow', /home/jack/.cargo/registry/src/github.com-1ecc6299db9ec823/rand-0.8.5/src/distributions/uniform.rs:998:1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
It is not obvious to me at all why this error arises. Can you shed any light upon it?
how can i create a random number between -100 to 200? in javascript [duplicate]
i need to create a random number -100 to 200: i can create a random number -100 to 100:
console.log(Math.ceil(Math.random() * 200) - 100); //this my code for -100 to 100
Shuffle a dictionary and list in unison?
I have a dictionary and list with same rows. I would like to shuffle the dictionary and list in unison that is with the same random seed.
test_dict = {3.0: deque([0.897, 24, 45]),
2.0: deque([0.0, 0.5, 56]),
9.0: deque([3.4, 0.9, 0.5])}
test_list = [deque([0.897, 24, 45]),
deque([0.0, 0.5, 56]),
deque([3.4, 0.9, 0.5])]
Is there a way to shuffle these two in the same order?
I tried the shuffle
function from:
from random import shuffle
from sklearn.utils import shuffle
Both ended up giving an error. Is there a easier way to do this?
Edit: Since the values in the dictionary and elements in the list are same, I was wondering if we could shuffle the list and reassign them to the keys in the dictionary.
mercredi 3 août 2022
I need to make this code Train id in Random integer between 100 and 200
enter image description here This is my Half of the Code, i need to make Train ID in random integer between 100 and 200