mardi 31 janvier 2023

Attempting to generate a random item from a list, use that item in the code, then generate a new item that is distinct from the first, repeate

I am making my first program, a "Quiz" that will generate a random street from a list of streets. Then, give you the option to view the street on google maps in a new window so the user can test their knowledge of the streets location. Then, ask if you want to see another street.
If you answer "y", it will go back to the beginning and generate another random street repeating the process.

I can make this whole thing loop through just fine, except it lists the first street result again the second time through the loop. I wish to have a new distinct random street every time the loop is repeated.

I can fix this problem by not assigning the random.choice function to a variable, however when I do this, the google maps opens up in a new window with a distinct street that is different from the one generated. (I use the variable answer_street to allow the printed street and google maps to be the same variable.)

I am stuck. Thank you in advance for your advice as I am just starting out here and look forward to learning this.

import random
import webbrowser

street_list = ["street1", "street2", "street3", "street4"]

#store the randomly generated street to be used later in the code by assigning a variable
answer_street = random.choice(street_list)

#create a function to display the random street name
def random_street():
    print(answer_street)
    
#Define strURL as a variable, the value is the link for the google maps of the street that was previously generated
strURL = "https://www.google.com/maps/place/" + answer_street + ",+City,+State"

#Define a function to ask user if they want to see the street in google maps
#Then if yes, open google maps
def view_map():
    user_action = input("Do you want to see the street in Google Maps? (Y/N):\n")
    possible_actions = ["y", "n"]
    if user_action == "y":
        webbrowser.open(strURL, new=2)

def play_again():
    see_another = input("Would you like to see another random street? (Y/N):\n")
    possible_actions = ["y", "n"]
    if see_another == "y":
        random_street()
        view_map()
        play_again()
    else:
        print("Stay classy!")
        
        
random_street()  

view_map()

play_again()



Do I use random randint or random choice to random click on the list?

enter image description here

For the picture below, I wish to perform an automation testing which is random click on the items and save it. But i wonder which function do i use. Thanks for those who willing to help!

Selenium Python




How do I ensure that the same error response is never repeated twice in a row

I have a program that emulates a small translation program and I'm trying to figure out how would I go about making the error responses not repeat itself twice in a row (e.g the response "I don't know this word, sorry." can be explicitly stated right after when there is a failure to translate a word).

public void fillErrorResponses() {
        // Adding responses to be used if no translation was found.
        errorResponses.add("I am sorry but I do not know how to translate this.");
        errorResponses.add("I don't know this word, sorry.");
        errorResponses.add("Are you sure that this is a word?");
        errorResponses.add("This cannot be translated.");
    }

    public String getErrorResponse() {

        // Pick a random number for the index in the error response list.
        // The number will be between 0 (inclusive) and the size of the list (exclusive).
        int idx = rnd.nextInt(errorResponses.size());
        return errorResponses.get(idx);

At the moment, when a word that a user inputs cannot be translated, it will provide a random error response but still allows for that same error response to be displayed directly after it being used, for example:

Please, type in a single word to translate it.
> gah
I don't know this word, sorry.
> gah
I am sorry but I do not know how to translate this.
> gah
I am sorry but I do not know how to translate this.

How do i make it so that it doesn't show the same response twice in a row when a user inputs word that cannot be translated?




How to shuffle big JSON file?

I have a JSON file with 1 000 000 entries in it (Size: 405 Mb). It looks like that:

[
  {
     "orderkey": 1,
     "name": "John",
     "age": 23,
     "email": "john@example.com"
  },
  {
     "orderkey": 2,
     "name": "Mark",
     "age": 33,
     "email": "mark@example.com"
  },
...
]

The data is sorted by "orderkey", I need to shuffle data.

I tried to apply the following Python code. It worked for smaller JSON file, but did not work for my 405 MB one.

import json
import random

with open("sorted.json") as f:
     data = json.load(f)

random.shuffle(data)

with open("sorted.json") as f:
     json.dump(data, f, indent=2)

How to do it?

UPDATE:

Initially I got the following error:

~/Desktop/shuffleData$ python3 toShuffle.py 
Traceback (most recent call last):
  File "/home/andrei/Desktop/shuffleData/toShuffle.py", line 5, in <module>
    data = json.load(f)
  File "/usr/lib/python3.10/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/usr/lib/python3.10/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.10/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 403646259 (char 403646258)

Figured out that the problem was that I had "}" in the end of JSON file. I had [{...},{...}]} that was not valid.

Removing "}" fixed the problem.




lundi 30 janvier 2023

Trying to use random number generator in a coin flip program in C

Hello i'm trying to create a program where it counts the number of heads and tails in a coin flip simulator based on the number of coin flips the user inputs. The issue with this is that when i'm trying to count the number of heads and tails then increment them, it gives me just a random number and not within the range of flips given.

This is a sample output of my error

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 1804289393
Number of tails: 846930886

Instead I want it to count it like this:

Coin Flip Simulator
How many times do you want to flip the coin? 10
Number of heads: 7
Number of tails: 3

Here's the program :

#include <stdio.h>
#include "getdouble.h"
#include <time.h>
#include <stdlib.h>

int main(void) {
  printf("Coin Flip Simulator\n");
  printf("How many times do you want to flip the coin? ");
  int numFlip = getdouble();
  if(numFlip == 0 || numFlip < 0) {
    printf("Error: Please enter an integer greater than or equal to 1.\n");
  }
  int i = 0;
  int numHead = rand();
  int numTails = rand();
  for (i = 0; i < numFlip; i++) {
    
    if(numFlip%2 == 0) {
      numHead++;
    }
    else {
      numTails++;
    }
  }
  printf("Number of heads: %d\n", numHead);
  printf("Number of tails: %d\n", numTails);
  
  return 0;
} 

Thanks for the suggestions, it's my first time trying to use the random number generator.




How to make sample from table to stay all 1 in some column and randomly select 0 in SAS Enterprise Guide?

I have table in SAS Enterprise Guide like below:

Input data:

Size of table: 500 000 rows, 10 columns

  • 3 000 as 1 in "COL1"

  • 497 000 as 0 in "COL1"

    COL1 COL2 ... COLn
    1 XX ... ...
    0 YY ... ...
    0 YY ... ...
    1 UUU ... ...
    ... ... ... ...

Requirements: I need to create sample of this table with 100 000 observations where:

  • I will have all rows with 1 in "COL1" (3 000) and rest randomly selected 97 000 observations with 0 in "COL1"

Desire output:

Size of table: 100 000 rows, 10 columns

  • 3 000 as 1 in "COL1"

  • 97 000 as 0 in "COL1"

    COL1 COL2 ... COLn
    1 XX ... ...
    0 YY ... ...
    0 YY ... ...
    1 UUU ... ...
    ... ... ... ...

How can I do that in SAS Enterprise Guide or PROC SQL ?




Beautifulsoup. Result long random string

I am learning web scraping, however, I got issue preparing soup. It doesn't even look like the HTML code I can see while inspecting the page.

import requests
from bs4 import BeautifulSoup

URL = "https://www.mediaexpert.pl/"

response = requests.get(URL).text
soup = BeautifulSoup(response,"html.parser")

print(soup)

The result is like this:Result, soup

I tried to search the whole internet, but I think I have too little knowledge, for now, to find a solution. This random string is 85% of the result.

I will be glad for every bit of help.




moviepy using a ton of memory (Process finished with exit code 137 (interrupted by signal 9: SIGKILL))

for some reason this basic code takes a ton of memory then does Process finished with exit code 137 (interrupted by signal 9: SIGKILL)

from moviepy.editor import *
import os
from random import randint, choice


def combineclips(mainvid,meme,t):
    clip1 = VideoFileClip(mainvid)
    clip = VideoFileClip(meme)
    return CompositeVideoClip([clip1, clip.set_position((randint(40,1040),randint(200,1720))).resize(250,250).set_start(t)])


for i in range(0,1):
    m = choice(os.listdir("memes/"))
    finalclip = combineclips(f"video/{i}.mp4",f"memes/{m}",i+3)
    finalclip.write_videofile(f"meme{i}.mp4")


It also dose not write the video at the end. I think I'm doing many things wrong here

I have tried not putting the clips in videofileclip format but that just makes it a wrong type error even though it is an mp4. and its probably not even the issue I'm pretty stumped here




How to generate a set of numbers consisting of a certain number of numbers in C#?

I have to generate a set of numbers consisting of 5 numbers, as shown below. I tried to search some info about this but found nothing.

int playerId;

System.Random rand = new System.random();
for (int i = 0; i <= 5; i++)
{
     playerId = random.Next();
}
Console.Write($"Generating player ID: {playerId}");

// output example: Generating player ID:  1158453178

As a result, i got a set of numbers consisting of 10 numbers. How can i solve this problem?




samedi 28 janvier 2023

Python randint not working(not printing the answer) [duplicate]

I was working on a project when I realized that random.randint would not print out.
This is my code:

import random

random.randint(1,25)

In the shell it works, but when I put it into a new file it doesn't work (print/display output).
Does anyone know why? Thanks!




how to get my for loop to stop numbers from repeating more than twice, c++ [duplicate]

