samedi 31 octobre 2020

I want to create the simplest html code for random text generator

I took like one year or html and php programming but i dont think its enough for me to make this type of code, what should i look for or start with? I want it to simply print a random text (from a database I suppose) everytime you open the page.

This would really help me a lot ! Thank you to everyone who responds




Google Forms Apps Script (.gs) function random assignment of users

I am a psychology student, with a little coding experience in a few different languages, but I'm a little, nix that, a lot rusty. I'm using Google Apps Script, trying to make it so that a Google Form can randomly assign participants into group A or B for a research project. This will be posted online so people can take it at any time, thus I won't be able to manually do it, it will have to be done programatically. I am using Google Sheets to store backend data, collecting email addresses to link data to specified user across sheets. Flow is such: Form 1 - link to informed consent on google drive for participants to download, sign, and upload, demographics data, and instructions walkthrough the next 4 forms they will be receiving. Click submit, and "submission received" ConfirmationMessage will contain link to either the group A form 2 or group B form 2. Form 2 will contain a link to an article to read, which they need to close after reading (I think we're going to have to be on the honor system here). I am collecting timestamp from submission of form 1 and timestamp of submission of form 2 to determine length of time spent reading the article. When they submit form 2, ConfirmationMessage needs to display link to form 3, a quiz on the article, rinse and repeat, each participant will read two articles. So, this is where I'm at, trying to random assign into group A or B...

         function onOpen() {
 var existingForm = FormApp.openById('1LWDhdp_xj7xXHDSHKFTgoARADPoZj5VXGo9H2p0rkNY');
    function pickRandom() {
      var wordsarray = ['heads','tails'];
      var randomnumber = Math.floor(Math.random() * wordsarray.length);
      console.log(wordsarray[randomnumber]);
    var answer = pickRandom(['heads','tails']);
if (answer === 'heads'){form.setConfirmationMessage('message1');}
if (answer === 'tails'){form.setConfirmationMessage('message2');}
      getConfirmationMessage();
      console.log(ConfirmationMessage);

I am getting nothing. I tried output to console to see what's going on, but no logs.




I want to make a simple html that can show a combination of two images from 2 sets of thousand images

I do not have html, css, javascript knowledge but I want to make a simple html that can show a combination of two image. I can edit a simple html and css by watching youtube tutorials. I need some help on this.

The website I want to make is simple. there will be 2 question mark images Left and right.

If I click a "shuffle" button, two initial question mark images change in to a random image combination after 2 seconds.

I want a shuffling motion during 2 seconds of shuffling and want final 2 images for a result.

random picks of 2 images of thosands of images from database.

you can think of this as a slot machine. yet the motion of shuffling doesn't have to show like wheel motion of slot machine. it can change in it's boxes or blocks for 2 seconds showing many random pictures before the result come out.

can anyone help me creating this website? Using html, css, javascript or anything.




Random.Next - Am I silently creating new instances?

Random.Next() randomness failures are almost always caused by creating and then using multiple instances of System.Random with the same seed, either with a time seed or a manual one. However, this is the only instance creation code in my class:

System.Random rNG;
if (string.IsNullOrEmpty(Map.Seed))
{
    rNG = new System.Random();
}
else
{
    rNG = new System.Random(Map.Seed.GetHashCode());
}

Looping through this second attempt code correctly creates random numbers:

var resourceRoll = rNG.Next(0, this.ResourceByRoll.Count);
var resourceRow = from row in this.ProcGenResourceTable.AsEnumerable()
    .Where(row => row["Resource"].Equals(
        this.ResourceByRoll[resourceRoll]
    ))

Looping through this original attempt code often creates the same number twice in a row:

var resourceRow = from row in this.ProcGenResourceTable.AsEnumerable()
    .Where(row => row["Resource"].Equals(
        this.ResourceByRoll[rNG.Next(0, this.ResourceByRoll.Count)]
    ))

Am I somehow silently creating a new instance of System.Random when using a Random.Next call as a dictionary index? Why does my original code often return the same number twice in a row?

If it matters:

  • This class is a Unity script
  • I am using System.Random, not UnityEngine.Random
  • My complete class is below:

using Assets.Code.Tools;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using UnityEngine;

public class Map : MonoBehaviour
{
    public static int Length { get; set; }
    public static int Width { get; set; }
    public static int ResourceChanceDenominator { get; set; }
    public static string Seed { get; set; }
    private static int[,] objectGrid;
    private DataTable ProcGenResourceTable { get; set; }
    private Dictionary<int, string> ResourceByRoll { get; set; }
    private List<GameObject> prefabTrees;
    private List<GameObject> prefabStones;


    private void Start()
    {
        this.prefabTrees = GeneralTools.GetPrefabsWithTag("Tree");
        this.prefabStones = GeneralTools.GetPrefabsWithTag("Stone");

        GenerateMap();
    }


    public void GenerateMap()
    {
        var procGenResourceTable = Resources.Load("ProcGenResourceTable") as TextAsset;
        if (procGenResourceTable != null)
        {
            this.ProcGenResourceTable = GeneralTools.GetDataTableFromCSV(procGenResourceTable, "|", true, false);
        }
        else
        {
            Console.WriteLine("ProcGenResourceTable could not be found");
            return;
        }

        Map.objectGrid = new int[Map.Width, Map.Length];

        this.ResourceByRoll = GetPopulatedResourceByRollDictionary();

        System.Random rNG;
        if (string.IsNullOrEmpty(Map.Seed))
        {
            rNG = new System.Random();
        }
        else
        {
            rNG = new System.Random(Map.Seed.GetHashCode());
        }


        for (var i = 0; i < Map.Length; i++)
        {
            for (var j = 0; j < Map.Width; j++)
            {
                var roll = rNG.Next(Map.ResourceChanceDenominator);

                if (roll == 1)
                {
                    // var resourceRoll = rNG.Next(0, this.ResourceByRoll.Count);
                    var resourceRow = from row in this.ProcGenResourceTable.AsEnumerable()
                                      .Where(row => row["Resource"].Equals(
                                            this.ResourceByRoll[rNG.Next(0, this.ResourceByRoll.Count)]
                                          ))
                                      select new
                                      {
                                          ModelFamily = row["Model Family"],
                                          Tags = row["Tags"]
                                      };

                    foreach (var row in resourceRow)
                    {
                        GameObject resource = null;

                        switch (row.ModelFamily)
                        {
                            case "Tree":
                                resource = Instantiate(this.prefabTrees[rNG.Next(this.prefabTrees.Count - 1)], new Vector3(i, 0, j), new Quaternion());
                                break;
                            case "Stone":
                                resource = Instantiate(this.prefabStones[rNG.Next(this.prefabStones.Count - 1)], new Vector3(i, 0, j), new Quaternion());
                                break;
                            default:
                                resource = Instantiate(this.prefabTrees[rNG.Next(this.prefabTrees.Count - 1)], new Vector3(i, 0, j), new Quaternion());
                                break;
                        }

                        var tagsListForResource = row.Tags.ToString().Split(new char[] { '|' }).ToList();
                        if (tagsListForResource.Contains("Resource"))
                        {
                            resource.tag = "Resource";
                        }
                    }
                }
            }
        }
    }


    private Dictionary<int, string> GetPopulatedResourceByRollDictionary()
    {
        var resourceByRoll = new Dictionary<int, string>();

        foreach (DataRow row in this.ProcGenResourceTable.Rows)
        {
            if (!string.IsNullOrEmpty(row["Weight"].ToString()))
            {
                for (var i = 0; i < Convert.ToInt32(row["Weight"]); i++)
                {
                    resourceByRoll.Add(resourceByRoll.Count, row["Resource"].ToString());
                }
            }
        }

        return resourceByRoll;
    }
}



Is there a way to make alert boxes randomly appear?

Basically, I am currently developing an app that is supposed to be a "companion", which needs the app to be proactive in seeking interaction. To this end, I was thinking of making alert boxes that can appear randomly in order to take initiative in engaging the user. Is there any way to do this?

Thank you.




clang - poor rand() implementation

I had made a Pong game where I had to randomize the throw of the ball. To do this, I used the inbuilt random number generator and got good results in Ubuntu/GCC. On porting the code to Mac and compiling, the ball would only be projected in a single direction, meaning that the rand() function in clang was not working as expected.

I have since reverted to a custom number generator, but here's the original problematic code in the game:

srand(time(NULL));
float ang = ((float)rand())/RAND_MAX * 120 - 60;
int side = (int)(((float)rand())/RAND_MAX * 2);

Upon further inspection, I created the following test program and compiled and ran it on both platforms.

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

int main(int argc, char** argv) {
    while (1) {
        int now = time(NULL);
        printf("Time now is %d\n", now);
        srand(now);
        int random = rand();
        printf("Random number generated is %d\n", random);
        sleep(1);
    }
}

The results (tabulated and calculated against RAND_MAX, which is 2147483647 on both systems) are as follows:

enter image description here

The results speak for themselves. While there is randomness in the clang version, as compared to the value of RAND_MAX, the randomness is very poor and is evidenced by the standard deviation of 0, compared to the standard deviation of 0.328 on gcc.

What are the reason(s) for this poor behaviour of rand() on clang? I would also like to see the reference implementation of this function in the header file. This seems nonstandard, and I must not be the only one who ran into problems while porting programs using this method to Mac. What other design principles are good practice while using/relying upon random number generators?




vendredi 30 octobre 2020

Randint is not working and i have no idea why

import turtle#importer turtle pour pouvoir l'utiliser import random from random import random #importer random pour pouvoir laisser le choix à l'ordinateur. Le choix sera aléatoire. #pour pouvoir utiliser screen turtle, demanderdes questions à l'utilisateur from turtle import Screen, Turtle #from random import random

is there a problem in the way i coded this? My problem is that after this, when i try to use randint like so:

turtle.forward(random.randint(100,400))

it gives me this error:

Traceback (most recent call last): File "/Users/ritamansour/Desktop/tyfkgjhv.py", line 62, in turtle.right(random.randint(1,360))#met que ce soit un random chiffre ici AttributeError: 'builtin_function_or_method' object has no attribute 'randint'

I dont understand where the problem is, because randint is apart of import random. If you need to see the full code, let me know. Thank you.




Python: How to create a DataFrame in which last column (i.e. fifth column) is the addition of first four column

A   B   C   D  Total
2   2   1   2   7
1   1   3   1   6
2   2   1   1   6
1   2   1   1   5

Here Column A, B, C, and D are generated using np.random.randint(1,3,size=4). Total is the addition of A, B, C, and D (i.e., Total = A+B+C+D). Only the Condition is the Value of Total should be more than 7.




random integers reading and writing a file. Attempting to create multiple functions using a range 0,501

Im working on some python assignments for class and I cannot answer this question. I cannot find the error in my code. The error I receive is TypeError: 'function' object is not iterable. The question is:

a. Random Number File Writer Function Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file.

b. Random Number File Reader Function Write another function that reads the random numbers from the file "random.txt", displays the numbers, then displays the following data:

The total of the numbers

The number of random numbers read from the file

c. Main Function Write a main function that asks the user about how many random number the user wants to generate. It them calls the function in a. with the number the user wants as an argument and generates random numbers to write to the file. Next, it calls the function in b.

Here is my code:

import random
def random_Write(num):
# Open a file  for writing 
    file_w = open('random.txt', 'w')
       
    for i in range(0,num):
        rand = random.randrange(1,501)
        file_w.write(str(rand) + '\n')
        #closing file
    file_w.close()
        
def random_Read():
# Reading from file
    readFile = open('random.txt', 'r')
    count = 0
    total = 0
    for lines in random_Read:
        count +=1
        total += float(lines)

        print ('number count: ', str(count))
        print ('The numbers add up to: ', str(total))
        readFile.close()

def main():
    num = int(input("How many numbers would you like to generate?: "))
    random_Write(num)
    random_Read()

main()



Calculating Intra class correlation in random intercept ordered probit model (mixor package in R)

I am using Mixor package (https://www.rdocumentation.org/packages/mixor/versions/1.0.4/topics/mixor) to analyze influencing factors on individuals' injury severity. I considered individuals involved in a crash as a cluster. The issue is I couldn't figure out how to calculate intra class correlation to make sure my assumption was correct.

enter image description here




How to get 5 random number from 0 to 10 that all are different? php [duplicate]

suppose i have an array

$array = [2,55,66,446,98,353,5435,36,335,35,33,33,33,33,33,333,333];

I will need 5 random indexes

$random1 = rand(0, $array.length() -1);
$random2 = rand(0, $array.length() -1);

but some times they will give equal results. sorry for php and javascript mess up




Random dice roll with 6 counters using arrays

This excersise is a bit challenging. Beginner coder using Javascript console. I can't figure out how to print each number in it's own row.

Question:

Use variables, arrays and constants to show how random dice roll. Define a loop that will call the random function 10000 times. Use 6 counters to show when each number appears. Display the die number and the number of times it appeared followed by a scaled histogram that shows 1 star for each 40 appearances.

Output should look like this:

1: (1587) 11111111111111111111111
2: (1542) 222222222222222
3: (1561) 333333333333333333333333
4: (1590) 44444444444444444444444
5: (1523) 555555555555555555
6: (1509) 66666666666666666666

Here is what I have so far.

var NUM_ROLLS = 10000;

function start(){
    var rolls = diceRoll();
    printArray(rolls);
}

//I divided NUM_ROLLS by 500 because I didn't want it to crush.//
//My output is not correct.//

function diceRoll(){
    var rolls = [];
    for(var i = 0; i < NUM_ROLLS/500; i++){
        if(Randomizer.nextBoolean()){
            rolls.push([1]);
            rolls.push([2]);
            rolls.push([3]);
            rolls.push([4]);
            rolls.push([5]);
            rolls.push([6]);
        
        }
    }
    return rolls;
}

function printArray(arr){
    for(var i = 1; i < arr.length; i++){
        println(i + ": " + arr[i]);
    }
}



random generator correlates 100% - why?

I am trying to use Intel MKL random generator, but when checking it randomness through correlation, I can see I am getting 100% correlation - why?

Initialized MKL random generator:

    RandomGenerator::RandomGenerator()
{
    vslNewStream (&_stream, VSL_BRNG_MCG31, VSL_RNG_METHOD_UNIFORM_STD);

    vsRngUniform (VSL_RNG_METHOD_UNIFORM_STD, _stream, 1000, _numbers.data(), 0.0f, 1.0f);
    
        _index = 0;
    }

float
RandomGenerator::get_float(float a, float b)
{
    const auto u = _numbers[_index];

    _index++;

    _update();

    return a + (b - a) * u;
}

However, when checking the correlation of the different initializations, it correlates 100%. What could be the problem here?

    for (int32_t i = 0; i < 5; i++)
    {

        RandomGenerator random;

        int32_t ncount = 0;

        float avg = 0;

        std::vector<float> x, y;

        for (int32_t j = 0; j < 100; j++)
        {
            x.push_back(random.get_float(0,10));
        }

        for (int32_t j = 0; j < 100; j++)
        {
            y.push_back(random.get_float(0,10));
        }

        float avgx = 0;

        float avgy = 0;

        for (int32_t j = 0; j < 100; j++)
        {
            avgx = avgx + x[j];

            avgy = avgy + y[j];
        }

        avgx = avgx / 100;

        avgy = avgy / 100;

        float xx = 0;

        float yy = 0;

        for (int32_t j = 0; j < 100; j++)
        {
            xx = xx + (x[j] - avgx)*(y[j] - avgy);

            yy = yy + (x[j] - avgx)*(x[j] - avgx)*(y[j] - avgy)*(y[j] - avgy);
        }

        std::cout<<avgx<<std::endl<<avgy<<std::endl;

        std::cout<<xx/std::sqrt(yy)<<std::endl;

    }
}

Output:

4.99885 5.10161 0.120765 4.99885 5.10161 0.120765




Unity C# Random Position Around A Point You Clicked

My problem is that the Unity Random.onUnitCircle doesn't work as supposed. The target is to choose a random positions in a circle around a point where the player has clicked. Also the points should not overlap and have some space between them.This is the code that runs in Update. enter image description here The objects spawn with an offset and I don't know why.Also objects spawn inside other objects.




How to output different random number in do while loop each loop Java

So i am very new to creating public classes and methods and we had an assignment to create a harry potter game in which 2 players roll random numbers which are assigned to spells which each have their own attack damage and defence capabilities. My main issue is that the random number which is assigned to the spells in the do while loop only outputs 2 random sets of spells (a set has 2 spells, one for attack and one for defence), I have tried testing out printing random numbers in another program and it worked, I feel like it might have

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


public class Game {
  
  public static void main (String [] args) {
    
  Player p2 = new Player ();  
  Player p1 = new Player ();
  Scanner input = new Scanner (System.in);
  Random rand = new Random();
  int y = 0;
  int ready;
  int p1r = p1.roll();
  int p2r = p2.opproll();
  int p2defdmg = p2.getDefensedmg(p2r);
  int p2attdmg = p2.getAttackdmg(p2r);
  int p1defdmg = p1.getDefensedmg(p1r);
  int p1attdmg = p1.getAttackdmg(p1r);
  int p1attfinal = (p1attdmg - p2defdmg);
  int p2attfinal = (p2attdmg - p1defdmg);
  int p2health = p2.getHealth();
  int p1health = p1.getHealth();
  int p2healthfinal = p2health - p1attfinal;
  int p1healthfinal = p1health - p2attfinal;
  
  System.out.println ("Please enter a name for Player 1.");
  p1.setName(input.next());
  
  System.out.println ("Please enter a name for Player 2.");
  p2.setName(input.next());
  
  System.out.println ("Welcome players " + p1.getName() + " and " + p2.getName() + "!\n\n");
  
  do {
  
  System.out.println ("Player " + p1.getName() + " is now attacking. They have rolled a " + p1r + " which is " + p1.getAttack(p1r) + " with a potential of dealing " + p1.getAttackdmg(p1r) + " damage!\n");
  System.out.println ("Player " + p2.getName() + " is now defending. They have rolled a " + p2r + " which is " + p2.getAttack(p2r) + " with a potential of defending " + p2.getDefensedmg(p2r) + " damage!\n");
  
  if (p2defdmg >= p1attdmg) {
    
    System.out.println (p2.getName() + " has successfully defended " + p1.getName() +"'s attack!\n");
    
  }
  
  else {
    
    System.out.println (p2.getName() + "'s defense failed! " + p1.getName() + "'s attack has dealt " + p1attfinal + " damage! Player 2's health has dropped to " + (p2healthfinal) +"\n");
    
  }
  
  do {
    
  System.out.println ("Ready for the next round? 1 = Yes\n\n");
  ready = input.nextInt();
  
  if (ready == 1) {
  y = 0;  
     
  }
 
  else {
   y = 1;
    System.out.println ("Please enter the requested number.");
    }  
 }while (y == 1);
 
 
   System.out.println ("Player " + p2.getName() + " is now attacking. They have rolled a " + p2r + " which is " + p2.getAttack(p1r) + " with a potential of dealing " + p2.getAttackdmg(p2r) + " damage!\n");
  System.out.println ("Player " + p1.getName() + " is now defending. They have rolled a " + p1r + " which is " + p1.getAttack(p2r) + " with a potential of defending " + p1.getDefensedmg(p1r) + " damage!\n");
  
  if (p1defdmg >= p2attdmg) {
    
    System.out.println (p1.getName() + " has successfully defended " + p2.getName() +"'s attack!\n");
    
  }
  
  else {
    
    System.out.println (p1.getName() + "'s defense failed! " + p2.getName() + "'s attack has dealt " + p2attfinal + " damage! Player 1's health has dropped to " + (p1healthfinal) +"\n");
    System.out.println ("The next round will now begin!\n");
  }
  
  do {
    
  System.out.println ("Ready for the next round? 1 = Yes\n\n");
  ready = input.nextInt();
  
  if (ready == 1) {
  y = 0;  
     
  }
 
  else {
   y = 1;
    System.out.println ("Please enter the requested number.");
    }  
 }while (y == 1);
  
     System.out.println ("-----------------------------------------------------------------------------------------------------------------------------\n");
   
  }while (p1health > 0 && p2health > 0);
 
    if (p1health <= 0) {
    
    System.out.println ("Game Over! " + p2.getName() + " Wins!");
    
  }
  
  else {
    
    System.out.println ("Game Over! " + p1.getName() + " Wins!");
    
  }
    
    
   }
}



R Radom data split based on 2 columns

I have data like this (column ObjectID and Cost) and I normally split data using:

sample.split(data$Cost, SplitRatio=0.7)

But in this case I want keep 'Cost' as relative ratio but also I want to use ObjectID - so each ObjectID can be only in test or train group. How to random split this?

ObjectID Cost   Type
12345   1624    Test
12345   1175    Test
12345   1049    Test
12345   1733    Test
11111   1945    Train
11111   1989    Train
22222   1448    Test
22222   1815    Test
22222   1244    Test
33333   1355    Train
33333   1134    Train
44444   1478    Train
44444   1082    Train
44444   1147    Train
44444   1290    Train
55555   1383    Train
55555   1378    Train
55555   1288    Train



How do I find the last value of a randomly generated int in c#?

So basically I'm trying to find both last positions of X and Y of my player in a .NET Core console application.

Every time I press W, A, S or D, it randomly generates positions (A and D for X values, W and S for Y values) in a map 1000px by 1000px. The problem is when every time it says the last values, only Y value is correct and X is still random.

So the question really is: How do I find the last value of a randomly generated int (for both X and Y values) in c#?

Edit1: Edited the language from portuguese to English

do
            {             
                targetPos = Console.ReadKey(true);

                if (targetPos.Key != ConsoleKey.Q)
                {
                    playerX = r.Next(0, 1000);
                    playerY = r.Next(0, 1000);
                }

                Console.WriteLine(" ");
                switch (targetPos.Key)
                {
                    case ConsoleKey.D:
                        playerX++;
                        Console.WriteLine("Right - Position X: {0} ", playerX);
                        Console.WriteLine();
                        break;

                    case ConsoleKey.A:
                        playerX--;
                        Console.WriteLine("Left - Position X: {0} ", playerX);
                        Console.WriteLine();
                        break;

                    case ConsoleKey.S:
                        playerY--;
                        Console.WriteLine("Down - Position Y: {0} ", playerY);
                        Console.WriteLine();
                        break;

                    case ConsoleKey.W:
                        playerY++;
                        Console.WriteLine("Up - Position Y: {0} ", playerY);
                        Console.WriteLine();
                        break;

                    case ConsoleKey.Q:
                        Console.WriteLine("\nLast Position X: {0}", playerX);
                        Console.WriteLine("\nLast Position Y: {0}", playerY);
                        Environment.Exit(0);
                        break;
                }
                Console.WriteLine(targetPos.Key.ToString());
            } while (targetPos.Key != ConsoleKey.Escape);



How to create a DataFrame in which last column (i.e. fifth column) will be the addition of first four column

The first four columns are randomly generated between a certain range. The fifth column contains the addition of the first four columns. The value of the fifth column should not be more than 10.




Program displays error when user has to input the value of the random number

I have been asked to get the program to generate an array of 15 random integers and then to ask the user to input the number from the array and for it to display a message saying that it was in the array, however, I get an error instead.

import numpy as ny
randnums = ny.random.randint(1,101,15)

print(randnums)

target = int(input("Please pick a random number: "))

for counter in range(0,15):
  while target != randnums:
    print("This number is not in the list")
    target = int(input("Please pick a random number: "))
  else:
   if target == randnums:
      print("The number" , target , "has been found in the list.")

Output:

Traceback (most recent call last):
  File "python", line 9, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()



Lightweight RandomState-like object in Python?

Is there a lightweight alternative to numpy's RandomState object in Python?

This object saves 624 integers to generate random numbers, however more lightweight methods to generate random numbers are possible (e.g. store integer s which is hashed for random number generation, then save s+1 as next state).

Is there a library which does something similar to the proposed method, while guaranteeing uniformity (generated numbers look like from uniform distribution) and independence (generated random numbers do not look like they have some dependence between each other)?




Question About Cookies and Python Requests

So I am trying to make a request to a site every 15 seconds or so and about every 15 minutes, I am required to do a captcha again, and that changes my cookie. Would I need to use 2Captcha or something to bypass this captcha or could I randomize part of the cookie or something? I don't know much about cookies, but the cookie that is changing is the Header.

Thanks and have a good day!




jeudi 29 octobre 2020

Generate random & unique 4 digit codes without brute force

I'm building an app and in one of my functions I need to generate random & unique 4 digit codes. Obviously there is a finite range from 0000 to 9999 but each day the entire list will be wiped and each day I will not need more than the available amount of codes which means it's possible to have unique codes for each day. Realistically I will probably only need a few hundred codes a day.

The way I've coded it for now is the simple brute force way which would be to generate a random 4 digit number, check if the number exists in an array and if it does, generate another number while if it doesn't, return the generated number.

Since it's 4 digits, the runtime isn't anything too crazy and I'm mostly generating a few hundred codes a day so there won't be some scenario where I've generated 9999 codes and I keep randomly generating numbers to find the last remaining one.

It would also be fine to have letters in there as well instead of just numbers if it would make the problem easier.

Other than my brute force method, what would be a more efficient way of doing this?

Thank you!




How do I pop the value returned from my array?

So I have a function,

def Multiples(OGvalue, count):
    multiples = []
    for i in range(count):
        multiples.append(i*OGvalue)
    multiples.pop(1), multiples.pop(0)
    return (multiples[randrange(len(multiples))])

that is being called elsewhere in my program. Now, I don't want to random value that is given to repeat, so I want to remove it from my array after it is used, how would I go about doing that?




How can I create a random list of integers in python from 1 to 5 with mean 4.6 and length 557? [closed]

course A has 312 ratings and a avg rating of 4.7

course B has 557 ratings and a avg rating of 4.6

I want to know with which course do I have higher chances of having a good experience

I think if a create an array with random integers between 1 and 5 with the mean equal to the avg rating of the course and with size equal to the length of the number of ratings. Then I just need to add this list [1, 2, 3, 4, 5] simulating my experience with the course and finally I can calcule the new average then to know with which course do I have higher chances of having a good experience

Thank you!




Python : get random data from dataframe pandas

Have a df with values :

name     algo      accuracy
tom       1         88
tommy     2         87
mark      1         88
stuart    3         100
alex      2         99
lincoln   1         88

How to randomly pick 4 records from df with a condition that atleast one record should be picked from each algo column . here algo columns has only 3 unique values (1 , 2 , 3 )

Sample outputs:

name     algo      accuracy
tom       1         88
tommy     2         87
stuart    3         100
lincoln   1         88

sample output2:

name     algo      accuracy
mark      1         88
stuart    3         100
alex      2         99
lincoln   1         88



java помогите сделать задания [closed]

enter image description here

помогите сделать лабу очень нужно




seed for different numpy functions

    a = (np.random.rand(10) > 0.1).astype(int)
    b = np.random.binomial(1, 0.9, 10)
    c = np.random.choice([0, 1], 10, [0.1, 0.9])

There are at least 3 different ways in numpy by which I can get an array of 0 and 1 (the ones are added with a certain probability p (p=0.9 in example)). When I use np.random.seed(1), the certain method always returns the same array. However, all the above methods create different arrays even with the same seed. Is this happening because they all have different PRNG algorithms or just some of them are not affected by np.random.seed(1)?




Creating a deck cards that can be shuffled and dealt using a class [closed]

I'm working on a task where I have to create a class that represent a deck with up to 52 different playing cards. The deck of cards should be represented as the rankings:

ranking = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

The suits of the cards are represented as the classic Clover, Diamond, Heart and Spade, as shown here:

suite = ["C", "D", "S", "H"]

The class should be built in this way:

class  Deck:
    def  __init__(self):
        ...
    def  hand(self , n):
        ...
    def  deal(n, p):
        ...
    def  __str__(self):
        ...

The cards dealt should be represented in the way as example: seven of diamonds is represented as the string "D7". Every time an object of this class is created, it will will contain all 52 cards as a list. This list will be shuffled. The method hand in the class should deal n cards from the deck and returns them as a list. The cards dealt should be removed from the main deck. The method deal should deal out an amount of hands (p) of n cards. This should return a list of a list. The method str should return the cards in the current deck in the order they are currently shuffled.

I'm uncertain what code should be written in the different methods to get this to work. Since I am struggling quite a bit all help is welcome.




Explanation of card shuffling algorithm (java)

I was trying to better understand in a common Java shuffle deck of cards algorithm, this piece of code:

// Random for remaining positions. 
int r = i + rand.nextInt(52 - i); 

Why is it necessary to "pad" or add i index to the resultant random number? It looks like as you iterate and add i, by subtracting i, you keep the max possible range of random numbers consistent from 0 to 51, but why not just do:

int r = rand.nextInt(52);

Full code:

      
    // Function which shuffle and print the array 
    public static void shuffle(int card[], int n) 
    { 
          
        Random rand = new Random(); 
          
        for (int i = 0; i < n; i++) 
        { 
            // Random for remaining positions. 
            int r = i + rand.nextInt(52 - i); 
              
             //swapping the elements 
             int temp = card[r]; 
             card[r] = card[i]; 
             card[i] = temp; 
               
        } 
    } 



How to randomise the characters '+' and '-' in java

I'm coding an arithmetic game where the user is asked a series of addition questions. I want to however randomly assign an operator for each question so that the question could be either:

Question 1: num1 + num2 =

or

Question 2: num1 - num2 = 

I have been using the Math.random() method to randomise num1 and num2 the last thing I am struggling on is randomly generating '+' and '-'.

Is it something to do with the ASCII values of these two characters and then I can randomly pick between them? Thanks for the help!

As a side note, I want to ask the user to 'press enter' to start the game, but i'm not sure how to do it. Currently I've got the user to enter 'y' to start. Any ideas? Thanks so much.

//prompt user to start the game
            System.out.println();
            System.out.print("Press y to Start the Game: ");
            String start_program = keyboard.next();
    
            if (start_program.equals("y")) {

heres my code so far:

public static void main(String[] args) {
        //mental arithmetic game
        System.out.println("You will be presented with 8 addition questions.");
        System.out.println("After the first question, your answer to the previous question will be used\nas the first number in the next addition question.");

        //set up input scanner
        Scanner keyboard = new Scanner(System.in);


        //declare constant variables
        final int min_range = 1, max_range = 10, Max_Number_of_Questions = 8;

        long start_time, end_time;

        //generate 2 random numbers
        int random_number1 = (int) ((Math.random() * max_range) + min_range);
        int random_number2 = (int) ((Math.random() * max_range) + min_range);

        //declare variables
        int question_number = 1;
        int guess;


        //prompt user to start the game
        System.out.println();
        System.out.print("Press y to Start the Game: ");
        String start_program = keyboard.next();

        if (start_program.equals("y")) {


            //start timer
            start_time = System.currentTimeMillis();

            //ask the question
            System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
            //take in user input
            guess = keyboard.nextInt();


            while (guess == (random_number1 + random_number2) && question_number < Max_Number_of_Questions) {
                System.out.println("Correct");
                ++question_number;
                //generate a new question
                //generate 2 random numbers
                random_number1 = guess;
                random_number2 = (int) ((Math.random() * max_range) + min_range);
                //ask the question again
                System.out.print("Question " + question_number + ": What is " + random_number1 + " + " + random_number2 + "? ");
                //take in user input
                guess = keyboard.nextInt();
            }
            end_time = System.currentTimeMillis();
            int time_taken = (int) (end_time - start_time);

            if (guess != (random_number1 + random_number2))
                System.out.println("Wrong");
            else {
                System.out.println();
                System.out.println("Well Done! You answered all questions successfully in " + (time_taken / 1000) + " seconds.");
            }

        }
    }



F# Card Shuffle function

I've been trying to create a simple card game in F#, i have created a simple randomizer function using system.Random.


type card = int
type deck = card list
let rand : int -> int = let rnd = System.Random ()
                        in fun n -> rnd.Next (0 , n )

However my problem is that i don't know how to create a shuffle function deck -> deck,using the rand function.

Any help is wanted.




why I get a second set of numbers after selecting switch

What am I doing wrong? I want it to show me a set of two numbers to add, subtract, etc. Instead, I get the numbers a and b, and after choosing options a and b they are drawn again. Why?

public class Dzialania_na_liczbach
{
    public static void Main(string[] args)
    {
        Random generator = new Random();
        int a = generator.Next(999);
        int b = generator.Next(999);
        double wynik = 0; 
        Console.WriteLine("a = " + a + "\nb = " + b);
        Console.WriteLine("Co chcesz zrobić?");
        Console.WriteLine("D - dodać \nO - odjąć \nM - pomnożyć \nZ - podzielić");
        string odp = Console.ReadLine().ToLower();
        switch (odp)
        {
            case "d":
                wynik = a+b;
                //Console.WriteLine("a = " + a + "\nb = " + b);
                Console.WriteLine("suma to: " + wynik);
                break;
            case "o":
                wynik = (double)a - b;
                Console.WriteLine("różnica to: " + wynik);
                break;
            case "m":
                wynik = a * b;
                Console.WriteLine("iloczyn to: " + wynik);
                break;
            case "z":
                if (b != 0)
                {
                    wynik = (double)a/b;
                    Console.WriteLine("iloraz to: " + wynik);
                }
                else
                {
                    Console.WriteLine("dzielenie przez liczbę 0 jest niewykonalne");
                }

                break;
            default:
                Console.WriteLine("sorry, nie ma takiej opcji");
                break;
        }
    }
}



I want to select some random numbers but their addition should always be even in Python

import random


for i in range(100):
    a = random.randint(1, 20)
    b = random.randint(1, 20)
    c = random.randint(1, 20)
    if ((a + b + c) % 2) == 0:
        print(str(a) + "," + str(b) + "," + str(c))

I tried this but I am not getting the desired output. I want it in a way that three random numbers are chosen between 1 and 20 such that their sum is always even. Here the programme prints only the outputs that are even it does not select the numbers in such a way. Hope you help me. Thanks!




Pyspark - how to mark parts of a sampled DataFrame?

I took a sample of an original DataFrame which gives me approximately 200000 records. I want to mark the sample such that it has three parts of marked records. 1/3 of the records is marked as sample_metric_1, another 1/3 is marked as sample_metric_2 and the rest of the records is marked as sample_metric_3.

sample_df = original_df.sample(False, .09, 5)

One way to do this that comes to mind is to apply a .withColumn() the parts of the DataFrame. But not sure how to correctly extract the needed data subsets from the sample?

Or maybe there is a better approach here?




mercredi 28 octobre 2020

How to get a random multiple of a given number within a range

I'm making a program in which a JPanel is created with a random RGB value and the user has to use buttons to match the color in another JPanel.

I want the random R, G, and B values to be multiples of 15, though, so the user can match the color more easily.

Right now my code looks like this:

int randRed = rand.nextInt(255);

and the same for green and blue. I could use a modulus to repeat the code until it happens to be a multiple of 15 but that would be terribly inefficient.

What is the best method to achieve a random multiple of 15 less than 255?




generate random values for pre-generated sets of math instructions

So I'm working on generating random math statements for various int types. the equations use PEMDAS (** / * + -) and can have inner math statements nested in () several times. I also want the math equations to be able to use a predefined list of variables in it that i know the value of but don't have control over the value of. Since I'm doing this for each int type, i need to make sure that the generated math doesn't create an overflow/underflow for whatever type is being used.

I have functions (gen_add, gen_sub, gen_pow etc) that take the value being operated on and generate another value that can be safely used in the equation without causing an overflow/underflow. I also have functions (checked_add, checked_sub etc) that can be used to check if two numbers would cause an overflow/underflow.

That part alone would usually be easy but the issue is I want to make it so i can "reroll" each math equation so the syntax stays the same every time but the values within change. To do this I'm using seeded RNG to create the syntax of the math equation then using unseeded RNG to generate the values.

The problem I'm running into is that i cant control whats returned from () equations like i can raw values. This leads to a lot of bad equations for basically any generated instruction set. I cant simply bruteforce the equations with random values until i get a valid one because for larger int types (like u128/i128) that could take an immense amount of time. The general technique I'm trying to use right now is:

x = 43u8;                               the variables used in the equation (i know but don't control)
y = 55u8;                               
type = u8                               the type for the equation (always the same for each seed)

[]  + x    + y    - ([]  ** [] )        generate syntax (always the same for each seed)                                          
[]  + 43u8 + 55u8 - ([]  ** [] )        fill variables with their current values                                                       
      43u8 + 55u8 is valid              check if overflow has already occurred between adjacent filled values, return error if true      
????????????????????????????????        generate nested vals that wont cause overflow                                       
5u8 + 43u8 + 55u8 - (5u8 ** 2u8)        generate surface level vals that wont cause overflow     

so basically, for each generated instruction set i need to fill the placeholders so that the given variables (x, y in the example) never go out of their int types range (0-255 in the example) during the calculation. Ive been stuck on this for a while now. Does anyone have any ideas on how i could do this?

if it matters, I'm doing this in rust. but i feel that this is more of a logistics problem than a language problem.




Asynchronous column iteration through an array

I'm trying to solve the following algorithmic problem:

I'm given an array (it could be a standard C/C++ array, a vector<vector<T> >, or something else... whatever is most suited to this problem is fine) populated with random non-zero values. I know the size of the array, m x n.

What I want to do is accomplish (either directly, or through an equivalent approach) the following: iterate through all n columns until a value over some threshold, t is found. Continue iterating in the remaining columns until either another value over t is found, or some maximum number of iterations has been reached.

If the max number of iterations has been reached, I continue from here iterating through all n columns until I again encounter a value exceeding threshold t. If I find a second value exceeding that threshold, I continue until I've either found a third value exceeding t, or I've reached the max number of iterations from the first value.

If I reach max iterations, I continue iteraitng through all n columns until I again encounter a value exceeding threshold t. If I find a third value, I add one to some count, and I continue iteration through all n columns.

So, in the end either I find three values, in three unique columns, exceeding the threshold, or I don't and I keep searching from the first found value + max iterations.


I'm not sure how to execute this. I have a few ideas:

  • Keep some sort of list of iterators, one for each column. Not sure where I'd go from there, though.
  • Have a for loop like for(int i = 0, j = 0, k = 0..., with one iterator for each column and changing the value of the iterator with if statements inside the loop. This quickly becomes pretty complicated, especially for large arrays, though.
  • Iterate through each row with nested for loops. When first value is found, save column index to an std::set. Start an iterator at 0 here. Continue iterating, adding found threshold value column #'s to the set each time one is found. Check each time if set size is 3. If set size is 3, add to count. When the iterator has reached the maximum value, reset to 0 and empty the set.

My goals:

  • Most important is readability. Many other people will be reading and using this. I understand that I'll likely need nested loops and such, but I'd like to avoid clutter as much as possible.
  • Speed. I'm looking at arrays with columns on the order of tens, and rows on the order of thousands or tens of thousands. Optimally, the code should be able to 'scan' the array in a few minutes time (I know that's a bit hand-wavy and there are a lot of factors at play, but hopefully that gives some sense of the 'constraints').

If it is at all useful to know, the random values are from a Gaussian distribution, with known values for mu and sigma.




Can someone help me figure out what to do on this random number guesser?

I have a random number guesser and I am trying to figure out how to get it to print and follow the other directions. Can someone help?

The instructions:

  1. Choose a random number from 0-100
  2. Get the first guess
  3. Loop while the guess does not equal the random number,
  4. If the guess is less than the random number, print out “Too low!”
  5. If the guess is greater than the random number, print out “Too high!”
  6. Get a new guess (save it into the same variable)
  7. Print out something like “You got it!”

My code so far:

Scanner user = new Scanner(System.in);
      int randoNum = 1 + (int) (Math.random()* 99);
      int guess;
      System.out.println("Guess a number from 0 to 100");
      guess = user.nextInt();
      while (guess != randoNum); 
      {
        if (guess < randoNum)
        {
          System.out.println("Too low!");
        }
        else if (guess > randoNum)
        {
          System.out.println("Too high");
        }
        else 
        {
          System.out.println("You got it!");
        }
      }



Why does rand()%10+1 give me a number between 1-10?

Im fairly new to programming

So i was actually trying to figure something out

Why does rand()%10+1 give us a number between 1-10 whereas 32767%10 is actually 7?




Sampling by quantiles in RStudio

I have a dataset in RStudio containing a column with all counties, a column with their respective states and another with their estimated population. I want to sample 2 random counties from each state. The sample however has to be composed by approximately one fifth of counties in each quintile by population. How should I go about it? I know that I can calculate the quintiles using the quantile() function, but not really sure how to proceed from there.




I can't find the problem with my particle simulation program in Java

I'm working on a project where I'm supposed to simulate the movement of a particle in the shielding of a reactor. Here is more information from the prompt.

A circular slab of uniform thickness (5 units) is to be used to shield a nuclear reactor. A radioactive particle entering the shield follows a random path by moving forward, backward, left, or right with equal likelihood, in jumps of one unit (You may assume the radioactive particle begins in the shield (position one)). A change in the direction of the particle is interpreted as a collision with a Lead atom in the shield. For example, heading forward then right would count as a collision, while going forward then forward would not. After 10 collisions the particle’s energy has dissipated and will not escape the shield. If the particle has moved forward 6 positions (without exceeding 10 collisions), it has escaped the shielding. If the particle returns to the reactor, it has not escaped the shield. There are three possible ways a simulation can terminate for a radioactive particle: (i) The particle has moved forward 6 positions (without exceeding 10 collisions) (ii) The particle has returned back to the shield, i.e., it has moved one unit backward from its starting position (iii) Energy of the particle has been dissipated, i.e., it has collided with the lead atom 10 times Write a program to simulate 1000 particles entering the shield and determine what percentage of the particles escape the shielding. Assumptions:

  1. The particle starts in the shield wall.
  2. The initial movement of the particle is going forward.

Here's my current code. Even when I simulate 1000000000 particles and look at the number of individual escaped particles, I get 0 particles escaping each time. Is there something wrong with my RNG or my nested loops and conditionals?

public class ParticleSimulation {
    public static void main(String[] args) {
        int numParticles = 1000000000;
        int yPos = 0;
        int prevDir = 1;
        int direction;
        int numEscaped = 0;
        int numCollisions = 0;
        while (numParticles > 0) {
            while (numCollisions < 10 && yPos >= 0 && yPos < 6) {
                direction = (int)(Math.random() * 4 + 1);
                if (prevDir != direction) {
                    numCollisions++;
                    prevDir = direction;
                }
                if (direction == 1) {
                    yPos++;
                }
                if (direction == 2) {
                    yPos--;
                }
            }
            if (yPos >= 6 && numCollisions < 10) {
                numEscaped++;
            }
            numParticles--;
        }
        System.out.println(numEscaped + " particles escaped the lead shielding.");
    }
}



How can I obtain a random number for each column in a matrix?

I have a matrix with n columns and 2 rows. But for each column I would like to pick a random number. I have been searching about this but I´ve gotten nothing. At this point I am using very small matrices but my code will be applied to big matrices.

I have this matrix, (more columns will be added)

          [,1]     [,2]
fcMax 2.391416 1.390129
fcMin 2.316555 1.374918

and I want to obtain a vector with dim = n (in this case 2, the number of columns), which is constructed by choosing a random number for each column.




I want to make a numpy array

As the title says I want to make a numpy array.

array=np.random.randint(2,size=(4,4))

First question, at this time I want to make code that size can be changeable. What should I do?

top = input("Top(k):")

Second question, I want to receive k value like this and send output as much as this value. At this time, I wanna print the top k-row indexes from the weakest to the strongest (weakest:smaller number of ones) How to do it??:(

example like this.

input

[[1,0,0,0],
[1,1,1,1],
[1,0,0,0],
[1,0,0,0]]

Top(k):2

output

0,2

if Top(k):4, output is

0,2,3,1




Best Way of Generating Random Domain Names

I need to make some request to as much websites as I could, so I have a small function that generates random domain names, (I need them as 'brute force' for making requests to this domains), this is my function:

from itertools import product
from string import ascii_lowercase

def _create_domain(self):
    return [''.join(i) for i in product(ascii_lowercase, repeat = 5)]

This function returns an array of all posible 5-letter combinations, and then I use that random words to create an url. Actually the majority of this 'words' isn't real domain names ['aaaaa', 'aaaab' ....] so it's a huge waste of time make requests to all this words, but I can't think of a better way of doing this, do you think there's a more optimal way?




When I try to get Random.Range from an Array and set an image I get "IndexOutOfRange" exception

I'm fairly new to programming and want to develop a Game that involves a slot machine. From my research I learned that I should use Arrays for this type of stuff. So I tried to make an array put my 3 images into it and show them random in the update function. When I start the project it shows one image and stops. After that I look at the console and I get a out of range exception. Please help me :/

here is my code

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


public Sprite[] sprites;  
    public Image image;
    public float StopTime;

void Update()
    {
        RandomingImage();
        

    }

    void RandomingImage()
    {
        gameObject.GetComponent<UnityEngine.UI.Image>().sprite = sprites[UnityEngine.Random.Range(0, sprites.Length)];

    }

    void EndRand()
    {
        enabled = false;
    }

    public void StopRand()
    {
        Invoke("EndRand", StopTime);

    }
    public void StartRand()
    {
        enabled = true;
    }
}



System.TypeInitializationException: "Null reference Exception". Slot Machine will not run [duplicate]

I am creating a slot machine game for a class project and am receiving this error.

System.TypeInitializationException: 'The type initializer for 'WindowsFormsApp5.SlotMachine' threw an exception.'

NullReferenceException: Object reference not set to an instance of an object.

I am attempting to have numbers display in my textboxes to show that random numbers were generated. Any help will do. I am just a beginner. Thank you.

Form2.cs class where the exception is occurring

private void btnSpin_Click(object sender, EventArgs e)
        {
            SlotMachine.SlotReader.spinSlot();


            txtGame1.Text = SlotMachine.SlotReader.getSlotOne().ToString();
            txtGame2.Text = SlotMachine.SlotReader.getSlotTwo().ToString();
            txtGame3.Text = SlotMachine.SlotReader.getSlotThree().ToString();
        }

SlotMachine Class

public class SlotMachine
    {
        //attributes
        int moneyCollected;
        int Betplaced;
        //instaniates classes
        public static Player player = new Player();
        public static Table table = new Table();
        public static RandomNumber randomnum = new RandomNumber();
        public static SlotReader SlotReader = new SlotReader();
}

SlotReader Class

This is boilerplate code, as I am just trying to display numbers in my form to see if it works disregard reelResult.

public class SlotReader {


  public void spinSlot()
        {
 //attributes
         int[] reelResult = { 0, 0, 0, 0, 0 };
        //first random number
        int Slot1;
        //second random number
        int Slot2;
        //third random number
         int Slot3;
         int max = 3;
        //how much was bet this round
         int betNum = 0;

        //Empty Constructor
        public SlotReader() {

        }

            Slot1 = SlotMachine.randomnum.pickRandomValue();
            Slot2 = SlotMachine.randomnum.pickRandomValue();
            Slot3 = SlotMachine.randomnum.pickRandomValue();
        }
        public int getSlotOne()
        {
            return Slot1;
        }
        public int getSlotTwo()
        {
            return Slot2;
        }
        public int getSlotThree()
        {
            return Slot3;
        }
    }

Any help would be extremely appreciated. It's a class assignment. I am trying my best to learn.




Python weighted random number within range

I am trying to write a function that will generate a weighted random number. Simply put, I have two ranges, and one of them falls within the other. In x% of the cases, the number should fall within the inner range, but in y%, it should be outside of that but within the outer range.

Generating weighted random numbers I found this question about weighted random numbers, but this results in a number picked from a list of options and not a random number within a range. Is it possible to do so?




Gaussians as a function of time in Python

I would like to create Gaussians with random amplitude and variance, as a function of time. I would like to use a day as a time frame, but it gives me an error.
TypeError: 'Timedelta' object is not iterable
Could you help me please.

from astropy import modeling
import random
import numpy as np
import matplotlib.pyplot as plt

t =pd.to_timedelta(np.arange(3600),unit='s')
x=random.randrange(15)
for i in range(x):
    y=random.uniform(-10, 10)
    z=random.randrange(5)
    p=random.choice(t)
    m = modeling.models.Gaussian1D(amplitude=y, mean=p, stddev=z)
    data = m(t)
    plt.plot(t, data)
plt.xlabel('time')
plt.show()



generating uniform distribution of integeres with python

I tried to generate an uniform distribution of random integeres on a given interval (it's unimportant whether it contains its upper limit or not) with python. I used the next snippet of code to do so:

propsedPython = np.random.randint(0,32767,proposedIndices.shape[0])%2048
propsedPythonNoMod = np.random.randint(0,2048,proposedIndices.shape[0])
propsedPythonNoModIntegers = np.random.random_integers(0,2048,proposedIndices.shape[0])
propsedPythonNoModRandInt = np.empty(proposedIndices.shape[0])
for i in range(proposedIndices.shape[0]):
    propsedPythonNoModRandInt[i] = randint(0,2048)

Plotting the above distributions producing.enter image description here Could somebody point me in the right direction why these spikes appear in al the different cases and or gives some advice which routine to use to got uniformly distributed random integers?

Thanks a lot!




generating two numbers with specific probability in C [closed]

I aim to generate numbers 1 and 2, with the probability of 1/250 for the number 1 to happen and the probability of 249/250 for the number 2 to happen.

I used a loop to run it 10 times and see what i would get but I've been getting a negative number for the number times that 1 has happened and 11 times for 2. I'm not sure what went wrong there.

int x;
x= (rand()%1000);

if(x<4){
return 1;
}else{
return 2; 
}



mardi 27 octobre 2020

Why does Math.random() round to incorrect values

Suppose I write

System.out.println (Math.random()*5);

then one would obtain and output of x in [0, 4.9...]. But upon casting it as an integer, the result I continuously see (in my course) is [0, 4]. My question is how we are defining the rounding function; I am familiar with the floor function, and the floor of 4.9... is precisely 5 due to there existing no epsilon larger than zero satisfying the output x existing in some epsilon neighborhood; i.e., the equality 4.9... = 5 suffices and because the floor of an integer is that integer, the result would be 5.

Where am I going wrong here?




What is wrong with this code for generating random integers in Java??? (Unexpected Outputs)

The code below is supposed to generate random integers from 97 till 122:

for(int x = 0; x < 10; x++) {
    int a = (int)(Math.random()*(26 + 97));
    System.out.println(a);
} 

The outputs I am getting are all over the place. They go below 97. Here are the outputs for one of the runs:

33
113
87
73
22
25
118
29
16
21



How can I randomly choose between multiple print commands?

How can I randomly choose between multiple print commands?

For instance...

I want to randomly choose one of these two print functions...

print ('The ball ', (random.choice (action_ball))
print ('The cat', (random.choice (action_cat))

then reference these two lists...

action_ball = ['rolled','bounced']
action_cat = ['purred','meowed']

to randomly generate one of these four sentences...

the ball rolled
the ball bounced
the cat purred
the cat meowed

I understand how to generate from one list:

import random
action_ball = ['rolled','bounced']
print ('The ball ', (random.choice (action_ball))

After that, I'm lost.




Making different random numbers

My function is working fine but needs to return 6 different random numbers, and eventually returns a pair of similar numbers. I tried to make it pass a simple condition if / else to run. If it doesn t pass, it is called again until the condition is satisfied.
Any suggestios how else to make sure my random function returns 6 different random numbers?

const randomNum = function() {  

  var al1, al2, al2, al4, al5, al6;
  function ran() {
    al1 = Math.floor((Math.random()*60)+1);
    al2 = Math.floor((Math.random()*60)+1);
    al3 = Math.floor((Math.random()*60)+1);
    al4 = Math.floor((Math.random()*60)+1);
    al5 = Math.floor((Math.random()*60)+1);
    al6 = Math.floor((Math.random()*60)+1);  
  }

    ran()    

  
    if(al1 != al2 || al2 != al3 ||  al3 != al4 || al4 != al5 || al5 != al6) {

       //do my code

    } else {

      ran()      
    }          
  }



How can I save the random output to use it in another function in python

I am new to python3 I am trying very hard to add the output of the function, is there any way that I can save an output of an random integer so that i can altogether add it please help me.

def dice():
    import random
    rollball = int(random.uniform(1, 6))
    return (rollball)

def dice2():
    import random
    rollball = int(random.uniform(1, 6))
    return (rollball)

print(dice())
input("you have 10 chances left")
print(dice2())
input("you have 9 chances left")
print(dice() + dice2())
#i want to print this last function but by adding only this first and second nothing else



Randomly selecting a subset from a dataset with same instances from each class in WEKA

I'm having a dataset with 68 instances. Out of the 68 instances, 34 instances are in class A and 34 instances are in class B. I need to select 40 data points.

It should contain is 20 from class A and 20 from class B. The randomly selected data should have the same instances of data. This needs to be done using WEKA.

I was able to pick 40 random instances. But the number of instances from each class is not similar. Can someone please help me on how to do it using WEKA.

This is how I done up to now.

Shuffled the dataset randomly by, filter --> Randomize

selected 40 instances by, filter --> Resample.

But the number of instances received were no 20 from each class. How can I fix this.




random copy and past in to textbox from pastbin an way i can do that ? c#

how do you make a button when you click the button random text from a past bin like will be put in the text box for ex click test:123 click test:244 ? pls help me or is there any other way to do this ? what I have tried can someone send me the way to do it with a check box that would be very cool : ).




Need help creating a random number generating button in google sheets

I want to generate a random number between 1 and the value in cell "a2" on the same sheet using a button. Is this possible?




How can you get random objects in python [closed]

Well you see I am creating a Pokemon game in Python and I have created a Pokemon class. Then I created the Pokemon as an object. I created 9 Pokemon. I want to pick a random pokemon object for the user to battle with so I used random.randint() and I even tried random.randrange() but it didn't work.




Java Script | Random image in HTML5 picture tag

Trying to make random images (I have a set of images, all following the pattern "imgN", where "N" is a number from 1 to 9) with HTML5 picture tag. No good till now. This is what I'm trying:

HTML code is:

<picture id="heroimg">
    <source class="rand_webp_srcset" srcset="img1.webp" type="image/webp">
    <source class="rand_jpeg_srcset" srcset="img1.jpg" type="image/jpeg">
    <img class="rand_jpeg_src" src="img1.jpg">
</picture>

Javascript code is:

var randomNum = Math.floor(Math.random() * 9) + 1
document.getElementsByClassName('rand_webp_srcset').srcset = 'img' + randomNum + '.jpg';
document.getElementsByClassName('rand_jpeg_srcset').srcset = 'img' + randomNum + '.jpg';
document.getElementsByClassName('rand_jpeg_src').src = 'img' + randomNum + '.jpg';

Any cue? Thanks.




What exactly does the parameter seed in MLContext do?

I am working in a ML project, I have never used C# and specially the ML.NET for this purpose. My question is: What does this line of code mean? I am creating an instance of the class MLContext, but I do not understand the parameters. Seed generates a random number but, what does :0 mean?

var mlContext = new MLContext(seed: 0);



Find the algorithm used to create next number in the sequence (Pseudo RNG)

The first number in a sequence is 0094332543029476 and the next number in the sequence is 0094332543031698. We know the difference between the two is 2222 and GDC is 2. I need to know the next number in the sequence. (And it's not 0094332543033920 after adding 2222). and it is also not 0094332543049474 by using 0094332543029476 + 2222*3^2.

The number of digits is fixed (16), the next number in the sequence is always positive and bigger than the previous one.

This means that some operation has been done to the first number which gives us 2222 as the number to add to make the second one.

There is an algorithm being applied to the first number(0094332543029476) (or its individual digits) to produce 2222 to be added and make the next one. Now this same algorithm must be applied to 0094332543031698 to produce the third number and so on.

This means that it is not based on 2222 and that there is an algorithm involved.

How would you approach this problem?

Thanks in advance.




Get all values in randomly selected JSON object

I'm retrieving a list of objects from a json call. They are quotes with values of 'Author' and 'Text'. Here is a small sample.

0:
author: "Thomas Edison"
text: "Genius is one percent inspiration and ninety-nine percent perspiration."
__proto__: Object
1:
author: "Yogi Berra"
text: "You can observe a lot just by watching."
__proto__: Object

Then I am selecting a random object from the list. I cant figure out how to get both values from the selected object. I can get text and author separately but I cant seem to get them both

these do work

data[ Math.floor(Math.random() * data.length) ]['text']
data[ Math.floor(Math.random() * data.length) ]['author']

I tried these and neither work

data[ Math.floor(Math.random() * data.length) ]['author','text']
data[ Math.floor(Math.random() * data.length) ]['author'],['text']

Thanks in advance




Testing condition in Java with random number generator [closed]

I am currently creating code for a simple game and the required task asks 'Place tiger in a random VACANT location (from 0-23) on the Board'.

I understand how to use random to generate a random integer but do not know how to repeat until the action has been performed.

I have bd.isVacant() to check if a particular spot is vacant and rn which generates a random number. If I did something like x = (int) rn * 24 and than ran if(bd.isVacant(x)){condition} would that just happen once? I need it to keep trying until random vacant position is found.




Implement Newton's method in python with a random number

The requirement is to use Newton's method to find the root of a function.

def newton(f, fprime, eps, maxiter=5000):
    from random import randint
    x = randint(-100, 100); n = 0
    # print(x)
    try:
        while n < maxiter:
            if abs(f(x)) < eps:
                # print(x)
                return x
            x = x - f(x)/fprime(x)
            # print(x)
            n += 1
            # print(n)
        return None
    except (ZeroDivisionError, ValueError):
        newton(f, fprime, eps, maxiter=5000)

The input function may not have a root, so maxiter is needed. Also needs to deal with the situation where f(x) doesn't exist or f'(x) = 0, so I chose to use random and call the function again.

When I test it with f = ln(x) and fprime = 1/x, it always returns nothing. The print functions in comments are just for test use, it seems that it can find the right value, just doesn't return it. I don't quite understand what's happening here.




lundi 26 octobre 2020

Is this static function thread safe?

Let's say I have this static function:

public static int GetRandomInt(int maxValue)
{
    Random r = new Random();
    return r.Next(maxValue);
}

I place the function in a class that has no property and it's only purpose is to get something from the parameter. Now I've been reading about the drawback of using static function in C#, but have not yet found a clear answer, is this thread safe? is the new instance of Random is cleaned everytime it finished? the function itself will be called by multiple functions across many users. another example is this :

public class People
{
    //usual class stuff

    public static double GetAverageAge() {
        SqlConnection conn = new SqlConnection()
        // proceed to get average age from database
        return averageAge;
    }
} 

Is the function GetAverageAge thread safe too, when I call SqlConnection there?




How do BLE IoT devices usually generate their private MAC addresses?

Are there any common ways for a BLE IoT device to generate its resolvable/non-resolvable private device addresses?

For example, it seems that in BR/EDR (classic Bluetooth) the spec demands the use of FIPS PRNGs, but I don't see the recommended/compulsory/popular ways to generate the 24-bit prand in resolvable private device addresses on Bluetooth Low Energy peripheral devices.

I wonder if resource constraints would stop IoT devices from using FIPS PRNGs. The results I found so far on MAC randomization are all about BLE on mobile devices...




How do you generate random objects in python? [closed]

I'm working on a game in Python and want to be able to generate random characters (think characters in an RPG with random stats, moves, levels, races, etc.) and have them be interacted with. I would also like for the game to be able to generate an infinite number of randomly generated characters. It's easy enough to generate the information, but I don't know how to assign them to an object and refer back to that object later. I realize this is probably a pretty complicated procedure, so if I could just get pointed in the right direction to learn how to do it it would be much appreciated.




How can I pick an especific random string up from an arrayString?

I have a situation where I received an input string with a random value contained there ("54403dd5-5f1d-4ba0-8477-9b16807ee285") basically that string is received from another source code but I just pasted there for reference, also notice that I split patterns in order to get a cleaner string output(this can be omitted). What I really need is how I can pick only that Id value up from there so I can process further. I also pasted the output generated with what I've done so far but not luck, If you have a better approach to get only this value without anything else I will appreciate.

String input = "\"{\"Protocol\":\"12345\",\"Version\":1,\"Timestamp\":\"2020-05-01T21:55:12.123456Z\",\"Assignment\":{\"Id\":\"54403dd5-5f1d-4ba0-8477-9b16807ee285\",\"Asset\":[]}}\"";
String pattern = @"\s-\s?[+*]?\s?-\s";
int found = 0;

String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);
foreach (var element in elements)
    Console.WriteLine(element);

Console.WriteLine("\nWe want to retrieve only the Id string value. That is:");
foreach (string s in elements)
{
    found = s.IndexOf("Id");
    Console.WriteLine(s.Substring(found + 5));
}

Output:

"{"Protocol":"12345","Version":1,"Timestamp":"2020-05-01T21:55:12.123456Z","Assignment":{"Id":"54403dd5-5f1d-4ba0-8477-9b16807ee285","Asset":[]}}"

We want to retrieve only the Id string value. That is: 54403dd5-5f1d-4ba0-8477-9b16807ee285","Asset":[]}}"




How do I choose a random part of the list Python [duplicate]

I am making an Oregon Trail remake, and I have a list called people_alive that is supposed to only have the people that are alive. In order to be taken off that list, you need to get the players health from 25 to 0. One way to do that is if they get sick.

cholera = random.randint(1,100)
if cholera == 1:
    person = random.randrange(people_alive)
    if person == p1:
        p1hp -= 1
    if person == p2:
        p2hp -= 1
    if person == p3:
        p3hp -= 1
    if person == p4:
        p4hp -= 1
    if person == p5:
        p5hp -= 1
    print('{} has cholera'.format(person))
    input()

It gives me an error right here: person = random.randrange(people_alive) here is the error:

Traceback (most recent call last):
  File "main.py", line 149, in <module>
    person = random.randrange(people_alive)
  File "/usr/lib/python3.8/random.py", line 210, in randrange
    istart = _int(start)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

And here is the list:

people_alive = [p1, p2, p3, p4, p5]



lottery of a random number with 2 classes

I'm trying to create a lottery where a random number is generated (from 20-150) and the code says you won if the number generated is a number 40-50. However, I'm having problems calling my second class in my main method. I'm getting an error saying that "method draw in class Lottery cannot be applied to given types." How can I improve my code?

class Main {

Lottery.draw();

}


import java.util.*;

public class Lottery {
  public static void draw(String[] args) {
  int entry1 = (int)(Math.random()*150)+20;
  
  if(entry1>= 40 && entry1<=50){
    System.out.println("You won the lottery!");}
  System.out.println(entry1);
}
}




Guessing game with integer input validation and number of right guessed answers displayed Java

I'm building a dice guessing game. the program has 5 die tosses. I've implemented hasNextInt() as it is the only one I can understand at the moment.

  1. When I enter something that's not an Int it breaks out of the code but I want the program to continue for the rest of the goes (out of 5).
  2. Also If the user guesses correctly I have to keep track of how many they get right.
  3. If they guess wrong I have let them know what the die toss was, this keeps returning the first wrong die toss for the five goes.
  4. At the end I have let the player know how many they got right out of 5.

This is my code so far

import java.util.Scanner;

public class Attempt11
{
    public static void main(String args[]) {
        int attempt = 1;
        int userGuessNumber = 0;
        int secretNumber = (int) (Math.random() * 6) + 1;
        Scanner userInput = new Scanner(System.in);
        System.out.println("Guess the next dice throw (1-6)");

        do {
            if (userInput.hasNextInt()) {
                userGuessNumber = userInput.nextInt();

                if (userGuessNumber == secretNumber) {
                    System.out.println("Congratulations you guessed right");
                    continue;
                } else if (userGuessNumber < 1) {
                    System.out.println("Number must be between 1 and 6 inclusive, please try again ");
                } else if (userGuessNumber > 6) {
                    System.out.println("Number must be between 1 and 6 inclusive, please try again ");
                } else if (userGuessNumber > secretNumber) {
                    System.out.println("Hard luck the last throw was " + secretNumber);

                } else if (userGuessNumber < secretNumber) {
                    System.out.println("Hard luck the last throw was " + secretNumber);
                }
                if (attempt == 5) {
                    System.out.println("You have exceeded the maximum attempt. Try Again");
                    break;
                }
                attempt++;
            } else {
                System.out.println("Enter a Valid Integer Number");
                break;
            }
        } while (userGuessNumber != secretNumber);
        userInput.close();
    }
}



How to provide students with a mystery function in Python

I'm teaching a discrete math course in which I've incorporated a programming component. We have been using Python Notebooks through Jupyter.

We're coming up on a section in probability theory, and I would like to provide them with a "mystery random variable:" I want students to be able to sample the random variable without knowing how it is defined.

I don't know the best way to implement this, and was hoping someone could provide a suggestion. Here are the features that I want:

  • I define one or several random variables (preferably in Python),
  • The students should be able to sample from the random variable in a Python notebook (so they can do experimentation with it), but
  • the students should not be able to see the code that defines the random variable.



Pushing an array of pointers into a std::vector avoiding copying the objects with push_back

In this code, an array of pointers newData is created in a for loop then it is pushed into a vector testData. The pointers are stored in the vector std::vector<testData*>.

My concern is that I need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them, do I lose this reference by calling the line newData = new unsigned char[frameSize]; in a for loop?

I mainly want to avoid copying the objects with a push_back.

How can I create an array of unsigned char* of random char (here I just use 'a') and then push these arrays to a vector?

int numFrames = 25;
int frameSize = 100;

std::vector<unsigned char*> testData;

unsigned char *newData;

for (int i = 0; i < numFrames; i++) {
    newData = new unsigned char[frameSize];

    for (int j = 0; j < frameSize; j++) {
        newData[j] = 'a'; // fill the frame with random data, 'a' here
    }

    testData.push_back(newData);
    newData = 0; // ??
    memset(&newData, 0, frameSize); // ??
}

std::cout << " testData " << testData.size() << "\n";



How to keep asking the user for input until they choose to exit?

How do I keep asking the user to input a number until they choose to exit? When I enter in another number, it doesn't keep going.

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

int numSets;
int a = 1, b = 53;    
int c;

int main()
{
    int ranOne, ranTwo, ranThree, ranFour, ranFive, ranSix;

    srand(time(NULL));

    printf("Enter the amount of sets you want otherwise put -1 to exit:\n");
    scanf("%d", &numSets);

    for (c = 1; c <= numSets; c++) {
        ranOne = (rand() % (b - a + 1)) + a;
        ranTwo = (rand() % (b - a + 1)) + a;
        ranThree = (rand() % (b - a +1)) + a;
        ranFour = (rand() % (b - a + 1)) + a;
        ranFive = (rand() % (b - a + 1)) + a;
        ranSix = (rand() % (b - a + 1)) + a;

        printf("Set # %d of six numbers: %d %d %d %d %d %d\n", c, ranOne, ranTwo, ranThree, ranFour, ranFive, ranSix);
    }

    if(numSets == -1) {
        printf("You have exited the application");
    }

    return 0;
}



Select one random row by group (Oracle 10g)

This post is similar to this thread in that I have multiple observations per group. However, I want to randomly select only one of them. I am also working on Oracle 10g.

There are multiple rows per person_id in table df. I want to order each group of person_ids by dbms_random.value() and select the first observation from each group. To do so, I tried:

select
    person_id, purchase_date
from
    df
where
    row_number() over (partition by person_id order by dbms_random.value()) = 1

The query returns:

ORA-30483: window functions are not allowed here 30483. 00000 - "window functions are not allowed here" *Cause: Window functions are allowed only in the SELECT list of a query. And, window function cannot be an argument to another window or group function.




How to place a random integer into a variable among some given numbers? [duplicate]

I have to write only one statement that puts a random integer into a variable from the numbers 50,78, 91, 565,250. This is where the statement will go:

public static void main(String[] args) {
 Random random = new Random();
 int randomInt;
 //single statement goes here
 System.out.println("The number is: “ + randomInt);

}




Expected numbers of turns to generate k distinct elements [closed]

Alice got a random number generator, The random number generated is between 1 to n equiprobably. Now alice wants to know the expected number of turns to generate k distinct numbers. Return the answer modulo 10^9 + 7. I only have constraints for this. No sample input and output. 1<=k<=n <= 10^5

EDIT: My approach is to generate random numbers till I get k distinct elements and the answer will be the number of tries it had taken. I doubt whether this is correct or not.

How to approach these types of questions? Need algorithm for this.




C++ how to stop a random engine from producing negative numbers?

I have a function that im trying to produce random numbers between 18 and 5

int randomAge() {
  int random;
  std::random_device rd;
  static std::default_random_engine generator(rd()); //produce a static random engine
  std::normal_distribution<double> distribution(18, 52);  //random age between 18 and 52
  random = distribution(generator);
  return random;
}

However I am recieving negative numbers and even numbers that are higher than 52. How can I fix this so it produces numbers between 18 and 52?




dimanche 25 octobre 2020

How to select random rows in tsql with priorities for some rows

My question is an extension of the question asked here: How to request a random row in SQL?

What is the extension? Let's say is given a table of users, with this structure:

id (int) | name | email | phone number (char)

If I want to select few random users I have this query:

SELECT TOP @X column FROM table ORDER BY NEWID()

The extension I need is to give priority to users that have phone number (NOT NULL). The users should be randomly selected, but the one with phone number (if any) should come first, and the total number of returned rows should still be @X.

Thank you.




Is there an efficient way to generate multinomial random variables in parallel?

numpy.random has the following function to generate multinomial random samples.

multinomial(n, p, size)

But I wonder if there is an efficient way to generate multinomial samples for different parameters n and p. For example,

n = np.array([[10],
             [20]])
p = np.array([[0.1, 0.2, 0.7],
             [0.4, 0.4, 0.2]])

and even for higher dimension n and p like these:

n = np.array([[[10],
        [20]],
       [[10],
        [20]]])
p = np.array([[[0.1, 0.2, 0.7],
        [0.1, 0.2, 0.7]],
       [[0.3, 0.2, 0.5],
        [0.4, 0.1, 0.5]]])

I know for the univariate random variable, we can do this kind of things, but don't know how to do it for multinomial in python.




Wanting to display an array of images in a random order and on random points of screen on click and then be draggable

I'm Wanting to display an array of images in a random order and on random points of the screen once rendered on click and then be draggable around the viewport. I've attached my current code and am totally open to changing anything. Any help would be greatly appreciated.

Thanks so much!

     function show_image(src, width, height, alt) {
  var img = document.createElement("img");
  img.src = src;
  img.width = width;
  img.height = height;
  img.alt = alt;
  
  // set the position
  img.style.position = 'absolute';
  img.style.top = document.body.clientHeight * Math.random() + 'px';
  img.style.left = document.body.clientWidth * Math.random() + 'px';

  document.body.appendChild(img);
}
document.getElementById('foo').addEventListener('click', () =>
  show_image("<?php bloginfo('template_url'); ?>/img/I flexibly pay attention to.jpeg", 300, 300, 'foo')
);




Injecting random numbers in random places in an 1D numpy array

I have a 1D numpy array X with the shape (1000,). I want to inject in random (uniform) places 10 random (normal) values and thus obtain the numpy array of shape (1010,). How to do it efficiently in numpy?




Normal Random Distribution with Random State [closed]

I am trying to generate a random distribution with a random state where all the generated values are positive. The code I am using is:

ran_state = 8
n = 10
average = 3
std = 2
random_generator = np.random.default_rng(ran_state)
normal = random_generator.normal(loc = average, scale = std, size = n)

However some values I am obtaining are negativas:

array([-0.4765328 , 0.32671441, 0.27778658, 2.29676574, -1.62516316, 2.62220561, 1.08554154, 4.78720037, 4.91369448, 5.78451646])

How can I do to obtain only positive values?

Can anyone help me?

Regards




Issue with rand() function and matrices [closed]

I'm trying to build a programm where i have a 4x3 matrix filled with random numbers (using the rand() function) but when i try to visualize the matrix, it is empty. It seems that the path never enters the first (and second) for{}.

The code is

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
    srand(time(NULL));
    const int nr=4,nc=3;
    int mat[nr][nc];
    for(int i=0; i++; i<nr)
    {
        for(int j=0; j++; j<nc)
        {
            mat[i][j]=rand();
            cout<<mat[i][j]<<endl; // ! doesn't do anything..
        }
    }   

    cout<<"MATRIX:"<<endl;
    for(int i=0;i++;i<nr)
    {
        for(int j=0;j++;j<nc)
            cout<<mat[i][j];
        cout<<endl;
    }
    system("pause");
}



How do I randomly get a certain number of elements of a numpy array with at least one element from each class?

I have a dataset of 400 images, 10 images of 40 different people. There are 2 NumPy arrays, "olivetti_faces" contains the images (400x64x64), and "olivetti_faces_target" contains the classes of those images (400), one class for each person. So "olivetti_faces" is of the form: array([<img1>, <img2>, ..., <img400>]) where <img> is a 64x64 array of numbers, and "olivetti_faces_target" is of the form: array([0, 0, ..., 39]).

You can access the dataset here. You can load them after downloading as follows:

import numpy as np
data=np.load("olivetti_faces.npy")
target=np.load("olivetti_faces_target.npy")

I would like to randomly choose 100 of the images, with at least one image of each of the 40 people. How can I achieve this in NumPy?

So far I could randomly get 100 images using the following code:

n = 100 # number of images to retrieve
rand_indeces = np.random.choice(data.shape[0], n, replace=False)
data_random = data[rand_indeces]
target_random = target_random[rand_indeces]

But it does not guarantee that at least one image of each of the 40 classes is included in data_random.




I've tried unsuccessfully to use Math.random to play song files on click button without repeating

<a href="#" id="soundbutton">Press</a>
     <script>
      
      var lastNum; 
         
     function mySounds() {

var x = Math.floor((Math.random() * 5) + 1); if(x === lastNum){sound();}

var sound = new Audio();     
  

switch (x) { case 1: sound.src = "CLA.WAV"; break; case 2: sound.src = "TBN.WAV"; break; case 3: sound.src = "TRI.WAV"; break; case 4: sound.src = "DB.WAV"; break; case 5: sound.src = "REC.WAV"; break; } sound.play();

   lastNum = x;    

}

document.getElementById('soundbutton').addEventListener('click', mySounds);

     </script>
     



random list within a certain limit

i want to generate a random list, in which generates n numbers between a and b. However, when executing, nothing comes out.

def random_list(a,b,n):
    import random
    xs=[]
    x=random.randint(a,b)
    xs.append(x)
    while len(xs)==n:
        return xs



How to split up a dataset randomly to reflect new class proportions in R?

I am currently apply different classifiers (LDA and kNN) to the data set and exploring their different predictions. I want to see how these would differ if the class proportions of each species were not equal thirds. For example, if they changed to 0.1, 0.1 and 0.8 for setosa, virginica and versicolor. However, I am not sure how to approach this.

My first thought was to alter the Iris dataset to reflect these percentage changes before I perform any classification. However, I am having some difficulties trying to create this new dataset. In R, I tried using the dplyr package to try and split the species up randomly and then represent their new proportions but having no such luck. Any tips of how to do this ?!

I have tried this but had no such luck:

attach(iris)
new<-split(iris, Species)
setosa.new<-new$setosa
set.seed(123)
setosa.new[sample(nrow(setosa.new), 15), ]

However, ideally i would like the random sample to be the same each time. How can I ensure this?




Flutter: How can I update a variable to display some text, have a delay, then update another variable also displaying text?

I'm very new to Flutter and Stack Overflow, so I apologize in advance if my question comes off as silly. I'm currently trying to create an app that helps a user memorize French vocabulary. I want the user to be able to click a button to check their answer, see immediately whether their answer is right or wrong, and then a have a delay of a few seconds to view their corrected answer, before the question changes. Here's a snippet of my code:

Padding(
          padding: const EdgeInsets.fromLTRB(10.0, 100.0, 0.0, 0.0),
          child: RaisedButton(
            color: Colors.white,
            child: Text(
              'Check Answer.',
              style: TextStyle(
                fontFamily: 'Oswald',
                fontStyle: FontStyle.italic,
                fontSize: 18.0,
                fontWeight: FontWeight.bold,
              ),
            ),
            onPressed: (){
              answer = myController.text;
              isCorrect = (answer == answers.elementAt(element));
              isCorrect == true ? answerMessage = "Correct!" : answerMessage = "Sorry, that answer was incorrect.";
              Future.delayed(const Duration(milliseconds: 5000), () {
                setState(() {
                  element = question.nextInt(3);
                  word = questions.elementAt(element);
                });
              });
            },
          ),
        ),

For reference, I've created two arrays, one for questions and one for the answers and the variable 'element' is simply a random number that is plugged into both arrays to generate the question and the expected answer.

I get the user's answer using a controller in a TextField widget and then compare it to the appropriate element in the 'answers' array. Based on whether the above condition is true or false, I update the 'answerMessage' variable to display on the screen whether the answer is correct or not. After this, I have tried to put a delay of around 5 seconds before the 'element' variable is given a new random integer value (which corresponds to a new question being randomly picked from my 'questions' array) before the 'word' variable that is being displayed on screen is updated to reflect the new question. I can't find any issues with my code, yet for some reason, my program instead waits 5 seconds before even displaying whether the user is correct or not, and then immediately updates the question, which defeats the delay's purpose as the whole point of the delay is for the user to have some time to see if their answer is correct before moving on to the next question.

Whew! I'm sorry if this came across as long-winded but I wanted to make sure to not miss out on any details. Thanks in advance!




samedi 24 octobre 2020

random choice is always return 1 as answer(simple game) [closed]

ok, I'm new to python(or coding in general) and I was trying to make a simple guessing game, the program decides on a number from 1 to 5 and the player tries to guess it, but every time I answer 1 it says correct, even when it is another number when you print. another problem I've been having is that the loop only lasts a short time, is that supposed to happen?

        import random
            num_list = [1, 2, 3, 4, 5,]
            num = random.choice(num_list)
            ur_num = input("pick a number, 1 to 5")

            for num in num_list:
                if int(ur_num) != num:
                    print("try again")
                    ur_num = input("pick a number, 1 to 5")
                else:
                    print("GOOD JOB")
                    again = input("wanna play again?(y/n)")
                    if again == "y":
                        num = random.choice(num_list)
                        print("OKIE DOKIE")
                    else:
                        print("Have a nice day!")
                        break



generating random number with lower bound excluded

I would like to generate a random number between x and y with the conditions (x, y] so x is excluded but y is included.

I am using Java.

I know that for the upper bound to be excluded it is Math.random * y but what do you do for lower bound? I am not sure how you would do it this way because the Math.random function returns the opposite [0, 1) so I am not sure how you would inverse that.

I also took a link at this source for answers but I didn't get any luck. https://careerkarma.com/blog/java-math-random/#:~:text=The%20Math.,is%20always%20less%20than%201.

Please let me know




Value randomly change while soup.find with Beautifulsoup [closed]

I try to scrape some informations on the french car advert website "LaCentral" using Beautifulsoup. Informations like price, mileage, colour... about sportcars interest me for data analysis.

I'm quite comfortable with Beautifulsoup, I successfully done that on other website but this one have something particular : when I try to get the price or the mileage of a car, the value in the html script is :

<span class="cbm__priceWrapper" 185 000&nbsp;€ </span>

So I use this python command :

price = soup.find('span',class_='cbm__priceWrapper').get_text()

But it gave me 212 740 € rather than 185 000 €. Same thing with the mileage and for every car advert and it is the only way in the html script to acess to the price or mileage.

I wonder if the website could add a random coefficient to price and mileage to prevent from scraping. Every other informations like colours, numbers of options, date... are correct except price and mileage (two most important of course...)

I didn't found any linear coefficient between the real price and the one get by soup.find, it looks really random...

Have you ever face to that issue while scraping ?




How do I make a random quote generator not repeat quotes

I've searched the site for answers but the one's that come up aren't similar/specific to the code that I have written. I don't know how to modify the code so that the quotes don't repeat when the user presses a button to generate another quote.

var quotes = [
{
    quote: "\"Don't just exist, live\""
},
{
    quote: "\"Try to be a rainbow in someone's cloud\""
},
{
    quote: "\"Prove them wrong\""
},
{
    quote: "\"Find reasons to smile\""
},
{
    quote: "\"You get what you give\""
}
]

var quotebtn = document.getElementById('quote-btn');
var quote = document.querySelector('.quote');

quotebtn.addEventListener('click', () => {
let random = Math.floor(Math.random() * quotes.length);

quote.innerHTML = quotes[random].quote;
})