I made a card game where its a matching game using 6 cards.the cards are hard coded in place and I have the values set to random between the 6 cards, Im not sure how to make it so it displays 2 of each of the cards for the game. Right now when I run it, the 12 cards pop up all with random values, sometimes repeating multiple times. Any help would be appreciated.

 void randomize(int arr[], int size)
 {
 srand(time(0));
 for (int n = 0; n < size; n++)
     {
 int random = rand() % 6;
 arr[n] = random;
     }

I'm thinking i'll need a counter variable and maybe adding a while statement so that when counter >= 2 it won't repeat, but im not advanced enough to figure out how to write the logic of it.

 void main ()
 {
 const unsigned int size = 12; 
 int cardValues[size];
 randomize(cardValues, size);
 }

I'm trying to write a for loop with a nested while statement, and using a counter variable to keep track of how many times a number is used and set it <= 2 but I'm not sure how to write it out.




In what scope and how should a std::random_device be defined?

I want to run two concurrent threads both of which call a function (e.g. void channel()) and that function needs access to a few objects namely a std::random_device, a PRNG engine, and two std::uniform_int_distribution objects. However I am not sure where I should define each of these objects. 3 different options come to my mind:

  1. Globally
  2. Inside the channel function as thread_local (this one seems more natural to me)
  3. In the body of each of thread functions (i.e. thread1 and thread2) as automatic variables.

Which one is the most efficient and least problematic? And is there any other option that might be better?

Here's an MRE (link):

#include <chrono>
#include <random>
#include <thread>
#include <fmt/core.h>
#include <fmt/std.h>

using std::chrono_literals::operator""ms;

// globally defined
// extern thread_local std::random_device rand_dev;
// extern thread_local std::random_device rand_dev { };

void
channel( /*std::mt19937& mtgen*/ )
{

    // inside the function as thread_local
    thread_local std::random_device rand_dev { };
    thread_local std::mt19937 mtgen { rand_dev( ) };
    thread_local std::uniform_int_distribution uniform_50_50_dist { 1, 2 };

    if ( uniform_50_50_dist( mtgen ) == 1 )
    {
        thread_local std::uniform_int_distribution<size_t> uniform_dist_for_bit_select { 0, 10 };
        const auto random_index { uniform_dist_for_bit_select( mtgen ) };

        std::this_thread::sleep_for( 100ms );
        fmt::print( "thread: {} produced {}\n", std::this_thread::get_id( ),
                                                random_index );
    }
}

void thread1( )
{
    // inside the actual thread as automatic storage duration
    // std::random_device rand_dev { };
    // std::mt19937 mtgen { rand_dev( ) };

    for ( size_t count { }; count < 10; ++count )
    {
        channel( /*mtgen*/ );
    }
}

void thread2( )
{
    // inside the actual thread as automatic storage duration
    // std::random_device rand_dev { };
    // std::mt19937 mtgen { rand_dev( ) };

    for ( size_t count { }; count < 5; ++count )
    {
        channel( /*mtgen*/ );
    }
}

int main( )
{
    std::jthread th1 { thread1 };
    std::jthread th2 { thread2 };
}

Now I may have to mention that I want each thread to have a separate std::random_device and a separate std::mt19937 engine so that I don't have to share them between threads (because that way I'll have to synchronize them using e.g. mutexes). Although I guess using a single std::random_device is possible by locking its mutex with a std::scoped_lock before accessing it via its call operator().




I have a random Number Generator that uses a XOR shift algorithm, using a global variable. Is there another method to accomplish this?

so I built this "Random" number Generator, and it works exactly like its supposed to. But I feel like the use of a Global variable in this way is cursed, and there must be a better way of accomplishing the same thing. Thanks in Advanced.

unsigned int State = 1804289383;
unsigned int get_random_U32_number() {
    unsigned int Number = State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    State = Number;
    return Number;
}

Not sure what else to try, I can't use any built like function like rand() for this project.




vendredi 27 janvier 2023

How to extract random element from an array - Node.js [duplicate]

I am doing a project in JS and Node.js and I need to extract a random element from my array and then display it.

// enemies.js
const enemies = [
  "Wizard Monster",
  "Ice Golem",
  "Electro Dragon",
  "Fire Giant",
  "Rahzar Mutant",
]
export default enemies

// fight.js
import enemies from "../utils/enemies.js"

// Code here

Any ideas ?

Thanks in advance.




Random number generator with freely chosen period

I want a simple (non-cryptographic) random number generation algorithm where I can freely choose the period.

One candidate would be a special instance of LCG:

X(n+1) = (aX(n)+c) mod m (m,c relatively prime; (a-1) divisible by all prime factors of m and also divisible by 4 if m is).

This has period m and does not restrict possible values of m.

I intend to use this RNG to create a permutation of an array by generating indices into it. I tried the LCG and it might be OK. However, it may not be "random enough" in that distances between adjacent outputs have very few possible values (i.e, plotting x(n) vs n gives a wrapped line). The arrays I want to index into have some structure that has to do with this distance and I want to avoid potential issues with this.

Of course, I could use any good PRNG to shuffle (using e.g. Fisher–Yates) an array [1,..., m]. But I don't want to have to store this array of indices. Is there some way to capture the permuted indices directly in an algorithm?

I don't really mind the method ending up biased w.r.t choice of RNG seed. Only the period matters and the permuted sequence (for a given seed) being reasonably random.




Difference drawing random numbers from distributions R [migrated]

I am comparing these two forms of drawing random numbers from a beta and a Gaussian distribution. What are their differences? Why are they different?

The first way (_1) simulates from a Uniform(0,1) and then applies the inverse CDF of the Beta (Normal) distribution on those uniform draws to get draws from the Beta (Normal) distribution.

While the second way (_2) uses the default function to generate random numbers from the distribution.

Beta Distribution

set.seed(1)
beta_1 <- qbeta(runif(1000,0,1), 2, 5)
set.seed(1)
beta_2 <- rbeta(1000, 2,5)

> summary(beta_1); summary(beta_2)
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
0.009481 0.164551 0.257283 0.286655 0.387597 0.895144 
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
0.006497 0.158083 0.261649 0.284843 0.396099 0.841760  

Here every number is different.

Normal distribution

set.seed(1)
norm_1 <- qnorm(runif(1000, 0,1), 0, 0.1)
set.seed(1)
norm_2 <- rnorm(1000, 0, 0.1)

> summary(norm_1); summary(norm_2)
      Min.    1st Qu.     Median       Mean    3rd Qu.       Max. 
-0.3008048 -0.0649125 -0.0041975  0.0009382  0.0664868  0.3810274 
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
-0.300805 -0.069737 -0.003532 -0.001165  0.068843  0.381028

Here the numbers are almost the same except in the mean and median

Shouldn't all be equal? Because I am generating random numbers from distributions with the same parameters




Draw function and replace elements with letters

The idea is to create simple hangman game, in which while you choose a given category and click new word button, the corresponding random word from the given list will be displayed (as underscores). Then, if letter matches letter present in this word, it will be revealed, if not, the consecutive element of hangman will be drawn.

But I have no clue now how to implement further these onto the project. How to create a function which will generate a word randomly on the background, and if chosen letter is not there, make it draw something, or if it is present in the word, change underscore with this letter?

I wanted to create a code which will allow to play hangman game described in the topic. I can't find solution for creating the code which will replace underscores with letters, and draw elements on the background if a given letter is not there.

let background;
let width, heigth, margin;
let animals, plants, clothes;
let lives;
let chosenCategory;
let word;

function initialize() {
  background = document.getElementById("background").getContext("2d");
  width = document.getElementById("background").width;
  height = document.getElementById("background").height;
  margin = 25;
  lives = 10;
  word = "nothing";
  animals = ["horse", "elephant", "squirell"];
  plants = ["pineapple", "tomato", "lettuce"];
  clothes = ["trousers", "shirt", "skirt"];
}

function drawLetters() {
  for (let i = 0; i < word.length; i++) {
    background.fillRect(i * ((width * 0.9) / word.length) + margin, height / 2, 30, 5);
  }
}

function randomWord() {
  chosenCategory = document.getElementById("category").value;
  if (chosenCategory == "animals") {
    word = animals[Math.floor(Math.random() * animals.length)];
  } else if (chosenCategory == "plants") {
    word = plants[Math.floor(Math.random() * plants.length)];
  } else if (chosenCategory == "clothes") {
    word = clothes[Math.floor(Math.random() * clothes.length)];
  }
}

function checkLetter(letter) {
  if (word.includes(letter)) {
    drawLetter(letter);
  }

}



function drawLetter(letter) {
  background.font = "30px Arial";
  background.fillText(letter, word.indexOf(letter) * ((width * 0.9) / word.length) + margin, height / 2 - 10);
}
body {
  text-align: center;
  background-color: #8EB19D;
}

#background {
  background-color: azure;
  border: 3px solid black;
}

h1 {
  color: rgb(190, 220, 254);
  font-Size: 40px;
  height: 50px;
  text-align: center;
  font-family: Tahoma;
}

.container {
  font-size: 16px;
  background-color: #ffffff;
  width: 64vw;
  max-width: 32em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  padding: 3em;
  border-radius: 0.6em;
}

.letter-row {
  padding-top: 0.5em;
  padding-bottom: 0.5em;
}

.letter-container {
  height: 2.4em;
  width: 2.4em;
  border-radius: 0.3em;
  font-weight: bold;
  background-color: #ffffff;
  cursor: pointer;
}
<body onload="initialize()">
  <h1>Hangman</h1>
  <div class="container">
    <p>
      <select id="category">
        <option value="">Category</option>
        <option id="animals" option value="animals">Animals</option>
        <option id="plants" option value="plants">Plants</option>
        <option id="clothes" option value="clothes">Clothes</option>
      </select>
    </p>
    <canvas id="background" width="350" height="250">No canvas support</canvas>
    <div id="text-container">
      <div class="letter-row">
        <input class="letter-container" type="button" value="A" onclick="checkLetter('a')" />
        <input class="letter-container" type="button" value="B" onclick="checkLetter('b')" />
        <input class="letter-container" type="button" value="C" onclick="checkLetter('c')" />
        <input class="letter-container" type="button" value="D" onclick="checkLetter('d')" />
        <input class="letter-container" type="button" value="E" onclick="checkLetter('e')" />
        <input class="letter-container" type="button" value="F" onclick="checkLetter('f')" />
        <input class="letter-container" type="button" value="G" onclick="checkLetter('g')" />
        <input class="letter-container" type="button" value="H" onclick="checkLetter('h')" />
        <input class="letter-container" type="button" value="I" onclick="checkLetter('i')" />
      </div>
      <div class="letter-row">
        <input class="letter-container" type="button" value="J" onclick="checkLetter('j')" />
        <input class="letter-container" type="button" value="K" onclick="checkLetter('k')" />
        <input class="letter-container" type="button" value="L" onclick="checkLetter('l')" />
        <input class="letter-container" type="button" value="M" onclick="checkLetter('m')" />
        <input class="letter-container" type="button" value="N" onclick="checkLetter('n')" />
        <input class="letter-container" type="button" value="O" onclick="checkLetter('o')" />
        <input class="letter-container" type="button" value="P" onclick="checkLetter('p')" />
        <input class="letter-container" type="button" value="Q" onclick="checkLetter('q')" />
      </div>
      <div class="letter-row">
        <input class="letter-container" type="button" value="R" onclick="checkLetter('r')" />
        <input class="letter-container" type="button" value="S" onclick="checkLetter('s')" />
        <input class="letter-container" type="button" value="T" onclick="checkLetter('t')" />
        <input class="letter-container" type="button" value="U" onclick="checkLetter('u')" />
        <input class="letter-container" type="button" value="V" onclick="checkLetter('v')" />
        <input class="letter-container" type="button" value="W" onclick="checkLetter('w')" />
        <input class="letter-container" type="button" value="X" onclick="checkLetter('x')" />
        <input class="letter-container" type="button" value="Y" onclick="checkLetter('y')" />
        <input class="letter-container" type="button" value="Z" onclick="checkLetter('z')" />
      </div>
    </div>
    <p></p>
    <div>
      <button id="New Word" type="button" onclick="randomWord()">New Word</button>
      <input type="button" value="Draw Lines" onclick="drawLetters()" />
    </div>
    <div class="game-container">
      <svg height="250" width="200" class="figure-container">
                <line x1="60" y1="20" x2="140" y2="20" />
            </svg>

      <div class="wrong-letter-container">
        <div id="wrong-letters"></div>
      </div>
      <div class="word" id="word"></div>
    </div>

    <div class="popup-container" id="popup-container">
      <div class="popup">
        <h2 id="final-message"></h2>
      </div>
    </div>
  </div>
</body>



jeudi 26 janvier 2023

Using Javascript to randomly scroll and zoom through back camera of iPhone (Automated process)

Just to be clear I am really a beginner at coding, so the code is not really fine tuned:) I appreciate all the help I can get!

I am currently writing a code that is supposed to automate the process of scrolling and zooming through images. As an input image I want the 'program' to zoom (using the random factor) through the live video stream of the back camera of my iPhone. This is working to some extent, but there are some problems:

  1. the screen is black when I open the site in Safari on my iPhone (before it was working but
    the image was freezed)

  2. the video is not adapting its size to the browser

  3. the video is not fixed - sometimes it "flys" out of the frame and you see white boarders

  4. the transition is still quite fast, I would like that the steps between changing the random
    factor are smaller

  5. I wrote this to choose the back camera of my phone: video: { facingMode: 'environment' } })

  6. I thought 100vw in height in width would
    solve that

  7. this probably has something to do with the fact that the video element is the one being
    scaled -> there is no real "zoom in" effect.

I appreciate any hints on how to improve this:)

var video = document.querySelector("#videoElement");

if (navigator.mediaDevices.getUserMedia) {
  navigator.mediaDevices.getUserMedia({ video: true,
    video: {
      facingMode: 'environment'
    } })
    .then(function (stream) {
      video.srcObject = stream;

    })
    .catch(function (err0r) {
      console.log("Something went wrong!");
    });
}

root = document.documentElement;

// Function to set random x, y and scale values
// math.random () returns a random number between 0 (inclusive),  and 1 (exclusive):
// ganzzahlige Zufallswerte mit: math.floor()

function setRandomScaleAndPosition() {
    // calculate values
    var x = Math.floor(Math.random() * 100 - 50) // min = 0*100-50 => -50 ; max = 1*100-50 => 50
    var y = Math.floor(Math.random() * 100 - 50)
    var scale = 2 // Math.floor(Math.random() * 6 + 2)    //siehe css var scale 
    
    // display values in console
    console.log("new values:", x, y, scale)
    
    // set CSS variables
  root.style.setProperty('--translate-x', x + "%");
  root.style.setProperty('--translate-y', y + "%");
  root.style.setProperty('--scale', scale);
}

// run setRandomScaleAndPosition 
setInterval(setRandomScaleAndPosition, 600)
#container {
    padding:0;
    width: 100vw;
    height: 100vw;
    /* object-fit: cover;
    overflow: hidden;   */
}


 /* div {            
    height: 100vw;
    width: 100vw;
    overflow:hidden;   /*The overflow property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area.

} */

#videoElement {
    width:100vw;      /*If the width property is set to 100%, the video player will be responsive and scale up and down:*/
    height: 100vw;        
    object-fit: cover;
    transition-duration: 6s;
    transform: scale(var(--scale)) translateX(var(--translate-x)) translateY(var(--translate-y)); 
    outline: none; 
    overflow: hidden;
    
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Please help me find the truth</title>

<link rel="stylesheet" href="main.css">
</head>
 
<body>
<div id="container">
    <video muted autoplay="true" id="videoElement">
        
    
    </video>
</div>
<script src="main.js"></script>

</body>
</html>



Why does my simulation code not adding to the variables? [closed]

I'm very new to coding and I made this rock, paper, scissors game in python. The singleplayer and multiplayer works fine but the "simulation" mode doesn't give any results for player one wins or player 2 wins. The output would be:

Player 1 won 0 times. Player 2 won 0 times. There were x amount of ties.

There shouldn't be 0 wins for both player one and two.

There shouldn't be 0 wins for both player one and two.




How to generate random color dot on screen at x interval of time in Flutter

So I'm trying to make an app where when clicked on Play button random color dots start to appear on screen at any location but I can't get around to how to implement that in flutter any help would be appreciated.

I know that I need to use random class which is built-in method but how to generate color dots using that?

Btw one color should appear at a given time and next color should appear after X seconds

Below is an image attached to what kind of effect I want on pressing play button.




mercredi 25 janvier 2023

jax minimization with stochastically estimated gradients

I'm trying to use the bfgs optimizer from tensorflow_probability.substrates.jax and from jax.scipy.optimize.minimize to minimize a function f which is estimated from pseudo-random samples and has a jax.random.PRNGKey as argument. To use this function with the jax/tfp bfgs minimizer, I wrap the function inside a lambda function

seed = 100
key  = jax.random.PRNGKey(seed)
fun = lambda x: return f(x,key)
result = jax.scipy.optimize.minimize(fun = fun, ...)

What is the best way to update the key when the minimization routine calls the function to be minimized so that I use different pseudo-random numbers in a reproducible way? Maybe a global key variable? If yes, is there an example I could follow?

Secondly, is there a way to make the optimization stop after a certain amount of time, as one could do with a callback in scipy? I could directly use the scipy implementation of bfgs/ l-bfgs-b/ etc and use jax ony for the estimation of the function and of tis gradients, which seems to work. Is there a difference between the scipy, jax.scipy and tfp.jax bfgs implementations?

Finally, is there a way to print the values of the arguments of fun during the bfgs optimization in jax.scipy or tfp, given that f is jitted?

Thank you!




Randomize order of s or s with pure JS on page load

I saw multiple answers to randomize the order of <div> (or <li>s or whatever) using jQuery, but how do I do this using pure javascript?

<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
</ul>



Stratified random sampling (into 4 groups) from data frame with R

I have a data frame in the format

> head(daten_strat)
   id age gender anxiety
1   7  40      2       7
2   3  53      1       8
3   4  40      1       4
4   1  62      2       8
5   5  60      2      11
6   6  45      1       8

I would like to create 4 random groups that are as similar as possible in terms of the distribution of gender, age and anxiety.

I have already reviewed other questions and their answers here on stackoverflow. However, I could not apply them to my example. In addition, I have never done stratified randomization before. Therefore, I would be happy if someone could help me along. Many thanks in advance :)




mardi 24 janvier 2023

How to create a fake but realistic scatter plot showing a relationship?

I would like to generate some dummy data to show a positive relationship in a scatterplot.

I have some code below but the output looks too "perfect":

import random
import pandas as pd

# num_obs = number of observations
def x_and_y(num_obs): 
    
    x_list = []
    y_list = []
    for i in range(1,num_obs):
        
        # between 1 and 10,000
        x = round(random.randint(1,10000))
        
        y_ratio = random.uniform(0.15,0.2)
        # multiply each X by above ratio
        y = round(x*y_ratio)
        
        # add to list
        x_list.append(x)
        y_list.append(y)
    return x_list, y_list

# run function
x, y = x_and_y(500)

# add to dataframe and plot
df = pd.DataFrame(list(zip(x, y)),
               columns =['X', 'Y'])
df.plot.scatter(x='X', y='Y')

I get this very clean looking relationship:

enter image description here

Is there anything I can do to make it look more natural / scattered without losing the relationship?

Something like this (just a screenshot from google):

enter image description here




I cannot find the xpath for the radio button which should be random using selenium

I cannot find the XPath or the class name for the radio button which should select color randomly from the list using selenium in a google form(link). Other name, age, country, and email are working fine with the xpath. Every time getting an error comes up. Can anyone help me? Code is -

from selenium import webdriver
from faker import Faker
import random
driver = webdriver.Chrome()
driver.get("https://forms.gle/PL3W5TxZVVJHRa1W9")
faker = Faker()

colors = ["green", "blue", "black", "red"]


for i in range(20):
    name = faker.name()
    age = random.randint(18, 99)
    country = faker.country()
    email = faker.email()
    color = random.choice(colors)
    name_field = driver.find_element('xpath','//*[@id="mG61Hd"]/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input')
    name_field.send_keys(name)
    age_field = driver.find_element('xpath','//*[@id="mG61Hd"]/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input')
    age_field.send_keys(str(age))
    country_field = driver.find_element('xpath','//*[@id="mG61Hd"]/div[2]/div/div[2]/div[3]/div/div/div[2]/div/div[1]/div/div[1]/input')
    country_field.send_keys(country)
    email_field = driver.find_element('xpath','//*[@id="mG61Hd"]/div[2]/div/div[2]/div[4]/div/div/div[2]/div/div[1]/div/div[1]/input')
    email_field.send_keys(email)
    color_field = driver.find_element("class name",'//div[@class="mG61Hd"]')
    color_field.send_keys(color)


    submit_button = driver.find_element_by_css_selector("[type='submit']")
    submit_button.click()


driver.quit()



lundi 23 janvier 2023

how to deal with missing value in exposure variable

I am examining the effect of A on B. A is exposure variable and B is outcome variable.There are almost 16777 records in the dataset. Out of which 21 records have missing value in A. A is a binary variable with 1 and 2, and my director ask me to treat missing value as a value. Now, A has three value:1,0 and missing. however, i think missing value is scare and random. Shall i remove the observation with missing value?




Better alternatives to random_device in C++?

I have been using random_device rd{} to generate seeds for my Mersenne-Twister pseudo random number generator mt19937 RNG{rd()} as have been suggested here. However, it is written in the documentation (comment in the documentations' example code), that "the performance of many implementations of random_device degrades sharply once the entropy pool is exhausted. For practical use random_device is generally only used to seed a PRNG such as mt19937". I have tried testing how big this "entropy pool" is, and for 10^6 number of calls, random_device returns me more than 10^2 repeating numbers (see my example code and output below). In other words, if I will try using random_device as a seed to my Mersenne-Twister PRNG, it will generate a solid fraction of repeating seeds.

Question: do people still use random_device in C++ to generate seeds for PRNG or are there already better alternatives?

My code:

#include <iostream>
#include <random>
#include <chrono>

using namespace std;

int main(){
    
    auto begin = std::chrono::high_resolution_clock::now();
    
    random_device rd{};
    mt19937 RNG{ rd() };

    int total_n_of_calls = 1e6;
    vector<int> seeds;
    
    for(auto call = 0; call < total_n_of_calls; call++){
    int call_rd = rd();
    seeds.push_back(call_rd);
    }
    
    int count_repeats = 0;
    sort(seeds.begin(), seeds.end());
    for(int i = 0; i < seeds.size() - 1; i++) {
        if (seeds[i] == seeds[i + 1]) {
            count_repeats++;
    }
    }
    
    printf("Number of times random_device have been called: %i\n", total_n_of_calls);
    printf("Number of repeats: %i\n", count_repeats);

    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
    printf("Duration: %.3f seconds.\n", elapsed.count() * 1e-9);

    return 0;
}

The output:

Number of times random_device have been called: 1000000
Number of repeats: 111
Duration: 0.594 seconds.




dimanche 22 janvier 2023

Assigning numbers 0-8 randomly to a 3x3 keypad in Android Studio

I'd like to make a game that requires numbers 0-8 to be randomly assigned (once each) to a 3x3 keypad. The buttons are named button1 to button9.
enter image description here

I thought I could do this by creating an ArrayList (called "labels") with numbers 0 to 8.

I then used the following code to assign each number in the ArrayList to a button.

Collections.shuffle(labels);
   button1.setText(String.valueOf(labels.get(0)));


   ArrayList<Integer> eight = new ArrayList<>(labels);
   eight.remove(0);
   Collections.shuffle(eight);
   button2.setText(String.valueOf(eight.get(0)));

   ArrayList<Integer> seven = new ArrayList<>(eight);
   seven.remove(0);
   Collections.shuffle(seven);

   button3.setText(String.valueOf(seven.get(0)));
   

This pattern continues all the way down to button9.

At first, I just used the one array and deleted a number from it after assigning it, but the program crashed. That's why I tried copying each array into a new one before deleting a value, but that didn't seem to help either.

When I run the new code, the program also crashes. Does anyone know why?

I was able to randomly assign numbers to the buttons with the following code, but some numbers would appear more than once (and strangely, only even numbers appeared).

Collections.shuffle(labels);
   button1.setText(String.valueOf(labels.get(0)));
   Collections.shuffle(labels);
   button2.setText(String.valueOf(labels.get(0)));
   Collections.shuffle(labels);

... to Button9.

Can anyone explain what I've done wrong?

Thanks




samedi 21 janvier 2023

Modify this sub random number generator sub to exclude certain numbers

I'm new to Excel VBA. The project I'm working on deals with ranges of random numbers. I have five ranges and found this code which works really well for not getting any duplicates in a range:

Public Sub generateRandNum()
    'Define your variabiles
    lowerbound = 1
    upperbound = 20000
    Set randomrange = Range("A1:C5000")
    
    randomrange.Clear
    For Each rng1 In randomrange
        counter = counter + 1
    Next
    
    If counter > upperbound - lowerbound + 1 Then
        MsgBox ("Number of cells > number of unique random numbers")
        Exit Sub
    End If
    
    For Each Rng In randomrange
        randnum = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
        Do While Application.WorksheetFunction.CountIf(randomrange, randnum) >= 1
            randnum = Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
        Loop
        Rng.Value = randnum
    Next
End Sub

The next part of the project involves the excluding one number (not random) from the second set and two numbers (also not random) from the fourth set.

I've searched all over Google, looked at a number of forums, but either the code looks really long or I can't quite understand it enough to modify it for my needs.

It has to be in VBA because the number generator works off of a button click.




R function for finding mean of a population greater than a specific value

I’m currently learn R and I’ve hit a rock. How do I present the code for the proportion of the population taller than 15m. (Question 5 in the picture)number 5 question for a randomly generated sample in a dataset

Tried using a for loop but can figure out what to input for the vector. I’m expecting a cut of of values from 15m and above




Order random with seed. Postgresql + Sequelize

Why does PostgreSQL not support random(<seed>)?

In most dialects the following code works.

const randomSeed = 123;
return Story.findOne({ order: sequelize.fn('random', randomSeed) });

Is there a way to do a seeded random with sequelize & postgreSQL? or am i fucked and need to switch back to mySQL?




Repeating Cell Fill In Randomly Selected Rows

I want to auto-fill the text "SOLD" to column K in each row from a pre-chosen set of rows not necessarily in sequential order. For ex: I may select rows 1-3 & maybe rows 8 & 10. Upon selecting said rows, I want to run my macro to enter the text "SOLD" in each of them.

Here is my current macro, which works only on one row at a time:

Sub ItemSold()

Range("K" & ActiveCell.Row).Select
ActiveCell.FormulaR1C1 = "SOLD"
Rows(ActiveCell.Row).Select

End Sub

I assume there's a way to cycle through all of the selected rows with FOR EACH or maybe a REPEAT function/?




vendredi 20 janvier 2023

Opening Five Random Images From a File - Python

I am coding a Convolutional Neural Network that identifies Brown Tail Moth nests in trees. For the first part of my program, I want to import the image file with all of the pictures of the trees and pick five random images from that folder (just to see if it actually has the right folder with the images). However, when I click "run", it shows an error:

Traceback (most recent call last): File "C:\Users\eumel\AppData\Roaming\JetBrains\PyCharmCE2021.2\scratches\Final.py", line 20, in image = random.choice(os.listdir(test_folder)) NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\eumel\Downloads\Photos-001 (4).zip'

I'm not sure if I have the code right for this, but I don't know how to fix it and have it show the images.

Can anyone help?




Random pixel image generator [closed]

I was trying to create an app where when users sign up they are given a random user image just like in GitHub.

So I was just asking that is there any API or NPM that can generate that kind of image?




jeudi 19 janvier 2023

How do I generate pseudo random array?

I need to generate array from letters A,H,O,J and numbers 0-9. I want to generate letters into new array in order AHOJ. The individual characters can appear elsewhere in new array but always in AHOJ order and they dont need to follow each other. Remaining indexes of new array will be filled with digits. Examples - A123H85O2J3, AHOJ9854273, 012AH851OJ3 and so on. The order of AHOJ must not be randomized within new array. I have this code, but is probably completly wrong. It only works as expected when condition equal to 7 is met.

let letters = ['A','H','O','J'];
let newArray =new Array(11);
let lastIndex = 10;

for (let i = 0; i < letters.length; i++) {
    
    newIndex = Math.floor(Math.random() * lastIndex);
    console.log(newIndex);
    if (newIndex == 7) {
        for (let j = 0; j < letters.length; j++) {

            newArray.splice(j + 7,1,letters[j]);
        }
        for ( let k = 0; k < 7; k++) {
            newArray.splice(k,1,Math.floor(Math.random() * 10).toString());
        }
        break;
    }
    else if (newIndex > 7) {
        lastIndex = Math.floor(Math.random() * 6);
        newArray.splice(lastIndex,1,letters[i]);
    }
    else {
        newArray.splice(newIndex,1,letters[i]);
        
    }



    
    console.log(letters[i]);
}

console.log(newArray);



Random number always begins with 1

I want to generate a random number between 1,000 and 9,999 and convert the return value to string. Thus I have:

(Math.floor(Math.random() * 9999) + 1000).toString()

However, this always returns me a number that starts with one. What am I doing wrong? Also, if I want to return a number where the digits are not repeated and the range is from 1 to 9999, how do I modify the equation?

A random number that didn't begin with a 1.




mercredi 18 janvier 2023

How do I choose a random number from a list?

I am creating a number-guessing game where the player has to guess a randomly generated number but I don't know how to choose a random number.

I have a variable called truenumber which is equal to a list of numbers, what I want to do is make it randomly choose from the list and compare it to the user's input.

    int truenumber; 
    truenumber = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;

So how do I make it pick a random number from the list each time?

#include <iostream>
using namespace std;

int main() {
    
    string message = "Hello";
    cout << message << endl;
    cout << "Lets play a game" << endl;
    cout << "Try to guess the number!" << endl;
 
    int truenumber; 
    truenumber = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
    int number;
    cin >> number;

    if (number = truenumber) {   
        cout << "You got it right!" << endl;
    }
    else if (number > truenumber) {
        cout  << "Too high" << endl;
        cin >> number;
    }
    else (number < truenumber) {
        cout << "Too low" << endl;
        cin >> number;
    }
    
} 

I wasn't expecting this to work since truenumber doesn't have an actual value and I was trying to find a solution online but only found really complex solutions that didn't match my ideas.




Java random character generated then output in the text attribute of a TextView element in Android Studio

I am trying to get a random character generated from a String array and then set it as the text for a TextView element. Currently the IDE does not show any syntax or logic errors but the app crashes when run on my phone.

I have set the random generation to take place when the Start button is pressed.

public void startGame (View starGame) { //ISOLATE RANDOM FUNCTION TO SEE IF IT WORKED OR NOT
    String notesLevelOne = "ABCDEF";
    Random rnd = new Random();
    char note = notesLevelOne.charAt(rnd.nextInt(notesLevelOne.length()));
    TextView noteQuestion = findViewById(R.id.noteLetterTxt); //capture the textView "welcomeMessage" in Welcome layout
    noteQuestion.setText(note); //set message string as textView text
}

This is the code in the main activity and the button has the onClick set to startGame.




C++ Error 0xC0000094: Integer division by zero [closed]

Keep getting this error for an unhandled exception in my C++ function whenever I try to generate a random integer between 0 & the size of a vector.

relevant code:

std::string Mountains::getRandomMountain()
{
    int randomValue = 0;
    string randomMountain;

    randomValue = rand() % 4;

    if (randomValue == 0) {
        randomValue = rand() % alpMountains.size();
        randomMountain = alpMountains[randomValue];
    }
    else if (randomValue == 1) {
        randomValue = rand() % pyreneesMountains.size();
        randomMountain = pyreneesMountains[randomValue];
    }
    else if (randomValue == 2) {
        randomValue = rand() % carpathiansMountains.size();
        randomMountain = carpathiansMountains[randomValue];
    }
    else if (randomValue == 3) {
        randomValue = rand() % icelandicHighlandsMountains.size();
        randomMountain = icelandicHighlandsMountains[randomValue];
    }

    return randomMountain;
}

It's main purpose is to select a random string from one of the 4 vectors and then assign it to the randomMountain variable, which is then returned. Also the error only occurs on the first else if, if that is any help?




Can javascript Math.random() really reach 0?

Based on mdn Math.random() can return 0 but can not return 1

The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1

I tried to loop Math.random() to get 10 number below e-10 and it takes 15 minutes to complete it with my 4 cores 8 threads cpu and from that 10 numbers 0 never get returned. Is my test case just too small or latest javascript Math.random() can never return 0?

note: I run the code using node.js v18.12.1 and the smallest number ever returned is 5.2724491439448684e-12 (yes its small, but it isn't 0)

let countSmallNumber = 0;
let temp = 0;
console.time("loopTime");
while (countSmallNumber < 10) {
    temp = Math.random();
    if (temp < 0.0000000001) {
        countSmallNumber++;
        console.log(`almost 0 => ${temp}`);
    }
}
console.timeEnd("loopTime");



mardi 17 janvier 2023

How to Extract Variable from CSV and Save to Another CSV file. Then Cross reference Variable file to see if Variable has already been extracted

I'm importing a random row from a CSV file and then converting that row into a variable. I then want to save that variable to another file (usedWords.csv) and then have the script cross reference the usedWords.csv file to see if the next randomly selected has already been selected.

Code snippet: ` import random import csv

with open('dictionary.csv') as f:
    reader = csv.reader(f)
    chosen_row = random.choice(list(reader))
    print(chosen_row)

with open('usedWords.csv', 'w',newline='') as f:
    #f.write(str(chosen_row))
    chosen_row = ','.join(chosen_row) + '\n'
    for i in chosen_row:
    if chosen_row != i:
         f.write(str(chosen_row))
    else:
        chosen_row == i
        print("Word Already Used")

`

The code I have currently iterates the word, multiple times, and refreshes the csv file each time. The previous word is deleted. The script would need to save the chosen word, start a new line and save then next chosen word each time the program is activated. Newbie here, any help would be appreciated.

Cheers,

Tried iterating. Tried writing to file. Tried Searching Stack Overflow for suggestions. Don't know after that.




Pseudo Random Number Generator test uniform distribution

If I test the Pseudo Random Number Generator(PRNG) and it satisfies the serial test, it is not sure that the resulting distribution is uniform. Is my observation correct? If it is correct, what test should I do to be sure?




How can I call a random image from an updating Unsplash Collection?

I am creating a website that shows a random picture of a Guinea Pig. I am constently adding pictures, and I'm storing all the photos in an unsplash collection: "unsplash.com/collections/09ARrXAI2Sk/guinea-pig"

I am wondering if I can choose a random image from this collection. This is my HTML code:

<img src="https://source.unsplash.com/collection/09ARrXAI2Sk/1600x900">

Can someone tell me how to do this correctly?




lundi 16 janvier 2023

How to pick a string from a list and convert it to a list - Python

What i want to do is make a hang man game, this is the first phase. I want to pick a word from that online list of words.

I print it to verify it's working.

Till the print line every thing works as intended.

After that there is 2 things:

1- The word is printed like this:b'covered'

Why is there a b? and How to remove it?

2- When i guess a letter it always give false even if the letter is in the word, like this:

b'covered'

Guess a letter: o

False

False

False

False

False

False

False

How can I fix that ?

import requests
import random
word_site = "https://www.mit.edu/~ecprice/wordlist.10000"
rand=random.randint(0,10000)
response = requests.get(word_site)
WORDS = response.content.splitlines()
pick=WORDS[rand]
pick_as_list=list(pick)
print(pick)
user=input("Guess a letter: ")
for letter in pick_as_list:
    if user == letter:
        print("Right")
    elif user != letter:
        print("False")

This code works fine with a given a list not one imported from a site:

rand=random.randint(0,2)
word_list = ["aardvark", "baboon", "camel"]
pick=word_list[rand]
pick_as_list=list(pick)
user=input("Guess a letter: ")
for letter in pick_as_list:
    if user == letter:
        print("Right")
    elif user != letter:
        print("False")

I want to make it work but with a huge list of words.




How to compare numbers in a python guessing game [closed]

My teachers has given me a challenge to try and create a game in python. The game is to guess a random number, the number being anywhere from 1000-9999. However, he has asked for the code to return what number matches a number in the random number. So if the random is 6392 and user inputs 4291, output that 9 is in the right place and correct but the rest are wrong. The only way I can think of doing this is by comparing an array, but I don't understand how to convert it and compare it. Or I've just confused myself. Any help appreciated!

I've tried to use some sort of functions I found online but they don't seem to work.




Random number generator using $dist_uniform in SystemVerilog

I am trying to generate a random number using the $dist_uniform using Quartus and ModelSim.

The relevant code section is as follows (within a loop):

rand= $dist_uniform(10,20,25);
rand_test=$random;

'rand' is always 20 while 'rand_test' is varied on every iteration.

Would appreciate any advice on the matter.

I have tried many variations of the $dist_uniform as well as other distributions as well - the only way I have succeeded to generate a random number is by the $random command




dimanche 15 janvier 2023

How Do I Get A Random Character From The Entire UTF-8 Character Set [duplicate]

I am trying to make a program that gives a random character from the entire UTF-8 character set, but I can't get access to a variable that has every single character in the UTF-8, any chance you know where I could find at-least the fist 100K? (I realy hope my computer can store the file) NOTE: I am using Javascript.

I already know how to get a random word from a data set using this code:

var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" // JUST AN EXAMPLE, I ACTUALLY NEED THE WHOLE UTF-8 IN HERE!
var randomletter = charset.split("")[Math.round(Math.random() * charset.split("").length)]

I just need to get the UTF-8 dataset in the charset variable




Difference between VRFConsumerBase and VRFV2WrapperConsumerBase

latest chainlink documentation shows an example of how to use VRFV2WrapperConsumerBase but all other old videos on creating NFT are using VRFConsumerBase. Can someone explain which one to use while deploying ERC721 nft and getting random numbers.

VRFV2 WrapperCunsumerBase




is it possible to predict the next number generator by LCG

i want to predict the next number in the crash game and these data i have collected

pseudo-random number generators (PRNG) is the linear congruential generator (LCG). The LCG algorithm uses a simple mathematical formula to generate a sequence of numbers that are statistically random. The formula for an LCG is typically of the form:

Xn+1 = (aXn + c) mod m

Where: Xn is the current number in the sequence Xn+1 is the next number in the sequence a, c, and m are constant values called the LCG parameters The LCG is defined by its initial seed (X0), called the state and the 3 parameters a, c, and m. The LCG has many advantages, it is easy to implement, it doesn't require much memory and it's fast, but it also has some drawbacks, it has a relatively short period and the numbers generated may have some correlation between them, making it less unpredictable.

The characteristic polynomial method obtain a sufficient number of numbers from the sequence generated by the LCG that you are trying to reverse-engineer. Create a system of equations by using the relationship between the numbers in the sequence. For example, if you have 3 numbers from the sequence: X1, X2, and X3, you can create the following system of equations: X1 = (aX0 + c) mod m X2 = (aX1 + c) mod m X3 = (aX2 + c) mod m Solve the system of equations using methods such as Gaussian elimination or matrix inversion. Once you have solved for X0, you have determined the seed value used by the LCG to generate the sequence.

i try to reach my target and i hope to




Generate 10 non-duplicate random integers from 0 to 20 [duplicate]

I have a problem in generating the non-duplicate numbers. I tried to do the do-while loop but it seems not working. How do I fix it?

import java.util.Arrays;

public class Assignment2_Q2 {
    
    public static void main (String[] args){
        
        int[] myList = new int[10];
        
        number(myList);
        sortedOrder(myList);
        display (myList);
    }
        
    public static void number(int[] list){
            
        int random;
        
        random = (int)(Math.random() * 21);
        list[0] = random;
            
        for (int i = 1; i < list.length; i++){
            do{
                random = (int)(Math.random() * 21);
                list[i] = random;        
            }while(list[i] == list[i-1]);
        }
    }
    
    public static void sortedOrder(int[] list){
        
        java.util.Arrays.sort(list);    
    }
    
    public static void display(int[] list){
        
        System.out.println("The array in the sorted order:\n" + Arrays.toString(list) + "\n");  
    }             
}



samedi 14 janvier 2023

Py: random int distribution of numbers over [list] with exact sum

I'll be as concice as I can be.

I have a number generated by other means:

topic_interest_0 = 50 # this number is generated elsewhere

I have a list with a number of items, in this case 7:

topic_interest_literature = [0, 0, 0, 0, 0, 0, 0]

I need to distribute topic_interest_0 randomly over topic_interest_literature but where the sum of all items in topic_interest_literature is topic_interest_0 and no item is larger than 10.

I have tried a while loop:

while topic_interest_0 > 0:
            if topic_interest_0 >= 10:
                topic_interest_literature[0] = random.randint(0, 10)
            else:
                topic_interest_literature[0] = random.randint(0, topic_interest_0)
                
            topic_interest_0 -= topic_interest_literature[0]

And run this for every item in topic_interest_literature 0 to 6. But this is tedious since I have multiple other such lists to go through, plus it will always leave me with either a surplus or a deficit on the last possible random.




How do I get randint,random.choice, or random.sample to pick a certain number for every nth choice?

I am currently assigning actions to certain numbers because I think it will work best with my current code. Everything works perfectly this way as I get a random choice that then assigns that number to a variable which is then checked to produce an action. Only issue is I want certain numbers to be chosen with a span of 9 choices, for example I want the numbers 3,4 or 5 to be chosen 3 times within a span of 9 choices, all other numbers can be random. The 3 choices can be split among those three numbers (so 3 can be chosen 2 times and 5 once for example). Is there a way to do this?

Here is a fraction of my code that goes with my explanation. So basically, what I'm trying to get at is modifying the amount of times that x is equal to 3,4 or 5 within the for loop. But I don't want to choose when x is equal to those numbers myself. I don't want to put ("if item == frame9: x = 3") for example. So, I don't want to pick the time or iteration to set x equal to 3, but I want the program to choose 3, at least 3 times in the for loop. Is it possible to make a way that the program goes back to check the choices, and then changes them if not enough of them were 3? Sorry if this is a bit confusing, I'm still new to this. Appreciate the help!

frames = [frame1, frame2, frame3, frame4, frame5, frame6, frame7, frame8, frame9]

 for item in frames:
        x = randint(1, 16)

        if x == 1:
            d1 = Ds(1)
            letter_list.append("d1")

        elif x == 2:
            d2 = Ds(0, 1)
            letter_list.append("d2")

        elif x == 3:
            d3 = Ds(1, 1)
            letter_list.append("d3")

        elif x == 4:
            d4 = Ds(2)
            letter_list.append("d4")

        elif x == 5:
            d5 = Ds(0, 2)
            letter_list.append("d5")



vendredi 13 janvier 2023

Generate string with random characters and digits [closed]

XXYYY

where

X = Random characters between A and Z
Y = Random number between 0 and 9

correct = AB123, BA223
wrong = 1BAC2, B2J12

can someone help me pls

can answer my questions




jeudi 12 janvier 2023

Generate A Random String With A Set of Banned Substrings

I want to generate a random string of a fixed length L. However, there is a set of "banned" substrings all of length b that cannot appear in the string. Is there a way to algorithmically generate this parent string?

Here is a small example:

I want a string that is 10 characters long -> XXXXXXXXXX The banned substrings are {'AA', 'CC', 'AD'} The string ABCDEFGHIJ is a valid string, but AABCDEFGHI is not.

For a small example it is relatively easy to randomly generate and then check the string, but as the set of banned substrings gets larger (or the length of the banned substrings gets smaller), the probability of randomly generating a valid string rapidly decreases.




mercredi 11 janvier 2023

Google Apps Script: How can I generate 5 random numbers (between 0 and 8) that always have the sum of 30?

I know RANDBETWEEN(1,8), but I cant figure out how to generate 5 random numbers that always have 30 as a sum. (or 365 numbers that have 1560 as a sum, which is probably much more complex even)




How do I get the variable and get it to sort the numbers and print how many passed?

I am somewhat new coding, and tried to make a "macro" of sorts to roll a large amount of dice, and show how many hit, and while I have not got to it yet, apply a modifier if x number was rolled, I am trying to get a variable, "roll dice" for the number from the variable, and then show how many were above a number from another variable.

import random

#whatisneededtoday will be used to bring up other pieces of code that is needed for the        diffrent actions

whatisneededtoday = input('Select an action attack, psychic, charge, unit table.')

#typeofattack will dictate whether a meele attack is going to be made or a ranged attack

if whatisneededtoday [1] == 't':

  typeofattack = input('meele or ranged? ')

  if typeofattack[0] == 'r':

    print(typeofattack)
    bs = input('what is your balistic skill? ')
    print(bs)
    dice = input('how many dice are needed to roll?')
    randomlist = [random.randint(1,6) for i in range (int(dice))]

    for i in randomlist:
      if randomlist[i] >= int(bs):
        print(dice)
    
  
        #if typeofattack[0] == 'm':        
         #print(typeofattack)
        #ws = input('what is your weapon skill? ')
        #print(ws)
        #meelehittingphase = input('how many dice are needed to roll? ')

#if whatisneededtoday [0] == 'p':
  #print ("test psychic")
#if whatisneededtoday [0] == 'c':
  #print("charge test")
#if whatisneededtoday [0] == 'u':
  #print("unit table test")`

I was hoping for it to take the variables dice, "roll" them, and if they are equal or greater then(gettint this from the variable bs) count them as hit, and if they are x number, either add more hits, wound, or do other affects.`




mardi 10 janvier 2023

Trying to iterate through a list with a for loop, although I receive a 'list' object is not callable error [closed]

I am creating a random linear search program. After adding 1000 random numbers between 0 and 3000 to a list, I am not able to iterate through the list with a for loop as I receive an error called 'list' object is not callable. Here is my code:

import random

randomnumberlist=[]

randomnumbers=random.randint(0,3001)

count=0

while count<1000:
    randomnumbers=random.randint(0,3001)
    randomnumberlist.append(randomnumbers)
    count+=1

userinput=int(input("Choose number between 1 and 3000"))



for i in randomnumberlist():
    if i==userinput:
        print("Your number has been found")
    else:
        print("Your number is not in the list")``

I expected this to work by the for loop just iterating through the for loop and if it finds the number it will stop and output 'Your number has been found' or if the number is not found to output 'Your number is not in the list'




Unwanted Brackets Output in Rubik's Cube Scrambler

I am making a Rubik's cube scrambler program using python 3.10.2 and everything works correctly except for one thing. When the randomly generated scramble is outputted, unwanted square brackets, quotation marks and commas show up as well. Any idea on how to fix this? -Thank you

import random

notation = ["R","L","F","B","U","D","R'","L'","F'","B'","U'","D'","R2","L2","F2","B2","U2","D2"]
scramble = []
i = 0

while i < 9:
    randomNotation = random.choice(notation)
    scramble.append(randomNotation)
    i += 1
print(scramble)

Output: ['L2', 'L', "R'", "D'", 'L', 'F2', 'R', "D2", 'L']




Choosing a random element from a list of tuples C#

I'm quite new to programming and I am trying to add a random bot move to a small game I've made. My idea was to make a list of tuples of all of the legal moves and then pick a random tuple from that list to then deconstruct and change a value in a 2D-array. I've looked all over the internet and found a way to make a list of tuples (I think), but couldn't manage to pick a random element from that list.

This is what I tried:

List<Tuple<int, int>> legalMoves; // To make the list of tuples

// Later on in a double for-loop that iterates through all the rows and columns of the 2D-array I check if that certain row and column combination is a legal move and then add it to the list like so:

legalMoves.Add(Tuple.Create(row, col));

//Then in a different method I try to pick a random element from that list (this doesn't work)

Random random = new Random();
int randomIndex = random.Next(legalMoves.Count);
(int, int) randomMove = legalMoves[randomIndex];

It gives the following error on the last line: Error CS0029 Cannot implicitly convert type 'System.Tuple<int, int>' to '(int, int)'

Is there any way to make this work?

Thanks in advance!




lundi 9 janvier 2023

Choose random numbers from multiple lists and it must contain at least one number from each list

Let's say I have 3 different lists

A = [1, 2, 3, 4, 5]
B = [11,12, 13, 14, 15]
C = [21, 22, 23, 24, 25]

I want to select 5 random numbers(repeating numbers are fine) from the above lists but it must contain at least one number from each of the lists. Here is my attempted implementation.

from random import choice
for i in range(5): # total numbers selected can be variable
    print(choice(choice([A, B, C]))) #inside choice chooses the list and outside one the number

The above code doesn't necessarily select numbers from each of the lists. How can I select the numbers from the lists ensuring at least one number is chosen from each list?




designing a game in python where random mathematical problems appear for the user to solve

  1. The code is supposed to generate random equations for the user to answer with num1 being in the range of 1 to 9 while num2 in the range 0,10
  2. The user starts with 100 points
  3. if user enters x the program terminates
  4. if user enter wrong answer the score decreases by 10
  5. if user enters correct answer the score increases by 9

I've been successful in doing steps one to 3 however when it comes to checking if the inputted answer by the user is correct it always returns it as wrong even if its correct example figure1

I assume this is because my code doesn't evaluate the question and been trying to figure out why

import random


# set variables
score = 100  # score of user
operator = ["+", "-", "*", "/"] #operators
number_1 = random.randint(1, 9)  # this variable will be a random number between 1 and 9
number_2 = random.randint(0, 10)  # this variable will be a random number between 0 and 10


# this function prints the dashes
def dash():
    print("-" * 50)

while score >= 0 and score <= 200:
    dash()
    print("You currently hold: ", score, " points")
    print("Get more than 200 points you win, under 0 you lose")

    sign = random.choice(operator)  # chooses random operator
    real_answer = number_1,sign,number_2

    print(str(number_1) + str(sign) + str(number_2), "?")
    dash()
    print("Press x to close program")
    answer = input("Enter your guess of number: ")

    if answer == "x":
        print("Program has been terminated properly")
        break
    elif answer == real_answer:
        score = score + 9
        continue
    elif answer  != real_answer:
        score = score - 10
        continue

if score < 0:
        print("Unlucky, You lost")

elif score > 200:
    print("CONGRATULATIONS YOU WON")



Object moving between random positions, how to put speed limitation with CSS or Javascript?

I have a keyframe animation in css like this:

@keyframes anim-target1 {
    0% {
    scale: 0.24;
        transform: translateX(0) translateY(0);
    }

    100% {
        scale: 0.24;
        transform: translateX(-650px) translateY(-25px);
    }
}

Now I want to make the object go forth and back randomly in between these two points, stopping at random positions not having to go to the start or end before going the other way. And having it be random every time it is run, otherwise I would obviously just make the keyframes for it. The keyframes being like a path it can not deviate from. Is there a way to do this simple with css and javascript? Taking scale into consideration, should it be two points between different scales also (I only have for X and Y). Anyone up for the task to solve?

I have tried making a script that creates random keyframes in between 0 and 100, and it works, but the speed is not consistent but fluxate. Somehow to make a speed limit on how fast the object can move no matter how far or short it travels.

Here is the javascript I have so far to make the random positions:

// Generate a random number of intermediate positions
    var numPositions = Math.floor(Math.random() * 10) + 1;

    // Generate the keyframes string
    var keyframes = "@keyframes anim-target1 {\n";
    keyframes += "  0% { scale: 0.24; transform: translateX(0) translateY(0); }\n";
    for (var i = 1; i <= numPositions; i++) {
        // Generate random values for the translateX and translateY properties
        var translateX = Math.floor(Math.random() * 651);
        var translateY = Math.floor(Math.random() * 26);
        keyframes += "  " + (i * 10) + "% { scale: 0.24; transform: translateX(" + translateX + "px) translateY(" + translateY + "px); }\n";
    }
    keyframes += "  100% { scale: 0.24; transform: translateX(-650px) translateY(-25px); }\n";
    keyframes += "}";

    // Inject the keyframes string into the page
    var style = document.createElement("style");
    style.innerHTML = keyframes;
    document.head.appendChild(style);

I figure it would be better maybe to make all the animation points in javascript somehow might be better, if anyone has any suggestions?

I was expecting this solution I have could be somehow easily controled to have a speed limit and not determin by the animation time. But yet to figure it out.




Multiple random API keys from the list

I have this code below, I want to use randomly API key picked from the list of keys:

function getSomething() {
    //
    var SomethingApiKey = "c40dcc41bb316dec013d";
    var SomethingApiCall = "https://api.website.net/catalog/" + SomethingApiKey + "/" + l + "," + l + "?units=si";
    $.ajax({
      url: SomethingApiCall,
      type: "GET",
      dataType: "jsonp",

I tried this :

var r_text = new Array();
 r_text[0] = "Ge8rp3OJNsoTvCRV";
 r_text[1] = "OZ4W4yBVRxfGc4xp";
 r_text[2] = "zInuwyCmOcuD-OjB";
 r_text[3] = "EcSyDtyL_PT5PCAd";
 r_text[4] = "AdCWLOhkjOAEDSdy";

function search() {
    var nn = Math.floor(5 * Math.random());

`  function getSomethin() {
    //
    var SomethingApiKey = r_text[nn]
    var SomethingApiCall = "https://api.website.net/catalog/" + SomethingApiKey + "/" + l + "," + l + "?units=si";
    $.ajax({
      url: SomethingApiCall,
      type: "GET",
      dataType: "jsonp",

But is not working :/




dimanche 8 janvier 2023

frequently used 3 times

How can I make a function that outputs only 3 frequently used usernames from an object


        let allUser = await User.findAll()
        var result = {};
        allUser.forEach(function(v){
            result[v.age = result[v.age] + 1 || 1;
        })
        for (var key in result)
            console.log(key + result[key])
console.log('amount ' + key + ' == ' + result[key] + ' times <br>')

//amount 19 == 1 times 
//amount 15 == 1 times 
//amount 20 == 34 times 

I don't have 3 but all at once, I want it to sort But not more than 3.

1. 34
2. 1 
3. 1



samedi 7 janvier 2023

Which Rust RNG should be used for multithreaded sampling?

I am trying to create a function in Rust which will sample from M normal distributions N times. I have the sequential version below, which runs fine. I am trying to parallelize it using Rayon, but am encountering the error

Rc<UnsafeCell<ReseedingRng<rand_chacha::chacha::ChaCha12Core, OsRng>>> cannot be sent between threads safely

It seems my rand::thread_rng does not implement the traits Send and Sync. I tried using StdRng and OsRng which both do, to no avail because then I get errors that the variables pred and rng cannot be borrowed as mutable because they are captured in a Fn closure.

This is the working code below. It errors when I change the first into_iter() to into_par_iter().

use rand_distr::{Normal, Distribution};
use std::time::Instant;
use rayon::prelude::*;

fn rprednorm(n: i32, means: Vec<f64>, sds: Vec<f64>) -> Vec<Vec<f64>> {

    let mut rng = rand::thread_rng();
    let mut preds = vec![vec![0.0; n as usize]; means.len()];

    (0..means.len()).into_iter().for_each(|i| {
        (0..n).into_iter().for_each(|j| {
            let normal = Normal::new(means[i], sds[i]).unwrap();
            preds[i][j as usize] = normal.sample(&mut rng);
        })
    });

    preds
}

fn main() {

    let means = vec![0.0; 67000];
    let sds = vec![1.0; 67000];
    let start = Instant::now();
    let preds = rprednorm(100, means, sds);
    let duration = start.elapsed();
    
    println!("{:?}", duration);
}

Any advice on how to make these two iterators parallel?

Thanks.




SyntaxError: name 'x' is used prior to global declaration

I want to create a programm which should get random strings of an array and put it inside a sentence. The problem is that the first sentence has to be different to the next sentence. Therefore I tried to use a global variable which should store the previous sentence, because otherwise it would be overwritten. But now I get an

SyntaxError: name 'previous_sentence' is used prior to global declaration

I hope you can help me

import random

previous_sentence = ''

def create_sentence():
    names = ["x", "y", "z"]
    designations = ["a", "b", "c"]
    sentence = '' 
    while sentence == previous_sentence:
        name = random.choice(names)
        designation = random.choice(designations)
        sentence = f'{name} ist ein {designation}'
    global previous_sentence
    previous_sentence = sentence
    return sentence

for i in range(10):
            print(create_sentence())



How to make every index of 2D array a random integer?

`import java.util.Random;

public class Main {

    public static void main(String[] args) {
        int[][] board = new int[5][5];
        int sNA = 5;

//        new GUI();

        sequenceMaker(board);
        drawBoard(board);
    }
//
    public static void drawBoard(int[][] board2D) {
        int m=1;

        for(int i = 0; i < board2D.length; i++){
            for(int j=0; j < board2D.length; j++){
                System.out.print(board2D[i][j]+" ");
            }
            System.out.println();
        }
    }

    public static void sequenceMaker(int[][] board2D) {
        Random rand = new Random();
        int m = 1;
        int x = 0;

        while(x < 24){
            int columnRandom = rand.nextInt(5);
            int rowsRandom = rand.nextInt(5);
            x += 1;

            if(board2D[columnRandom][rowsRandom] == 0) {
                board2D[columnRandom][rowsRandom] = m;
                m += 1;
            }
            else if(board2D[columnRandom][rowsRandom] == m) {
                while(board2D[columnRandom][rowsRandom] == m) {
                    columnRandom = rand.nextInt(5);
                    rowsRandom = rand.nextInt(5);

                    board2D[columnRandom][rowsRandom] = m;
                    m+=1;
                }
            }
        }
    }
}`

This is what I wrote to this point, but the output doesn't include every index, maximally going to 15-16ish.

I tried a while loop, so that if another integer is in the place of randomally generated number, it generates those number once again. I don't know why my output is incomplete though.




vendredi 6 janvier 2023

Generate random coordinates of points on a circle

I have to write a code where I write a random number, it should give me the number of random points with coordinates and after these points to draw the corresponding circle. I really need help because I do not even know how to start writting.

I find this code on Stackoverflow:

import random
import math

# radius of the circle
circle_r = 10
# center of the circle (x, y)
circle_x = 5
circle_y = 7

# random angle
alpha = 2 * math.pi * random.random()
# random radius
r = circle_r * math.sqrt(random.random())
# calculating coordinates
x = r * math.cos(alpha) + circle_x
y = r * math.sin(alpha) + circle_y

print("Random point", (x, y))

How can I change this code that I could get random multiple points for random circle?




How to obtain the length of a file

I am trying to run a simple C program that takes a file of random floating point values, automatically identify the length of the file and use the length to perform further computation. However, my compiler either hangs or I get erroneous results. Here is my code

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>



int main()
{

    
   FILE *fptr;
    int count = 0; // Line counter (result)
    char ch; // To store a character read from file

    if ((fptr = fopen("C:\\Users\\Evandovich\\Desktop\\White_Noise.txt","r")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

    // Extract characters from file and store in character ch
    for (ch = getc(fptr); ch != EOF; ch = getc(fptr))
    {
        if (ch == '\n') // Increment count if this character is newline
            count = count + 1;
    }
      printf("The file has %d lines\n ", count);

// use the value of "count" to be the length of the array.

  char arrayNum[count];
  char *eptr;
  double result, result1[count];


  for (int i = 0; i<count; i++)
   {
       fscanf(fptr,"%s", &arrayNum[i]);

       /* Convert the provided value to a double */
    result = strtod(&arrayNum[i], &eptr);
    result1[i] = pow(result,2) ;
    printf("value %f\n", result1[i]);

   }


   fclose(fptr);
    return 0;
}


What particularly is the error? Your input is well appreciated

INPUT file (N.txt) contains

0.137726
0.390126
-0.883234
0.006154
-0.170388
-1.651212
0.510328

OUTPUT The file has 7 files

value 0.000000
value 0.000000
value 0.000000
value 0.000000
value 0.000000
value 0.000000
value 0.000000

Expected The file has 7 files

value 0.018968
value 0.152198
value 0.780102
value 0.000038
value 0.029032
value 2.726501
value 0.260435



rearranging list using for loop and random choice [duplicate]

import random
a=['sai','raju','phani'] 
b=[]
for I in a:
     b += random.Choice(a) 
print(b)

result:

['s', 'a', 'i', 's', 'a', 'i', 'r', 'a', 'j', 'u']

but expected to be total string not individual

['sai','sai','raju']

What did I do wrong?




jeudi 5 janvier 2023

Random choice function adds invinsible "0"?

I wanted to define a function that gets me the set amount of keys in a dictionary and puts it in a list. The function though adds a "0" to the list, which is not a key and also exceeds the set amount? I tried the code in 2 different editors (VS Code and Thonny), both did this in like 40% of the time...

The Code:

import random

def random_card(times):
    chosen_card = []
    for t in range(times):
        chosen_card += random.choice(list(cards))
    return chosen_card

cards = {
        'A': 1,
        '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 
        'J': 10, 'Q': 10, 'K': 10
        }

player_cards = random_card(2)
pc_cards = random_card(2)

print(f"Your cards: {player_cards}\nDealer cards: {pc_cards}")

print(list(cards))

Outputs with the "0":

Your cards: ['8', '1', '0']
Dealer cards: ['9', '1', '0']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

Your cards: ['Q', '1', '0']
Dealer cards: ['7', '1', '0']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

Your cards: ['J', '1', '0']
Dealer cards: ['Q', '4']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']



Linear Congruential generator graph

I implemented a simple code for a linear congruential generator

clear all; clc

% Input
m = 59;         % module
a = 17;         % multiplier
c = 43;         % increase
X0 = 27;        % seed

n = 100;        % sample length

y = [X0 zeros(1,n-1)];

% recursive formula
% X(n+1) = (a*X(n) + c) mod m

 for i = 2:n

  y(i) = mod(a*y(i-1)+c,m);

end

x = 0:1:n-1;

%for i = 1:n

 %   plot(x,y);

%end

What I would like to do is a plot where each time the period repeats it draws a vertical line upward as in this graph

enter image description here

I think I have to use the plot function inside a FOR loop and an IF-ELSE to see if the value of the subsequence X(n) is equal to the seed X(0) but I have no idea how to implement it

I think I have to use the plot function inside a FOR loop and an IF-ELSE to see if the value of the subsequence X(n) is equal to the seed X(0) but I have no idea how to implement it




I want the highest and the lowest value of a table, why can't I save that value in PHP?

$category = htmlspecialchars($_GET['category']);

$sql = "(SELECT number 
        FROM german 
        WHERE german.category_german LIKE ".$category." 
        ORDER BY number DESC 
        LIMIT 1) as 'high', 
        (SELECT number 
        FROM german 
        WHERE german.category_german LIKE ".$category." 
        ORDER BY number ASC 
        LIMIT 1) as 'low'";
    if ($result = $conn -> query($sql)) {
      while ($row = $result -> fetch_row()) {
        
          $high_value = $row[high];
          $low_value = $row[low];
          $r_n = rand($low_value,$high_value).PHP_EOL;
          echo $r_n;
          }

      }

What am I missing? I want the highest and the lowest value of a table, why can't I save that value in PHP? I just can't access the values. And I tried out MIN and MAX as well, but they didn't function neither:

$category = htmlspecialchars($_GET['category']);

$sql = "SELECT MIN('number') AS 'low', MAX('number') AS 'high' FROM german WHERE german.category_german LIKE ".$category."";
    if ($result = $conn -> query($sql)) {
      while ($row = $result -> fetch_row()) {
          $high_value = $row[high];
          $low_value = $row[low];
          $r_n = rand($low_value,$high_value).PHP_EOL;
          echo $r_n;
          }

      }

As a result of $r_n I only get 0. The database shouldn't be the problem. Beforehand (where I only used the highest value) everything functioned:

$category = htmlspecialchars($_GET['category']);

$sql = "SELECT number FROM german WHERE german.category_german LIKE ".$category." ORDER BY number DESC LIMIT 1";
if ($result = $conn -> query($sql)) {
  while ($row = $result -> fetch_row()) {
    
      $r_n = $row[0];
      $r_n = rand(1,$r_n).PHP_EOL;
      echo $r_n;
      }

  }



Delphi - use Windows OS CryptGenRandomBytes to generate random bytes

I read Are there any cryptographically secure PRNG libraries for Delphi? but the solution it presents uses WCrypt2 which I don't want to use.

So I made my own unit depending on nothing.

An example using this unit:

uses SysUtils, WinRandomBytes;

function BytesToHex(const Bytes: TBytes): string;
var i : integer;
begin
    Result := '';

    for i := 0 to Length(Bytes)-1 do
    begin
        Result := Result + IntToHex(Bytes[i],2);
    end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var bytes : TBytes;
begin
    bytes := OSWinRandomBytes(32);

    ShowMessage(BytesToHex(bytes));
end;

This is the new unit for acquiring random bytes via the Windows Crypto API. It exposes one function OSWinRandomBytes() which either returns the requested random bytes or raises an error.

unit WinRandomBytes;

interface
uses SysUtils;

{ Return requested TBytes or raise an Exception }
function OSWinRandomBytes(Length: cardinal) : TBytes;

implementation
uses Windows;

type HCRYPTPROV = pointer;
type TCryptAcquireContextA = function(var phProv: HCRYPTPROV; pszContainer: PAnsiChar; pszProvider: PAnsiChar; dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall;
type TCryptGenRandom = function(hProv: HCRYPTPROV; dwLen: DWORD; pbBuffer: Pointer): BOOL; stdcall;
type TCryptReleaseContext = function(hProv: HCRYPTPROV; dwFlags: DWORD): BOOL; stdcall;

const PROV_RSA_FULL = 1;
const CRYPT_VERIFYCONTEXT = $F0000000;

var AdvApiLoaded: boolean;
var AdvApiHandle: HModule;
var CryptAcquireContextA : TCryptAcquireContextA;
var CryptGenRandom : TCryptGenRandom;
var CryptReleaseContext : TCryptReleaseContext;

function LoadAdvApi() : boolean;
begin
    if not AdvApiLoaded then
        begin
            AdvApiLoaded := true;

            AdvApiHandle := LoadLibrary('advapi32.dll');
            if AdvApiHandle <> 0 then
                begin
                    CryptAcquireContextA := GetProcAddress(AdvApiHandle,'CryptAcquireContextA');
                    CryptGenRandom := GetProcAddress(AdvApiHandle,'CryptGenRandom');
                    CryptReleaseContext := GetProcAddress(AdvApiHandle,'CryptReleaseContext');
                end;
        end;

    Result := Assigned(CryptAcquireContextA) and Assigned(CryptGenRandom) and Assigned(CryptReleaseContext);
end;

function OSWinRandomBytes(Length: cardinal) : TBytes;
var hProv : HCRYPTPROV;
begin
    if not LoadAdvApi() then
        begin
            raise Exception.Create('Error loading advapi32.dll');
        end;

    hProv := nil;
    if not CryptAcquireContextA(hProv,
                                nil,
                                nil,
                                PROV_RSA_FULL,
                                CRYPT_VERIFYCONTEXT) then
        begin
            RaiseLastOSError();
        end;

    try
        SetLength(Result, Length);

        if not CryptGenRandom(hProv, Length, @Result[0]) then
            begin
                RaiseLastOSError();
            end;
    finally
        CryptReleaseContext(hProv, 0);
    end;
end;

begin
    AdvApiLoaded := false;
    AdvApiHandle := 0;
    CryptAcquireContextA := nil;
    CryptGenRandom := nil;
    CryptReleaseContext := nil;
end.



mercredi 4 janvier 2023

How can I compare two randomly generated numbers within two functions with each other?

I'm trying to compare two random numbers (each returned by a function) because I need to select a random element from a list and then turn the second number into the same +1 if they are equal.

Here's my code:

def random_1():
  first_random_num = randint(1, 50)
  return first_random_num

def random_2():
  second_random_num = randint(1, 50)
  return second_random_num
  
  if random_1() == random_2():
    print("hello")
  else:
    print("World")

OUTPUT:

 ...



Random Password with 4 characters from String

I made a code that gives me every possible 4 character combination of a String. Now I need to make a program that chooses 1 random combination as a Password and then goes over every possible combination till it finds the chosen one and then tells me how many guesses it took to find the right one. This is what I have so far:

String alphabet = "ABCabc012!";
        char pw[] = alphabet.toCharArray();
        

        for (int i = 0; i < pw.length ; i++) {
            for (int j = 0; j < pw.length ; j++) {
                for (int k = 0; k < pw.length ; k++) {
                    for (int l = 0; l < pw.length ; l++) {

                        System.out.println(pw[i] + " " + pw[j] + " " + pw[k] + " " + pw[l]);
                    }
                }
            }
        }

I tried to store the pw[] in an array but I dont know exactly how to do it.




Python Random Module sample method with setstate notworking

I am wondering if I am doing it wrong when setting the random seed and state. The random number generated from the random.sample seems not predictable. Does anyone know why? Thanks.

>>> state = random.getstate()
>>> random.seed(7)           
>>> x = list(range(10))
>>> random.sample(x, 5)
[5, 2, 6, 9, 0]
>>> random.sample(x, 5)
[1, 8, 9, 2, 4]
>>> random.sample(x, 5)
[0, 8, 3, 9, 6]
>>> random.setstate(state)
>>> random.sample(x, 5)    
[3, 1, 9, 7, 8]
>>> random.sample(x, 5)
[4, 2, 7, 5, 0]
>>> random.sample(x, 5)
[9, 6, 7, 8, 0]



mardi 3 janvier 2023

Roll Dice And Play [closed]

  1. Write a model class that represents a die (that is, a cube whose sides are numbered 1 to 6). The class will likely have just one method, throw(), and no attributes. (Hint: use Math.random to write throw.) Then, write an output-view class that displays a die after it has been thrown. Finally, write a controller that lets a user throw two dice repeatedly.
  2. Use the class from the previous exercise to build a game called “draw the house.” The objective is to throw a die repeatedly, and based on the outcome, draw parts of a house. A throw of 6 lets one draw the building, a square; a throw of 5 lets one draw the roof; a throw of 4 lets one draw the door; and a throw of 3 lets one draw a window. (There are two windows.) The finished house looks something like this: /
    / \

| _ | |x| |x|

Of course, the building must be drawn before the roof, and the roof must be drawn before the doors and windows. In addition to the class that represents the die, write a model class that represents the state of a partially built house. Then, write an output view that displays the house, and write a controller that enforces the rules of the game. 8. Make a version of the game in the previous Project that lets two players compete at building their respective houses.

Of course, the building must be drawn before the roof, and the roof must be drawn before the doors and windows. In addition to the class that represents the die, write a model class that represents the state of a partially built house. Then, write an output view that displays the house, and write a controller that enforces the rules of the game.




CUDA randState intializer kernel identifier "curandState_t" is undefined

The problem

I am compiling a CUDA shared library that I've written, for this library, I need the capability to randomly sample stuff, therefore, as specified by the docs, I am initializing an array of curandState_t:


/**
 * @brief Sets up random number generators for each thread
 *
 * @param state pointer to the array of curandState
 * @param seed seed for the random number generator
 */
__global__ void rand_setup(curandState_t* state, unsigned long seed)
{
    /* 3D grid of 3D blocks id */
    size_t gid = getGlobalIdx_3D_3D();

    curand_init(seed, gid, 0, &state[gid]);

    printf("Initializing random number generator for thread %d");
}

The getGlobalIdx_3D_3D() call just retrieves the global ID through a bunch of tedious calculations, such as:

/**
 * @brief Get the global identifier of the thread
 *
 * thanks to: https://cs.calvin.edu/courses/cs/374/CUDA/CUDA-Thread-Indexing-Cheatsheet.pdf
 * for the snippet
 *
 * @return size_t The global index of the thread
 */
__device__ size_t getGlobalIdx_3D_3D()
{
    size_t blockId = blockIdx.x + blockIdx.y * gridDim.x
        + gridDim.x * gridDim.y * blockIdx.z;
    size_t threadId = blockId * (blockDim.x * blockDim.y * blockDim.z)
        + (threadIdx.z * (blockDim.x * blockDim.y))
        + (threadIdx.y * blockDim.x) + threadIdx.x;
    return threadId;
}

The errors

I am getting a cascade of compilation errors (I have just completed a substantial amount of work), however, many of them seem to stem from the fact that curandState_t is not recognized as a proper type, hence I get this annoying dump:

D:\Repos\MulticoreTree\shared\libkernel.cu(325): error: attribute "__global__" does not apply here

D:\Repos\MulticoreTree\shared\libkernel.cu(325): error: incomplete type is not allowed

D:\Repos\MulticoreTree\shared\libkernel.cu(325): error: identifier "curandState_t" is undefined

D:\Repos\MulticoreTree\shared\libkernel.cu(325): error: identifier "state" is undefined

D:\Repos\MulticoreTree\shared\libkernel.cu(325): error: type name is not allowed

D:\Repos\MulticoreTree\shared\libkernel.cu(325): error: expected a ")"

D:\Repos\MulticoreTree\shared\libkernel.cu(326): error: expected a ";"

D:\Repos\MulticoreTree\shared\libkernel.cu(407): warning #12-D: parsing restarts here after previous syntax error

Looking online for documentation, there doesn't seem to be anything that tells me to import a specific header, also, I have #include <cuda_runtime.h> at the top of my file, so what could be wrong?

I personally think that the type is not being recognized, but there might also be a problem with something else in the function's signature causing it to fail compilation.




lundi 2 janvier 2023

How do i create an array with n elements where values are between 0 - n without duplicates?

I want to give an array of a specific length a random number generated to each elements value where the values are varying.

srand(time(NULL));
int r;
int n = 8; //n is given for the sake of this example
for (int i = 0; i < n; i++)
{
  r[i] = (rand() % n) + 1;
  for (int j = 0; j < i; j++)
  {
    if (r[i] != r[j])
    {
     return 0;
    }
    else
    {
      while (r[i] == r[j])
      {
        r[i] = (rand() % n) + 1;
      }
   }
}

The problem is that the while loop doesn't go through every single element in the array "r" which most likely will give the array multiple elements with the same value since it only checks for one element and not the ones before.

In conclusion I need help to check for all elements and somehow eliminate the ones already chosen.




How to increase the probability of choosing a number?

So i have a code that choses a random number between 1 and 2. If the code choses 1, i want to increase the probability of choosing 1 by 10%. If the code choses 2, i want to increase the probability of choosing by 2 15%. Here is my code :


import pygame, random,sys

pygame.init()
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
BLACK = (0,0,0)
white = "#FFFFFF"
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Test")

def test2():
win.fill(BLACK)

    test = random.randint(1,2) 
    text_font = pygame.font.Font('freesansbold.ttf', 100)
    screws_text = text_font.render(str(test), True ,white)
    textRect = screws_text.get_rect()
    textRect.center = (250,250)
    win.blit(screws_text, textRect)
    
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit() 
    pygame.display.update()

while True:

    for event in pygame.event.get():
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                test2()
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

I didn't really tried anything because i have no idea that i should do, i never did that so i would be very grateful if you could help me.