vendredi 30 avril 2021

Random number with limited deviation from previous value [closed]

I'm trying to generate a random number within range 1 to 20. So let's say I get 10. I would like the next random number to be close to the last random number so say 10.6 or 9.1. How would I give this this new random number a range that is close to the last one?

Current code:

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

int main()
{
    int min = 1, max = 20;

    srand(time(0));
    printf("The random number is: ");
    int num = (rand() % (min - max));
    printf("%d ", num);
    return 0;
}



How can I automatically generate numbers and store them in a database?

I am trying to create a system that auto-generate 10 numbers between 1-60 using php/MySQL database.

<?php
    $n=range(1,60);
    shuffle($n);
        for ($x=1; $x< 11; $x++)     {
             echo $n[$x].' ';
             }
        echo "\n"
?>

The system auto-refresh every 5 mins but the problem is how do I store previous generated numbers in a database with a unique query number automatically when numbers are generated?

It has a 300 sec auto-reload on the meta-tag

<meta http-equiv="refresh" content="10">

Thank you.




Generating random points from intersection of multiple spaces in _R_8

I am trying to write a Python code to sample 50 random points from the intersection of five subspaces in R8. The spaces are three hypercylinders (x12+x22=4; x32+x42=4; x52+x62=4) and two linear spaces (x1+x3+x5+x7=4; x2+x4+x6+x8=0).

For all I know is that the intersection can be an infinite set and finding roots of functions as mentioned in Python: Intersection of Spheres may not be feasible.

Also, I tried implementing from Sample random points over intersection if surfaces but couldn't get much.

I have recently started to use Python and request you to pardon me for my rookie mistakes.




I want to randomly shuffle a List containg 10 cards(will increase later to 52) using c#. But i am having problems.Only half of them are beingshuffled

static List<List<int>> CardDistribution(List<int> Deck,List<int> PlayerCard, List<int> OpponentCard)
{
    int TotsalCards = Deck.Count;
    int CardTaken;
    int IndexofCardTaken;
    int value;

    Random CardTaker = new Random();

    for (int PlC = 0; PlC < TotsalCards; PlC++)
    {
        TotsalCards--;
        if (TotsalCards > 1)
        {
            if (PlC % 2 == 0)
            {
            Redo:
                IndexofCardTaken = CardTaker.Next(0, TotsalCards + 1);
                CardTaken = Deck[IndexofCardTaken];
                if (PlayerCard.Contains(CardTaken))
                {
                    goto Redo;
                }
                else
                {
                    PlayerCard.Add(CardTaken);
                    value = Deck[IndexofCardTaken];
                    Deck[IndexofCardTaken] = Deck[TotsalCards];
                    Deck[TotsalCards] = value;
                }
            }
            else if (PlC % 2 != 0)
            {
            Redo:
                IndexofCardTaken = CardTaker.Next(0, TotsalCards + 1);
                CardTaken = Deck[IndexofCardTaken];
                if (OpponentCard.Contains(CardTaken))
                {
                    goto Redo;
                }
                else
                {
                    OpponentCard.Add(CardTaken);
                    value = Deck[IndexofCardTaken];
                    Deck[IndexofCardTaken] = Deck[TotsalCards];
                    Deck[TotsalCards] = value;
                }
            }
        }
        else if(TotsalCards == 1)
        {
            OpponentCard.Add(Deck[0]);
        }
    }
    List<List<int>> ReturnDecks = new List<List<int>>();
    ReturnDecks.Add(PlayerCard);
    ReturnDecks.Add(OpponentCard);
    return ReturnDecks;
}

I am using two other functions to populate the original Deck list and check what cards do all the lists receive.

I Have seen that only half of the values are being shuffled.
Please help as I have seen all the other similar questions on here but they are not helpful in this situation.




Finding possible arrangements of books on a shelf with Monte-Carlo in Matlab

I am trying to learn about Monte-Carlo simulations and data structures in Matlab, and as an example to play with I am trying to estimate numerically in Matlab how many possible ways books can be arranged on a shelf.

I have x3 categories "physics", "sci-fi", and "travel". Each contains N_phys, N_scifi, and N_travel numbers of books respectively. Within their category, the books can be placed in any order, but they must stay within their respective category (i.e all the physics books together). The categories can then be arranged in any order (i.e I could have all the sci-fi books first, followed by travel, followed by physics, for example).

This problem can be solved easily by a permutation, and the result is N_phys ! x N_scifi ! x N_travel ! x 3 !. For N_phys = 4, N_scifi = 3, and N_travel = 2, the result is 1728 possible arrangements.

I have decided to label both each book and its category by integers, with "physics" = 1, "sci-fi" = 2, and "travel" = 3. The shelf is then a 2D array. So for example, a whole shelf could look like the following:

3   2   1   4   1   2   2   1   3
1   1   1   1   3   3   2   2   2

where the the first 4 books are physics (because the second row is 1), followed by 2 travel books, and finally 3 sci-fi books, like this:

enter image description here

I have written a "brute-force" approach, shown below, which seems to give the correct result:

N_phys = 4;   % Number of physics books
N_scifi = 3;  % Number of sci-fi books
N_travel = 2; % Number of travel books

books_physics = [1:N_phys;...
                 ones(1,N_phys)]; % Collection of physics books

books_scifi = [1:N_scifi;...
               2*ones(1,N_scifi)]; % Collection of sci-fi books

books_travel = [1:N_travel;...
                3*ones(1,N_travel)];  % Collection of travel books

num_samples = 10000; % Number of random shelves to generate
unique_shelves = zeros(num_samples*2,N_phys+N_scifi+N_travel); % Preallocate 

unique_shelves(1:2,:) = [books_physics books_scifi books_travel];
num_unique_shelves = 1;

% Generate "num_samples" permutations of shelves randomly
for sample_num = 1:num_samples
    
books_physics_shuffled = books_physics( :, randperm(N_phys) ); % Shuffle physics books
books_scifi_shuffled = books_scifi( :, randperm(N_scifi) );    % Shuffle sci-fi books
books_travel_shuffled = books_travel( :, randperm(N_travel) ); % Shuffle travel books

category_order = randperm(3,3); % Choose order of categories, e.g. sci-fi/phsycis/travel  = [2 1 3]

shelf = [];

% Arrange the categories in a random order
for k = 1:3
    if category_order(k) == 1
        shelf = [shelf books_physics_shuffled];
    elseif category_order(k) == 2
        shelf = [shelf books_scifi_shuffled];
    elseif category_order(k) == 3
        shelf = [shelf books_travel_shuffled];
    end
end

% Iterate over discovered shelves, and see if we have found a new unique one
shelf_exists = 0;
for k = 1:num_unique_shelves
    if shelf == unique_shelves( (2*k-1):(2*k),:)
        shelf_exists = 1; % Shelf was previously discovered
        break
    end
end

if ~shelf_exists % New shelf was found
    unique_shelves( (2*num_unique_shelves+1):(2*num_unique_shelves+2),:) = shelf; % Add shelf to existing ones
    num_unique_shelves = num_unique_shelves + 1;
end

end

disp(['Number of unique shelves found = ',num2str(num_unique_shelves)])
disp(['Expected = ', num2str(factorial(N_phys)*factorial(N_scifi)*factorial(N_travel)*factorial(3) )])

As can be seen, I am basically randomly generating a shelf, and then checking if it has been previously found. If it has, I add it to the list.

My question is how can I learn and improve this approach, making it more concise? Is there a better data structure for storing such "unique_shelves", instead of the 2D array of integers, as well as finding the matches?

This is also quite slow to run, and also doesn't scale for more categories, since they are hardcoded.

Tips or alternative examples would be great! Thanks.




jeudi 29 avril 2021

Is there a way to have randomized string values in an array only be called once while using a for loop?

I want to make a program where you enter input in a for loop and after the iterations, a randomized string value from an array gets placed with it in the output message at the end. I do not want the string values to repeat, I want each value to only be produced once. How can I go about doing that? (the int values and the string values in the two arrays have to stay matched as well)

I want the output to be like:

Alex likes mangos and the number 3

John likes apples and the number 1

Jane likes bananas and the number 2

instead of:

Alex likes mangos and the number 3

John likes mangos and the number 3

Jane likes apples and the number 1

package example;
import javax.swing.JOptionPane;
import java.util.Random;
public class Example {

    public static void main(String[] args) {
        
        StringBuilder generator = new StringBuilder();
        
        for (int a=1; a<4; a++){
            
            String name = JOptionPane.showInputDialog(null, "Enter person " + a + "'s name");
            
            Random random = new Random();
            String [] fruit = {"apples", "bananas", "mangos"};
            int [] number = {1, 2, 3};
            int randomIndex = random.nextInt(fruit.length);
            
            generator.append(name).append(" likes ").append(fruit[randomIndex]).append(" and the number ").append(number[randomIndex]).append("\n");     
        }
        JOptionPane.showMessageDialog(null, generator);
    }
    
}



Random shuffle function works in main(), but not a class

I'm attempting to use a seeded random_shuffle to simply shuffle a vector, before I use it. I tested this out by doing

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <bits/stdc++.h>


using namespace std;

int seed;
int rng(int i)
{
    srand(seed);
    return rand()%i;
}
int main()
{
    vector<int> myVec;
    cin >> seed;

for (int i = 0; i < 10; ++i)
    myVec.push_back(i);

for (auto it = myVec.begin(); it != myVec.end(); ++it)
    cout << *it;
cout << endl;
random_shuffle(myVec.begin(), myVec.end(), rng);

for (auto it = myVec.begin(); it != myVec.end(); ++it)
    cout << *it;
}

and it worked just fine. This lets me enter an int for the seed, and then prints out the before and after. However, when I tried to insert it into a class and run a build task with VSCode, it exploded.

class Test
{
public:
    Test(int seed)
    {
        random = seed;
        for (int i = 0; i < 10; ++i)
        myVec2.push_back(i);

       random_shuffle(myVec2.begin(), myVec2.end(), r);

    }
private:
    vector<int> myVec2;
    int random;

    int r(int i)
    {
        srand(random);
        return rand()%i;
    }
};

Here's the errors that came up:

25:54 required from here
error: must use '.*' or '->*' to call pointer-to-member function in '__rand (...)', e.g. '(... ->* __rand) (...)'
 4619 |    _RandomAccessIterator __j = __first + __rand((__i - __first) + 1);

Why is random_shuffle functioning correctly in main(), but not a class?




I cant make a random number turn in a string [closed]

Random random = new Random();
int monster = random.nextInt(3);
    
}if (String.valueOf(monster).equals(3)) 
 System.out.println("Um dragão enorme aparceu!");

}if (String.valueOf(monster).equals(2));
System.out.println("Um lobo selvagem apareceu!"); 
    
}if (String.valueOf(monster).equals(1));
System.out.println("UM velho aparceu!"); 
    }
}

Multiple markers at this line - Syntax error on token "}", { expected - Unlikely argument type for equals(): int seems to be unrelated to String

Multiple markers at this line - monster cannot be resolved to a variable - Unlikely argument type for equals(): int seems to be unrelated




Why does my random function always returns same number? [duplicate]

I have an ID system with PHP. It generates a 12 digit ID this way:

// create a 12 digit ID
function createTwelveId(){
  $digit_1 = rand(0, 9);

  $digit_2 = rand(0, 9);

  $digit_3 = rand(0, 9);

  $digit_4 = rand(0, 9);

  $digit_5 = rand(0, 9);

  $digit_6 = rand(0, 9);

  $digit_7 = rand(0, 9);

  $digit_8 = rand(0, 9);

  $digit_9 = rand(0, 9);

  $digit_10 = rand(0, 9);

  $digit_11 = rand(0, 9);

  $digit_12 = rand(0, 9);

  $pre_twelve_id = $digit_1 . $digit_2 . $digit_3 . $digit_4 . $digit_5 . $digit_6 . $digit_7 . $digit_8 . $digit_9 . $digit_10 . $digit_11 . $digit_12;

  return $pre_twelve_id;
}

When called, it is like this:

$comment_ID = createTwelveId();

And then it is inserted into my database this way:

//create comment
  $sentence = $connection->prepare("
    INSERT INTO comments (ID)
    VALUES (:ID)
");
$sentence->execute(array(
  ':ID' => $comment_ID
));

But every time I check the result on the database, it always inserts this:

004294967295

Please notice on this column I have Zerofill and Unsigned values on, that's why the int has 2 zeros at the beginning. And when I remove the Zerofill and Unsigned values, it inserts this:

2147483647

It always does this. Isn't it supposed to insert a random int into the database instead of those 2 numbers?

How can I stop this from happening and instead of those 2, insert the real random characters?




Weighted random sample from a list of lists in python

I would like to select multiple elements (lists) from a list but considering a weighted probability for each element, so far I've tried with np.random.choice but it sends an error that says that the list must be 1-dimensional.

import numpy as np

population = [[0, 7, 3, 3, 5, 0, 6], [0, 8, 4, 3, 5, 2, 5], [2, 1, 6, 6, 6, 2, 2], 
              [3, 6, 1, 7, 4, 3, 6], [3, 8, 1, 3, 6, 0, 5], [4, 7, 2, 0, 3, 5, 8], 
              [4, 8, 5, 5, 6, 2, 0], [1,0,0,1,0,1,1], [5, 1, 3, 4, 4, 4, 0], 
              [6, 7, 5, 5, 2, 3, 5], [7, 5, 3, 8, 3, 4, 2], [8, 1, 3, 5, 1, 5, 6], 
              [8, 1, 5, 7, 7, 5, 8], [8, 2, 4, 8, 7, 0, 8], [1,0,0,0,1,1,1], 
              [8, 4, 8, 2, 3, 5, 6], [8, 6, 3, 2, 4, 2, 2], [8, 7, 2, 8, 5, 2, 2]]

probability = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5833333333333334, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4166666666666667, 0.0, 0.0, 0.0]

selection = np.random.choice(population,size=2,replace=False, p=probability)

print(selection)

>> ValueError: a must be 1-dimensional



Seedable CSPRNG for python?

With the random module, you are able to seed it to get the same values every time.

import random

random.seed(1)
print(random.randint(1,100)) # outputs 18 every time

Is there a CSPRNG that can do this? For example, according to this question How can I create a random number that is cryptographically secure in python?, random.SystemRandom is secure. But seeding it doesn't return the same thing.

from random import SystemRandom

s = SystemRandom()
s.seed(1)
print(s.randint(1,100)) # 81, 16, 100, 58

Does such a CSPRNG exist? or does this negate the security aspect?




MySQL Generate random timestamps from range, order it by date asc, then use it to update missing values from another table

I have a table "ips", where I store my download logs. Accidentally, I forgot to add timestamp for it (yea, stupid mistake)... Now, I have fixed it, but there are already 65.5k entries without timestamp.. Is there a way, how to add random timestamp from date range to fill NULL timestamps?

I was able to generate timestamps list using this queries:

SET @MIN = '2020-04-05 18:30:00';
SET @MAX = NOW();
SELECT TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN) as dldate FROM ips WHERE name="filename1" ORDER BY dldate ASC;

It generated the exact count of entries I need for specific filename, but I have absolutely no idea, how to use this list to update already existing entries in my "ips" table and KEEP IT ORDERED by "dldate"...

When I was testing it, I was close, when I used this query (I was afraid to use UPDATE to not mess my data up, so I used just SELECT):

SELECT ips.id, ips.name, t1.dldate FROM (SELECT id, name FROM ips WHERE name="filename1") ips INNER JOIN (SELECT ips.id as id, TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN) as dldate FROM ips WHERE name="filename1" ORDER BY dldate ASC) t1 ON (ips.id=t1.id) ORDER BY ips.id ASC;

That worked, but timestaps are purely random (obviously :D), and I need them to "respect" id from "ips" table (starting with lower timestamp for lowest id, and then continuously higher timestamps for higher ids).

I'm getting this:

+------+-----------+---------------------+
| id   | name      | dldate              |
+------+-----------+---------------------+
|   15 | filename1 | 2020-12-18 21:35:03 |
| 1118 | filename1 | 2020-12-18 13:34:47 |
| 1141 | filename1 | 2020-08-07 12:49:46 |
| 1142 | filename1 | 2020-11-29 00:43:31 |
| 1143 | filename1 | 2020-05-13 03:00:16 |
| 1286 | filename1 | 2020-12-14 09:58:50 |
| 1393 | filename1 | 2021-04-14 06:45:23 |
| 1394 | filename1 | 2021-03-03 17:42:25 |
| 1395 | filename1 | 2020-09-03 05:56:56 |
| .... |
|62801 | filename1 | 2021-01-05 21:21:29 |
+------+-----------+---------------------+

And I would like to get this:

+------+-----------+---------------------+
| id   | name      | dldate              |
+------+-----------+---------------------+
|   15 | filename1 | 2020-04-05 21:35:03 |
| 1118 | filename1 | 2020-04-18 13:34:47 |
| 1141 | filename1 | 2020-05-07 12:49:46 |
| 1142 | filename1 | 2020-06-29 00:43:31 |
| 1143 | filename1 | 2020-08-13 03:00:16 |
| 1286 | filename1 | 2020-10-14 09:58:50 |
| 1393 | filename1 | 2020-12-14 06:45:23 |
| 1394 | filename1 | 2021-01-03 17:42:25 |
| 1395 | filename1 | 2021-03-03 05:56:56 |
| .... |
|62801 | filename1 | 2021-04-29 14:21:29 |
+------+-----------+---------------------+

Is there any way, how to achieve this output and how to use it with UPDATE statement instead of SELECT with INNER JOIN?

Thank you for help!




How to generate random Decimal128, Decimal256 numbers with Python

I am making a test for ClickHouse database for verifying Decimal data types. According to documentation:

Decimal Parameters:

P - precision. Valid range: [1 : 76]. Determines how many decimal digits number can have (including fraction). S - scale. Valid range: [0 : P]. Determines how many decimal digits fraction can have. Depending on P parameter value Decimal(P, S) is a synonym for:

  • P from [1 : 9] - for Decimal32(S)
  • P from [10 : 18] - for Decimal64(S)
  • P from [19 : 38] - for Decimal128(S)
  • P from [39 : 76] - for Decimal256(S)

I am trying to generate random numbers for all of these data types. I've found a good answer already and this is how I used it:

Decimal32:

>>> decimal.Decimal(random.randint(-2147483648, 2147483647))/1000
Decimal('-47484.47')

Decimal64:

>>> decimal.Decimal(random.randint(-9223372036854775808, 9223372036854775807))/100000000000
Decimal('-62028733.96730274309')

These two give me the expected result. But, my function for Decimal128 already is too long and produces wrong result:

>>> decimal.Decimal(random.randint(-170141183460469231731687303715884105728, 170141183460469231731687303715884105727))/1000000000000000000000
Decimal('149971182339396169.8957534906')

Question:

How can I generate random Decimal128 and Decimal256?

Please suggest what I should use.




mercredi 28 avril 2021

Setting cookie to random integer: TypeError: Excpected bytes

As the title suggests, I am attempting to set a cookie with a random integer generated with "random.randint(1,5)" and got a TypeError: Expected bytes. I found a method online that almost fixed the problem by changing "resp.set_cookie('ranNum', randomNumber, 3600)" to "resp.set_cookie('ranNum', json.dumps(randomNumber), 3600)". With this method, the cookie would be saved as a random number, but would be altered each time the page was refreshed. Here's how it would change with 2 being the example number and "->" being a page refresh:

2 -> "2" -> ""2"" -> ""\"2\""" -> ""\"\\\"2\\\"\"""

Why are quotation marks and backslashes being added to the integer with each refresh?

    if ("firstName" in request.args) or (request.cookies.get('userFName') is not None):
        
        if request.args.get('firstName') is not None:
            firstName = request.args["firstName"]
        elif request.cookies.get('userFName') is not None:
            firstName = request.cookies.get('userFName')
        if request.args.get('lastName') is not None:
            lastName = request.args["lastName"]
        elif request.cookies.get('userLName') is not None:
            lastName = request.cookies.get('userLName')
        
        if request.cookies.get('ranNum') is None:
            randomNumber = random.randint(1, 5)
        elif request.cookies.get('ranNum') is not None:
            randomNumber = request.cookies.get('ranNum')
        
        resp = make_response(render_template('assignment10_2.html', firstName=firstName, lastName=lastName, randomNumber=randomNumber))
        
        resp.set_cookie('userFName', firstName, 3600)
        resp.set_cookie('userLName', lastName, 3600)
        resp.set_cookie('ranNum', randomNumber, 3600)
        
        return resp



Finding random k points at least d apart in 3D confined space

For my simulation purposes, I want to generate a randomly distributed k number of spheres (having the same radii) in a confined 3D space (inside a rectangle) where k is in order of 1000. Those spheres should not impinge on one another.

So, I want to generate random k points in a 3D space at least d distance away from one another; considering the number of points and the frequency at which I need those points for simulation, I don't want to apply brute force; I'm looking for some efficient algorithms achieving this.




Join 2 randomly genreted list

I am trying to join 2 randomly generated list into one but its adding them element wise. Suppose I generated 2 list each with 2 random numbers I want my output list to be of numbers. For example:

import numpy as np

x1 = np.random.uniform(0,0.1, 2)
x2 = np.random.uniform(0,0.1, 2)

x = x1 + x2

print(x1)
print(x2)
print(x)
The output is: 
[0.06878713 0.03807816]
[0.01801809 0.06292975]
[0.08680523 0.10100791]

But I want my output as 
[0.06878713 0.03807816]
[0.01801809 0.06292975]
[0.06878713 0.03807816 0.01801809 0.06292975]

If I use append() or extend() its giving me: AttributeError: 'numpy.ndarray' object has no attribute 'append'.




Generate python object using typing

How I can generate random python object using typing module? For example:

from typing import List
t: List[Set[str]]
data = generate_data(t)
print(data)  # [{"123", "asbDw"}, {"fdasa"}, *some other sets with random strings*]

It would be nice if I could specify the amount of data or its range.

P.S. I know how I can write my own implementation for different data types, but it will take a relatively long time. I would like to know if there are ready-made solutions or ideas for implementation.

Thanks in advance!




Math.random() in Javascipt giving quite non-random looking distribution

I'm running a study which redirects participants to one of 8 random websites using the below piece of javascript (on an otherwise blank HTML page).

What's odd is the distribution of participants to each site. I have about 64 participants so far and I know that true randomness does not mean there should be 8 visitors to each site. However, one of the sites only has had a single redirect (site number 5) while another one has had 19 (site number 1). The others are all close to 8 visits each.

I just wanted to check that I haven't made any silly mistakes/assumptions with such a simple code. I can't think of any reason why it would be much more likely to generate a "1" and much less likely to generate a "5".

Is it just the case that this is the luck of the draw with random number generation and that one can end up with some sites being visited 19 more times that others while sample size is low and there are 8 possibilities?

Any opinions would be really appreciated.

<script type="text/javascript">

function randomlinks(){
        var myrandom=Math.floor(Math.random()*8)
        var links=new Array()
        links[0]="[website0 name here]"
        links[1]="[website1]"
        links[2]="[website2]"
        links[3]="[website3]"
        links[4]="[website4]"
        links[5]="[website5]"
        links[6]="[website6]"
        links[7]="[website7]"
     
        window.location=links[myrandom]
        }
    
    randomlinks();
</script>



Generating uniform random numbers between two large integers in fortran90/95 or python

I want to generate some uniform random numbers between [2E16, 5E20] in fortran90/95 or python. I know that if "R" is a random number between zero and one (0<R<1), we can transform R to [A, B] as:

R = (B-A)*R + A.

But when I use this algorithm to generate some random numbers between [2E16, 5E20], most of generated random numbers are very close to 5E20. I know why this is occurred, it is because of that, the term B-A is approximately equal to B (because B is so bigger than A), and most of the generated random numbers are placed within the magnitude of B or B/10 (I mean it was very close to B).

How can I solve this problem?

One solution that I tried to apply is that, I split the [2E16, 5E20] interval into smaller intervals, such as:

[2E16, 2E17], [2E17, 2E18], [2E18, 2E19], [2E19, 2E20], [2E20, 5E20].

And I generated some random numbers between each of the above intervals.

Is there any other solutions? Is my solution correct?

Thanks in advance!




How can I generate random numbers which fall in a normal distribution pattern?

I will need to initialize an 'n' number of classes that will have a random value attached to them from 1 to 100.

I know how to create a random value between 1 and 100 but how can I make all the values to fall in a the normal distribution pattern?

+ (int)randomIntBetweenMinimum:(int)minimum maximum:(int)maximum {
    
    return (int)(minimum + arc4random_uniform(maximum - minimum + 1.0f));
}



Generating very large (million+) highly correlated random datasets

Currently I have a point-cloud containing 1million+ correlated points.

My aim is to generate a "virtual" point-cloud, a random point-cloud created by generating 1million+ random samples from a gaussian distribution that follows the same correlation as my point-cloud. I am only focusing on one dimension for now, so i am not perturbing the x and y axes. I am able to calculate the covariance matrix for these points (incrementally) from work done previously. The problem is that the covariance matrix is huge (many terabytes) so I can't calculate the whole thing, nor can I store it. The covariance is not sparse, but changes smoothly across the entire point-cloud.

I am aware of the technique to generate correlated random numbers using cholesky decomposition. Even if I could store the covariance matrix calculating the cholesky decomposition of a (1million+ x 1million+) matrix is not feasible.

For background: This is for conducting a Monte-Carlo simulation on a point-cloud.

My question: Is this approach remotely feasible? Perhaps there is more a efficient way of representing the covariance matrix? Perhaps using a neural network (I have TensorFlow experience) I could simulate the generation of a specifically correlated random numbers using a smaller random seed? Has this been done before? I am struggling to find solutions of similar problems online.

This is being coded in Python. Thanks for any help.




What is the formula for choosing random number from a Excel Sheet Column?

Suppose a column has 100 entries but I want to choose only a certain percentage of a random number in that entry.

What is the formula for choosing a random number from an Excel Sheet Column? But, I choose only a certain percentage of number from that list?




mardi 27 avril 2021

How to randomly segment lines from one text file into two different text files?

I have a text file with say, 100 lines, I want to randomly segment these lines into 80-20 lines into two separate text files, Using the code below but it's not doing proper partition. I am getting a different number of files. I should get 80 lines in file2 and 20 files in file1. can someone point out the error and plz suggest if there is a better way. please note in total.txt is the original file which needs to be segmented into file1 and file 2. '''

def partition(l, pred):
    fid_train=open('meta/file1.txt','w')
    fid_test = open('meta/file2.txt','w')
    for e in l:
        if pred(e):
            fid_test.write(e)
        else:
            #fid_train.write(e+'\n')
            fid_train.write(e)
    return fid_train,fid_test
lines = open("meta/total_list.txt").readlines()
lines1, lines2 = partition(lines, lambda x: random.random() < 0.2)    

'''




How to get the unselected population in python random module?

So, I know I can get a random list from a population using the random module,

l = [0, 1, 2, 3, 4, 8 ,9]

print(random.sample(l, 3))
# [1, 3, 2]

But, how do I get the list of the unselected ones? Do, I need to remove them manually from the list? Or, is there a method to get them too?

Edit: The list l from example doesn't contain the same items multiple times, but when it does I wouldn't want it removed more than it's selected as sample.




Array population with random integers in C [duplicate]

I'm attempting to populate an array of 256 elements with randomly generated integers between 0 and 1024 in C as my language of choice for a DSA class. After doing some research, I found that this could be a viable solution:

int A[256];
  
for (int i = 0; i < 256 ; i++)
{
    A[i] = (rand() % 1024 + 0);
}

However, I then noticed that the rand function populates in a pseudo-random manner. In this case, what is the difference between 'random' and 'pseudorandom'? If there is a significant difference, is there a way to implement this in a way that could be done in a random manner in C?

TIA




React js material ui generate n random colors

I am writing a method which should generate n random colors without repetition, passing the following properties.

random({
      number: 150,
      colors: ["blue", "lightBlue", "cyan"],
      shades: ["200", "500"]
      //excludeColors: ["blue", "lightBlue", "cyan"],
      //excludeShades: ["200", "500", "700", "A700"]
});

The colors are the ones used using @material-ui/core/colors, but I would like to improve the function to make it more performant.

Can you give me a hand?

Link: codesandbox

import "./styles.css";
import React, { useState, useEffect } from "react";
import {
  red,
  pink,
  purple,
  deepPurple,
  indigo,
  blue,
  lightBlue,
  cyan,
  teal,
  green,
  lightGreen,
  lime,
  yellow,
  amber,
  orange,
  deepOrange,
  brown,
  grey,
  blueGrey
} from "@material-ui/core/colors";

export default function App() {
  const [state, setState] = useState({
    colors: []
  });

  const { colors } = state;

  const random = ({
    number,
    colors = [],
    shades = [],
    excludeColors = [],
    excludeShades = []
  }) => {
    const hueArray = [
      red,
      pink,
      purple,
      deepPurple,
      indigo,
      blue,
      lightBlue,
      cyan,
      teal,
      green,
      lightGreen,
      lime,
      yellow,
      amber,
      orange,
      deepOrange,
      brown,
      grey,
      blueGrey
    ];
    const hueNameArray = [
      "red",
      "pink",
      "purple",
      "deepPurple",
      "indigo",
      "blue",
      "lightBlue",
      "cyan",
      "teal",
      "green",
      "lightGreen",
      "lime",
      "yellow",
      "amber",
      "orange",
      "deepOrange",
      "brown",
      "grey",
      "blueGrey"
    ];
    const shadeArray = [
      "50",
      "100",
      "200",
      "300",
      "400",
      "500",
      "600",
      "700",
      "800",
      "900",
      "A100",
      "A200",
      "A400",
      "A700"
    ];

    const random = (items) => Math.floor(Math.random() * items.length);

    return [...Array(number).keys()].reduce((acc, el) => {
      let check = true;
      while (check) {
        let checkHue = true,
          checkShade = true;
        let hueR, shadeR;

        while (checkHue) {
          hueR = random(hueArray);
          if (
            (colors.length === 0 && excludeColors.length === 0) ||
            (colors.length !== 0 && colors.includes(hueNameArray[hueR])) ||
            (excludeColors.length !== 0 &&
              !excludeColors.includes(hueNameArray[hueR]))
          )
            checkHue = false;
        }

        while (checkShade) {
          shadeR = shadeArray[random(shadeArray)];
          if (
            (shades.length === 0 && excludeShades.length === 0) ||
            (shades.length !== 0 && shades.includes(shadeR)) ||
            (excludeShades.length !== 0 && !excludeShades.includes(shadeR))
          )
            checkShade = false;
        }

        const color = hueArray[hueR][shadeR];

        console.log(
          hueNameArray[hueR],
          shadeR,
          color,
          acc,
          !acc.includes(color)
        );

        if (!acc.includes(color)) {
          acc[el] = color;
          check = false;
        }
      }
      return acc;
    }, []);
  };

  useEffect(() => {
    let u = (a) => [...new Set(a)];
    let a, b;

    /*a = random({
      number: 257
    }); //<-- [258,...,266] problem codesanbox
    b = u(a);
    console.log("a", a, a.length);
    console.log("b", b, b.length);
    //19(hue)*14(shade)=266 possible colors

    a = random({
      number: 28, <- certainly can not be a higher value to 28
      colors: ["red", "blue"]
    });
    b = u(a);
    console.log("a", a, a.length);
    console.log("b", b, b.length);
    //2(hue)*14(shade)=28 possible colors

    a = random({
      number: 38, <- certainly can not be a higher value to 38
      shades: ["200", "500"]
    });
    b = u(a);
    console.log("a", a, a.length);
    console.log("b", b, b.length);
    //19(hue)*2(shade)=38 possible colors

    a = random({
      number: 4, <- certainly can not be a higher value to 4
      colors: ["red", "blue"],
      shades: ["200", "500"]
    });
    b = u(a);
    console.log("a", a, a.length);
    console.log("b", b, b.length);
    */
    //2(hue)*2(shade)=4 possible colors

    a = random({
      number: 150,
      excludeColors: ["blue", "lightBlue", "cyan"],
      excludeShades: ["200", "500", "700", "A700"]
    });
    b = u(a);
    console.log("a", a, a.length);
    console.log("b", b, b.length);
    //16(hue)*10(shade)=160 possible colors

    setState((prev) => ({
      ...prev,
      colors: a
    }));
  }, []);

  return (
    <div className="App">
      {colors.map((backgroundColor, key) => (
        <div key={key} style=>
          {key + 1}) {backgroundColor}
        </div>
      ))}
    </div>
  );
}



LOGIC ERROR: Converting Python to JavaScript. Code runs, but gives wrong answer

I started learning JavaScript 4 days ago and I am trying to convert my python project to JavaScript for practice.

Here is my working python code:

def shuffle(l):
    for shuffles in range(numPerformed):
        heads = 0
        #tails = 0 
        toss = []
        for card in range(numCards):
            x = np.random.randint(2)
            toss.append(x)
            if x == 0:
                heads += 1
            #else:
                #tails += 1
        
        left = l[:heads] #left hand
        right = l[heads:] #right hand
        shuffled = []   #shuffled deck
        
        for card in range(numCards):
            if toss[card] == 0:
                shuffled.append(left.pop(0))
            if toss[card] == 1:
                shuffled.append(right.pop(0))
        l = shuffled
    return l

numCards = int(input("Enter number of cards in deck: "))
l = list(range(numCards))
numPerformed = int(input("Enter number of shuffles to perform on deck: "))
print(shuffle(l))

I am using the coin-toss method to do riffle shuffle. Here is my JS code, but something is causing it to give the wrong answer:

const list = (numCards) => {
    var newList = []
    var i = 0;
    while (i < numCards){
        newList.push(i);
        i++;
    }
    return newList
}

function shuffle(l, numPerformed){
    for (var shuffles = 0; shuffles < numPerformed; shuffles++){
        var heads = 0;
        var tails = 0;
        var toss = [];
        for (var card = 0; card < l.length; card++){
            var x = Math.floor(Math.random() * 2);
            toss.push(x);
            if (x == 0){
                heads++;
            }else{
                tails++;
            }
        }
        var left = []; //l[:heads]
        var right = []; //l[heads:]
        for (var i = 0; i < l.length; i++){
            i < heads ? left.push(i) : right.push(i);
        }

        var shuffled = [];
        for (var card = 0; card < numCards; card++){
            if (toss[card] == 0){
                shuffled.push(left.shift());
            }else if (toss[card] == 1){
                shuffled.push(right.shift());
            }
        }
        l = shuffled;
    }
    return l
}

var numCards = parseInt(prompt("Enter number of cards in deck: "))
var l = list(numCards)
var numPerformed = parseInt(prompt("Enter number of shuffles to perform on deck: "));
console.log(shuffle(l))

What am I doing wrong? I think this error is caused due to my inexperience with JavaScript syntax.




How to uniformly sample integer partitions of n into m parts, with each part in {0,..,k}

How do you generate uniformly random samples for an integer n, number of parts m and upper bound of parts k, such that:

  1. all m parts sum to n
  2. each individual part is an integer from 0 to k (including both 0 and k)

For example, for n=2, m=3, k=4 all possible samples are:

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



I have tried to make a code that on getting input of 2 numbers from the user, generates a random number

This is the code I have. The main.js file is currently empty I keep it there just for show. The styles.css is currently only making the font cursive, so again, I didn't mention it. I hope it can be fixed without major changes. I need it to generate a random number between the two input numbers from a user on the webpage. I expect it to give me a random number between for example 1 and 10. It should give me something like 3 or maybe 7. I ran the snippet and it didn't give me any clear error. It said that there is a code error in line 0 file "".

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="styles.css" rel="stylesheet">
    <script src="main.js" defer></script>
</head>
<body>
    <input type="text" placeholder="First Value" id="firstNum"><br>
    <input type="text" placeholder="Second Value" id="secondNum"><br>
    <input type="text" placeholder="Generated Number" id="genNum"><br>
    <button onclick="genRand();">Generate</button><br>
    

    <script>
        var num1 = document.getElementById("firstNum").value;
        var num2 = document.getElementById("secondNum").value;
        var numGen;

        function genRand(num1, num2) {
            Math.floor(Math.random() * (num2 - num1 + 0) + num1) = numGen;
            document.getElementById("genNum").value = numGen;
        }
        
    </script>
</body>
</html>



Random Uniform 3D Distribution of Points Inside a Spherical Shell of Inner and Outer Radius

I'm trying to generate (as efficiently as possible), a random uniform, 3D distribution of points inside of a sphere of an inner radius r_min and outer radius r_max,i.e. a shell. I found a similar solution here: Sampling uniformly distributed random points inside a spherical volume, however this is only true for a whole sphere of r_min=0 and r_max=1. This is done using the following code:

r     = r_max*np.cbrt(np.random.uniform(low=r_min,high=r_max,size=nsamp))
phi   = np.random.uniform(0,2*np.pi,nsamp)
theta = np.arccos( np.random.uniform(-1,1,nsamp)

When r_min=0 and r_max=1.0, it produces the expected result (2D projection along x-y):

enter image description here

However, when I change either r_max or r_min to anything other than 0 and 1, I do not get the expected results, and this is likely due to the usage of np.cbrt(). How can I properly generate uniform random points on this spherical shell while specifying inner and outer radii?




Picking out a random class c# [closed]

so my problem is that I have a cooking program. I have several Recipes which consists of several materials. All of them are classes for example (class Egg()). The thing is that I have a Chef class instance and I need to give random materials to my chef. The question is that how do I create instances of a random material (Like a class Egg()).

To get it clearer here's an example: Chef Amy gets random materials like an Egg,Flour,Baking soda etc. So I have multiple material classes and I need to choose randomly from them. I do have a class hierarchy so I have an Ingredient base class, ingredients inherit from this class.

Thanks in advance.




Generate Random numbers using C

I want to initialize certain weights for training a neural network using C. However, I'm facing issues in initializing weights. Here's what I've tried -

double generate_random_num(){
    srand(time(NULL));
    double num = ((double)rand()/(double)RAND_MAX)*2.0 - 0.1;
    return num;
}

int main(){
    double x = generate_random_num();
    printf("%lf\n", x);
}

I get the outputs similar when I tried to run the program various times -

1.541774
1.510279
1.504480
1.502100

The generated numbers are close to 1.5 every time. It's not uniform over a range of values. How to generate random values which are uniform over a range?




More efficient way to formulate if/elif statement based on outcome of np.random.random?

I am attempting to speed up my code which has a long if/elif statement of the following form:

random = np.random.random()
tot = a + b + c + d

if random < a/tot:
   var1 += 1
elif a/tot < random < (a+b)/tot:
   var1 -= 1
elif (a+b)/tot < random < (a+b+c)/tot:
   var2 += 1
elif (a+b+c)/tot < random < tot:
   var2 -= 1

I have tried to figure out a way to do this with a dictionary but I can't figure out how I would index into it. The code works as is, however I am trying to speed up this section of the code which takes a large chunk of the runtime. Is there any other way to do this?




What is the time complexity of this while loop with two random operation and one if-else statement?

code is here:

combine_set = set()
total_num = k         # A constant variable
save_idx = 0
while save_idx < total_num:
    main_txt = random.choice(main_text)    # using python random module select a txt from list
    minor_txt = random.choice(minor_text)
    if (main_txt, minor_txt) in combine_set:
        continue
    else:
        save_idx += 1
        combine_set.add((main_txt, minor_txt))
        res = Combiner(main_txt, minor_txt)

I want to figure out the time complexity of this while loop. The Combiner operation's time complexity is O(n), and from here I know the time complexity of random.choice(list) in python is O(logn).

Now, my main problem is that I don't know how to handle the continue statement inside the if statement. Can anyone help me?




Audio for random answers - JS

everybody. I have a question. I did a magic 8 ball for practice with JS, and then someone told me if I could link the answers with an audio file that says exact the same that is displayed. I've been searching the web and I couldnt find an answer. I don't know how to link a Math.random list of the answers with the audio file. I'm sorry, I'm new and learning. Any idea would be highly appreciated.




lundi 26 avril 2021

python random error IndexError: list index out of range

I try to import random user-agent from a randua.txt file using this

uat = open('randua.txt', 'r')
ua_rand = uat.read().splitlines()
rua = random.choices(ua_rand)
header = {'User-Agent': rua}
r = requests.get('https://www.google.com/', headers=header)
print('Status Code : '+r.status_code)

but i dont know whats wrong i already checked maybe some typo or any error but when i try the script in another file it work, only in this file and i get this error

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    rua = random.choices(ua_rand)
  File "\Python\Python39\lib\random.py", line 487, in choices
    return [population[floor(random() * n)] for i in _repeat(None, k)]
  File "\Python\Python39\lib\random.py", line 487, in <listcomp>
    return [population[floor(random() * n)] for i in _repeat(None, k)]
IndexError: list index out of range

randua.txt

Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.94 Chrome/37.0.2062.94 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safari/600.8.9
Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240
Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.7.12 (KHTML, like Gecko) Version/8.0.7 Safari/600.7.12
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/7.1.8 Safari/537.85.17
Mozilla/5.0 (iPad; CPU OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H143 Safari/600.1.4
Mozilla/5.0 (iPad; CPU OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12F69 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.1; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko



How can I code a program so that when a random string is selected from an array a specific value is produced in java

I am new to coding and I wanted to make a program where when a random string value from an array is selected, it prints out that string as well as an int value that corresponds to it. So if "a" was selected, I want it to print out 1 and if "B" was selected, 2 and so forth. How would I go about doing something like that?

package example;

import java.util.Random;

public class Example {

public static String [] letter = {"a", "b", "c"};
public static int [] number = {1, 2, 3};

public static void main(String[] args) {

Random random = new Random();
int randomLetter = random.nextInt(letter.length);

System.out.println(letter [randomLetter] + number);
}
}



Generate numpy array of random integers within a range and some fixed integers outside the defined range

I want to combine two random number generator.

I want to generate size = 20 random integers between [-5,5] and a fixed integer -999.

I tried following code:

from random import randint, choice  
import numpy as np
np.random.seed(1)
dd = np.array([choice([randint(-999,-999),randint(-5,5)]) for _ in range(20)])
print(dd)

Result:

[-999 -999 -999   -4 -999 -999   -4 -999 -999    3    5   -3    2    0
   -1 -999 -999   -5 -999   -4]

Is there any better way to generate random integers? The result with current code has many -999 due to same upper and lower limit.




Random numbers with given range AND given sum [closed]

I know there are a lot of similar questions like this but none of them matches my problem exactly. So i would like to generate 6 random numbers, each of them are in the range of 1-8 AND their sum is 18.

[8, 1, 1, 1, 1, 6] would be a good (but quite extreme) example.

Edit:

I'm looking for an algorithm that would do this similar to: generate random integers with a specific sum

P.S.: I would like to implement this in java




Random output from vector within Map C++ [duplicate]

If I wanted to take a random output from a vector and store it into a string, I would use this method:

vector<string> vec = { "Hello", "World" };
string random = vec[rand() % vec.size()];

Say if I had a map with vec stored like this:

myMap["hello"] = vec;

How would I access this vector to randomize the output of that specific key? Would it be the same concept? I've tried a few things to no avail.




How to make weighted random sampling for matrix - Matlab

I would like to create a weighted sample from an m by n matrix starting from an excel file ("DataTab", please see image 1). First column (UGT) represents the ID of the matrix and the column B-F represent the probability associated to the variable "fi" for each UGT. "fi" is a scalar that has value 10, 20, 30, 40, 50: this means that UGT 1101 has 50% of probability to have value 10 or 20, the UGT 1102 can be 30 or 40, so on...

Image 1

I used "randsample function" that works only for scalar, and i can not be able to use it for my situation.

fi = [10,20,30,40,50];
p = [0.15,0.20,0.30,0.10,0.25];
n=10000;
sample = randsample (fi, n, true, p);
hist(sample,fi);
bar(fi,n*p,0.7);

I put the entire code which works correcty with "Fv2" variable, not working with "Fv1" which is the goal of my question.

Nsample = 10000 
DataTab = xlsread('Scenari_stabilita_R6.xlsx','S1','A2:f6');
Ugt   = csvread('raster_ugt.acs'); 
UgtV   = reshape(Ugt,[],1);
MRas   = [UgtV];
MCycle  = MRas(~idxNaN,:);
a=unique(MCycle(:,4));
idxDataTab=ismember(DataTab(:,1),a);
DataTab2 = DataTab(idxDataTab,:);
nUGT = length(a);    
fi = [10,20,30,40,50];
Fv = [];
    for i = 1:nUGT
        Fv1 = randsample (fi, Nsample, true, DataTab2(i,:));
        %Fv2 = (DataTab2(i,3)-DataTab2(i,2)).*rand(Nsample,1) +
        %DataTab2(i,2); % this line calculates uniform distribution and
        %it has to be modified into weighted sampling
        Fv = [Fv,Fv1];
    end

The "Fv1" variable must be like this:

Image 2 - final risults

Anyone can help me, please?




MATLAB's smoothdata function in Python

I have the following code in MATLAB for generation random trajectory:

N = 20;
scale = 40;
alpha = 0.8;

x = ones(N, 1);
y = ones(N, 1);
d = round(smoothdata(rand(N,2)*scale-(scale*alpha/2)));

for i = 2:N
    x(i) = x(i-1) + d(i, 1);
    y(i) = y(i-1) + d(i, 2);
end

This code generates a random trajectory, which I can plot as plot(x,y). Then, I apply some filtering on the obtained curve.

My question is, how can convert this MATLAB's code to Python, to obtain similar randomly generated trajectories? In Python, I want to write something like this:

import numpy as np

N = 20
scale = 40
alpha = 0.8

x = np.ones(N)
y = np.ones(N)
d = np.around(some_smoothing_function(np.random.rand(2, N) * scale - (scale * alpha / 2)))

for i in range(1, N):
    x[i] = x[i-1] + d[0][i]
    y[i] = y[i-1] + d[1][i]

What can I use as some_smoothing_function? It seems that Python does not have a function, that would do the same (or similar) as MATLAB's smoothdata function. And if I don't apply any function, then pairs of points (x[i],y[i]) are just too random and the trajectory does not look good.

Example of a good trajectory, which I want to create (this is what I got in MATLAB): enter image description here




Need regex to extract only alphabets from random string having 15length suppose "Anr2sne3niii5" in html language

i need to extract alphabets only from random string in html for Automation anywhere softwear




6*6 int array number generator with specific numbers

I want to make a 6*6 int array (global array), which has 36 numbers.

The 36 numbers must include 1, 2, 3, ..., 17, 18 and each number cannot appear more than twice. They need to be generated in totally random orders, e.g. no {1, 1, 2, 2, 3, 3, ...}, {1, 2, 3, ..., 1, 2, 3, ...}... Each time it can generate different random orders.

How to efficiently make a void function of this?

The compiling time must be as short as possible. Only rand() and simple things can be used (for, while, if, do-while).

int array[6][6];
void numberGenerator(){
    ...
}



dimanche 25 avril 2021

JMeter: How to pass random number that contains decimal?

We have to pass values random between 8, 8.5, 9, 9.5, 10, 10.5 like wise till 99. How may I achieve this?




Numpy Random Simulation Returns Same Results Every Time

I am currently trying to simulate a stochastic process (to be specific, the Vasicek Model) for my class in fixed income securities. I need to run a simulation multiple times for the same parameters to show different paths that interest rates can take. The code I am currently using is:

import numpy as np
import matplotlib.pyplot as plt

def vasicek(r0, K, theta, sigma, T, N, seed=777):    
    np.random.seed(seed)
    dt = T/float(N)    
    rates = [r0]
    for i in range(N):
        dr = K*(theta-rates[-1])*dt + sigma*np.random.normal()
        rates.append(rates[-1] + dr)
    return range(N+1), rates

My issue is that this function returns the same path when range and rates are plotted. Shouldn't np.random.normal() return different values every time I run this function? How can I change this code to make it do that?




How to locate and count the number of words in a column

So want to count the occurrences of contaminants but some cases has more than one contaminants so when I use the value_counts it counts them as one. For example "Gasoline, Diesel = 8" How would I count the them as separate without doing it manually.

And would it be possible to create a function that would make it easier to categorize them into lets say 4 types of contaminant? I just need a clue or a simple explanation on what I need to do.

data=pd.read_csv('Data gathered.csv') data

data['CONTAMINANTS'].value_counts().plot(kind = 'barh').invert_yaxis()

enter image description here

enter image description here




Windows RNG APIs inplemented in C program

During my research on the random number generation API in Windows 10, I found answear by user Anders. I really like his experimental results. I expected that he use some kind of a program to obtain this information. I tried to get similar informations using windbg preview and GDB for MinGW-W64 x86_64, v.9.2. But I couldn't get anything like that. Can anyone describe or advise me how to obtain such information?

I tried to work with these APIs: CryptGenRandom, BcryptGenRandom and RtlGenRandom on Windows 10 via C language.




Shuffle an Array is giving the same value in Javascript

I'm making a generator of random arrays shuffling one initial array multiple times.

SHUFFLE FUNCTION

const shuffle =(array) => {
    let currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array;
}

GENERATE CHROMOSOMES(This function generates an array of arrays that are randomized from an initial one "sequence")

const generateChromosomes = (numberOfChromosomes) =>{
    const result = [];
    const sequence = ["2", "3", "4"];

    for(let i = 1; i < numberOfChromosomes; i++){
        result.push(shuffle(sequence))
    }

    return(result);
}

I do not know why, each time when I run it, I don't get different arrays. I get 50 times the same one. When I re-run the code, it gives me 50 times another one.




Python - Random Values generation based on distribution

I need to create a simulation of case assignment in Python:

For each item in a list it needs to be assigned value from one of the below location based on the %age of cases that need to be assigned to each country.

Country Case Load
US 30%
UK 30%
India 30%
Singapore 10%

For example, if there are 100 items in a python list, each needs to be assigned to either of the countries in the list. For example, once the count of cases assigned to UK reaches 30, it needs to stop assigning US anymore.

distro = {'US': 0.3, 'UK': 0.3, 'India': 0.3, 'Singapore': 0.1}

locations = []
for key in distro.keys():
    locations.append(key)
locations

loc_assign = []
cases = 100

distro = {'US': 0.3, 'UK': 0.3, 'India': 0.3, 'Singapore': 0.1}

locations = []
for key in distro.keys():
    locations.append(key)
locations

for i in range(cases):
    a = random.choice(locations)
    if loc_assign.count(a) < distro.get(a):
        loc_assign.append(a)
    else:
        a = random.choice(locations)
        loc_assign.append(a)

But the output I am getting is below not correct:

US: 0.27
UK: 0.3
India: 0.22
Singapore: 0.21

How to I get this to arrive at the target distribution percentage.

I am fairly new to Python and can't figure this out. Any help would be appreciated.




node - TypeError: Cannot read property 'question' of undefined

I have a problem with a cli app that I'm converting to client/server app.

I have a function in the class I wrote that will manage the random extracion of some questions. Sometimes I've noticed that the function fails to extract questions and I get this error

/Users/dev/Desktop/demo/demo-gui.js:77
                question: this.questions[n].question,
                                            ^

TypeError: Cannot read property 'question' of undefined
    at DemoGUI.extractQuestions (/Users/dev/Desktop/demo/demo-gui.js:77:45)
    at /Users/dev/Desktop/demo/demo-gui.js:51:18
    at Layer.handle [as handle_request] (/Users/dev/Desktop/demo/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/dev/Desktop/demo/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/dev/Desktop/demo/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/dev/Desktop/demo/node_modules/express/lib/router/layer.js:95:5)
    at /Users/dev/Desktop/demo/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/dev/Desktop/demo/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/dev/Desktop/demo/node_modules/express/lib/router/index.js:275:10)
    at urlencodedParser (/Users/dev/Desktop/demo/node_modules/body-parser/lib/types/urlencoded.js:91:7)

this is the method of the class that cause the problem

    async extractQuestions(){
        this.askQuestions = [];
        this.questionsAnswers = [];


        for(let i = 0; i < 10; i++){
            let n = chance.integer({min: 0, max: this.questions.length});

            this.askQuestions.push({
                questionIndex: n,
                question: this.questions[n].question,
                choices: this.questions[n].possibleAnswers
            });

            this.questionsAnswers.push({
                index: n,
                correctAnswer: this.questions[n].correctAnswer 
            });
        }
        //this.maxScore = Math.floor( 5 * 10 );
    }

the questions are loaded from a json file that is loaded in constructor of the class

    constructor(questionsFile, uiResources){
        this.questionsData = fs.readFileSync(questionsFile, {encoding: 'utf-8'});
        this.questions = JSON.parse(this.questionsData);
        this.uiResources = uiResources;
        this.app = express();
    }

Is there a way to fix this problem?




how to restore numpy seed back to its former state?

I have a function which do some random things..

And I want to input seed to it, so for same seeds the output will be the same..

But initiating the seed at the beggining like this:

def generate_random_number(seed):

    np.random.seed(seed)
    return np.random.random(1)

Will result that after calling this method, the seed is ruined.

Is there a way to "save" the current seed state and restore it later?

So it will look something like this:

def generate_random_number2(seed):
    old_seed = np.random.get_seed()
    np.random.seed(seed)
    random_number = np.random.random(1)
    np.random.seed(old_seed)
    return random_number

Of course, the command: np.random.get_seed() is a made-up function.. is there something like this? Or alternative approach to generate "random" (up to seed input) output without destroying everyone's randomness state?

(The actual random process is much more complicated in practice, it generates matrices in loop so I would like to stick with the format of initiating seed at the beggining for simplicity)




How to generate random time in SAS and get time difference?

I am very new to SAS Programming. I have to create two variables for working hour calculation. I also have to use random time for this task. Here is what I have tried...

DATA wh;
in_1 = 28800;
in_2 = 36000;
out_1 = 18000;
out_2 = 25200;

DO i=1 TO 5;
  time_in = RAND("UNIFORM", in_1, in_2);
  time_out = RAND("UNIFORM", out_1, out_2);

  working_hour = INTCK('HOUR', time_out, time_in);
OUTPUT;
END;
RUN;

The random time generator works fine, but the INTCK function does not return expected values. I know it may be very silly. But I am stuck :(




samedi 24 avril 2021

How to let the user attempt many times?

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

/*

    1. the user can attempt many times and you need to display the number of successful attempt
    1. the range of random number 1..49
    1. output >> You successfully guess the number in 16 attempts
    1. output >> Do you want to play again?
  • */

public class GuessingGame {

public static void main(String[] args) {
    Scanner uInput = new Scanner(System.in);
    Random randNum = new Random();
    int guessNumber, number, count=0;
    String in;
    char again; 
    
    System.out.println("Welcome to Guessing Game");
    do {
            number = randNum.nextInt(50); // random number in the range of 1..50
    
            for(int i=0; i<5; i++)
            {
                System.out.println("Enter a number to guess: ");
                guessNumber = uInput.nextInt(); // get guess number from user
                
                if(guessNumber > number)
                {
                    System.out.println("Too big");
                }else if(guessNumber < number)
                {
                    System.out.println("Too small");
                }else
                {
                    System.out.println("Success");
                    count+=1;
                    return;
                }
            }
            System.out.println("You successfully guess the number in "+count);
            System.out.println("Do you want to play again? ");
            in = uInput.nextLine();
            
            again = in.charAt(0); //again will hold the first character from in var
            
    }while(again =='Y'|| again =='y');
    System.out.println("Guessing game terminate, thank you");
}

}




How to make an object move randomly with a mouse click using Java?

I'm quite new to Java, but I'm trying to make a game in which when you click on an object it moves randomly on the screen. For the object I chose a circle. It also reduces the size by 25 every time it is being clicked.

Here's the mouseClicked method

    public void mouseClicked(MouseEvent event)
    {
        circleClicked++;
        xClick = event.getX();      //adds the mouse x click position to variable x Click
        yClick = event.getY();      //adds the mouse y click position to variable y click
        repaint();                  //forces applet paint method to be called again
        
        if(CIRCLE_LENGTH < 2)       //resets the game only if the CIRCLE_LENGTH is equal or less than 0 and if the left mouse button is clicked
        {
            xClick = 0;
            yClick = 0;
            misses = 0;
            CIRCLE_LENGTH = 100;
        }
    }//end mouseClicked method

and here's the if statement for when the circle is clicked

//program only executes IF statement if the user clicks on the circle       
        if((xCircle == xClick) && (yCircle == yClick))
        {   
            hitNum++;
            //Paint x and y to a random integer value between MIN_RANDOM and MAX_RANDOM
            xCircle = X_MIN_RANDOM + (int)(Math.random()*(X_MAX_RANDOM - X_MIN_RANDOM));
            yCircle = Y_MIN_RANDOM + (int)(Math.arandom()*(Y_MAX_RANDOM - Y_MIN_RANDOM));
            CIRCLE_LENGTH = CIRCLE_LENGTH - 25;   //the circle length is subsctracted by 25 everytime the user click on the circle
        }//end if

Thanks for the help!




How to calculate the number of Blocks(1s) and gaps(0s) in a binary sequence

I have a assignment that I'm asked to count the number of Blocks & Gaps in a Pseudo random binary sequence and in a m-sequence LFSR and compare their outputs together. I can use either MATLAB or Python. I'd appreciate if you know something that might help and share with us.




BASH - Problem with generating a different random string in each curl command

I did a thorough research everywhere I could and yet came up short (partial solutions) on solving the problem described in the Title.

I tried adapting my script by using this solution found here - https://stackoverflow.com/a/32484733/7238741

chars=abcd1234ABCD
for i in {1..8} ; do
    echo -n "${chars:RANDOM%${#chars}:1}"
done
echo

PROBLEM: It will generate a random string for each curl command in my bash script, the problem is when it generates a, let's say, string of 5 characters, it will use 'neighbor' characters i.e. 45678 or defgh. So perhaps we should leave this solution aside completely, and focus on the next one.

Next, I used this solution in my script which seems would've done the job 100% - https://gist.github.com/earthgecko/3089509 - but... here's a practical example what I'd like to achieve - each of the two curl commands should end up posting a Random and Different comment which, in this case, consists of 5 alpha-numeric characters:

Here's v1 of the bash script:

#!/bin/bash

NEW_UUID=$(cat /dev/urandom | tr -dc "a-zA-Z0-9" | fold -w 5 | head -n 1)

curl "https://mywebsite.com/comment... ...&text=$NEW_UUID"; sleep 60;
curl "https://mywebsite.com/comment... ...&text=$NEW_UUID"; sleep 60;

Here's v2 of the bash script (I will use this one, I posted the more simple v1 just in case it's easier for someone to provide a solution)

#!/bin/bash

NEW_UUID=$(cat /dev/urandom | tr -dc "a-zA-Z0-9" | fold -w 5 | head -n 1)

for i in {1..2}; do curl "https://mywebsite.com/comment... ...&text=$NEW_UUID"; sleep 60; done

PROBLEM: In both versions, the script will generate a different random string each time it's executed, but that one string will be used for both curl commands, resulting in always posting the exact same comment both times ( ex: TuJ1a ), and the goal is to generate a different and random string for each curl command.

In the end, the first few answers to this Question which is somewhat the same as mine, do provide a solution how to "generate a different string in each line" - https://unix.stackexchange.com/questions/428737/how-can-i-add-random-string-for-each-line - it's just Their answers are adapted to OP's personal script, and unfortunately for me I do not have the proper knowledge to adapt those solutions to my 'v2 script'.

Thank you for any assistance / hint you may provide <3




Seeded Random Uniform float generator using SIMD?

I need a seeded random uniform distribution generator (in range [0, 1]) that can be coded using SIMD built with -march=nocona.

Xorshift https://en.wikipedia.org/wiki/Xorshift or Hash https://github.com/skeeto/hash-prospector seems good, but works with uint32/64, which are not well suited to translate in single (float) precision (due to conversion).

what would you suggest? it must be 32x4 vectorized, uniform spaced in range 0-1, seeded and quite fast.

Note: I'll use it to make white noise audio signal.




randomize time for looping task in discord

I have this code:

import discord
from discord.ext import tasks    
client = discord.Client()
@tasks.loop(minutes=1)
    async def test():
        channel = client.get_channel(MY_CHANNEL)
        await channel.send("hello")

    @client.event
    async def on_ready():
        test.start()

Which basically sends every minute a hello message in my channel. But is it also possible to randomize the time between the message sent. Like for one loop it is 3 and in the other 5...




{python} Can someone explain this code to me (random numbers)

im still fairly new to python im wondering what this code does

    import random
    import string
    chars = string.digits
    random =  ''.join(choice(chars) for _ in range(4))

i know it makes a 4 digit random number but i want to know how it works with the ''.join(choice(chars) for _ in range(4)) and what string.digits means!

Thanks




Python repeating a function n times repeats the same one

I have this code that randomly selects an item in the list and matches each other following a rule. I would like to repeat the matches N times, and count how many events occurred stored in variables tie and diff.

The problem is that, at the moment, it repeats N times the same results, not a different match. If I sate range(10) it will repeat the same match result 10 times. I would like to repeat the match N times, not the same result.

import random

rules = ['rock', 'paper', 'scissors']
pc1 = random.choices(rules)
pc2 = random.choices(rules)
tie = 0
diff = 0

def match():
    if pc1 == pc2:
        return False
        print('tie')
    if pc1 != pc2:
        return True
        print('different') 

for _ in range(10):
    if match() == False:
        tie +=1
    if match() == True:
        diff +=1
    
print(tie, diff)



vendredi 23 avril 2021

Why does random.choice() sometimes not make any choice?

I'm trying to create some logic that will reliably choose between two things. But the following code seems to have some serious bug in it because often there is no choice made.

import random
while True:
    if random.choice([0, 1]) == 0:
        print("Right")
    elif random.choice([0, 1]) == 1:
        print("Left")
    else:
        print("Why do we ever reach the else?")

The output looks like this:

$ python3 random.choice.broken.py 
Why do we ever reach the else?
Why do we ever reach the else?
Left
Why do we ever reach the else?
Left
Right
Left
Left
Why do we ever reach the else?
Why do we ever reach the else?
Right
Why do we ever reach the else?
Left
Right
Right
Why do we ever reach the else?
Left
Right
Left
Left
Right
Left
Right
Right
Right
Why do we ever reach the else?
Left
Why do we ever reach the else?
Why do we ever reach the else?
Right

I'm sure there must be a reasonable explanation. But I can't find it online or in the documentation. Thanks.




How do I make a discord.js random number generator that generates off user input

How do I make a discord.js random number generator that generates off user input? I've been trying to do this for a long time but just cant get anything to work with my format of code.

if (message.content == "<lottery") {
   let embed = new Discord.MessageEmbed()
   .setTitle("**Lottery Winner!**")
   .setDescription("The winner of the lottery's number is {The random number that is generated")
   .setColor("RANDOM")
   .setFooter(`Congratulations!`)
   .setThumbnail('https://cdn.discordapp.com/attachments/800757031506149426/835360163782459422/OIP.png')
   message.channel.send(embed);
}``` How do I somehow get the rng inside that embed?



Keep reducing values in a list until all of them are 0

I have an initial list called origin_list. I want to pick a position in this list at random and reduce the value of that positional element by 1 until all of them are 0. What would the fastest way to do this be?

I have some rather inaccurate pseudo-code below to get an idea of what I'm trying to do

import numpy as np
origin_list = [120,240,201]
while all(origin_list)>=0:
    rand_int = np.random.randint(0,len(origin_list))
    origin_list[rand_int] = origin_list[rand_int]-1
    if origin_list[rand_int]==0:
    # Continue with reducing only the non-zero elements in the list




Is there a way to exclude a specific integer from being randomly generated? [duplicate]

I'm attempting a problem which asks me to define a func() that generates 4 unique random integers from 2-8 (inclusive). I've got everything working so far, except that I can't figure out if it's even possible to ensure that the next randomly generated integer isn't a repeat from the given range (2-8)

Code so far:

def get_unique_code():
    code_str = ""

    while len(code_str) != 4:
        x = str(random.randint(2,8))
        code_str += x
    return code_str

Expected output: 6842

Got: 6846




How to make class-wide use of

I am trying to use the C++ random library by initializing it in the ctor and using it in private member functions. I am able to make the simple code in the highest rated answer from Generating random integer from a range work in a main with no functions, but I cannot get it to compile in a basic class with a header. What is needed to make the random library work in this kind of structure?

Randy.h

#ifndef Randy_H_
#define Randy_H_

#include <random>

class Randy
{
    public:
        Randy();
        unsigned short int Doit();
    private:
        std::random_device rd;
        std::mt19937 rng();
        std::uniform_int_distribution<unsigned short int> InRange1();
        std::uniform_int_distribution<unsigned short int> InRange2();

        unsigned short int GenerateBar();
};
#endif

Randy.cpp

#include <random>
#include "Randy.h"

using namespace std;

Randy::Randy()
{
    std::random_device rd;
    std::mt19937 rng(rd());
    std::uniform_int_distribution<unsigned short int> InRange1(0, 180);
    std::uniform_int_distribution<unsigned short int> InRange2(150, 15000);
}

unsigned short int Randy::Doit()
{
    unsigned short int x = GenerateBar();
    return x;
}

unsigned short int Randy::GenerateBar()
{
    unsigned short int oof = InRange1(rng);
    unsigned short int rab = InRange2(rng);
    unsigned short int bar = oof + rab;
    return bar;
}

g++ on Windows 10 complains as follows:

Randy.cpp: In member function 'short unsigned int Randy::GenerateBar()':
Randy.cpp:22:42: error: no matching function for call to 'Randy::InRange1(<unresolved overloaded function type>)'
     unsigned short int oof = InRange1(rng);
                                          ^
In file included from Randy.cpp:2:
Randy.h:14:59: note: candidate: 'std::uniform_int_distribution<short unsigned int> Randy::InRange1()'
         std::uniform_int_distribution<unsigned short int> InRange1();
                                                           ^~~~~~~~
Randy.h:14:59: note:   candidate expects 0 arguments, 1 provided
Randy.cpp:23:42: error: no matching function for call to 'Randy::InRange2(<unresolved overloaded function type>)'
     unsigned short int rab = InRange2(rng);
                                          ^
In file included from Randy.cpp:2:
Randy.h:15:59: note: candidate: 'std::uniform_int_distribution<short unsigned int> Randy::InRange2()'
         std::uniform_int_distribution<unsigned short int> InRange2();
                                                           ^~~~~~~~
Randy.h:15:59: note:   candidate expects 0 arguments, 1 provided

Thanks in advance...




Algorithm: randomly select points within user-defined ranges, separated by minimum user-defined intervals

I need to develop an algorithm that randomly selects values within user-specified intervals. Furthermore, these values need to be separated by a minimum user-defined distance. In my case the values and intervals are times, but this may not be important for the development of a general algorithm.

For example: A user may define three time intervals (0900-1200, 1200-1500; 1500-1800) upon which 3 values (1 per interval) are to be selected. The user may also say they want the values to be separated by at least 30 minutes. Thus, values cannot be 1159, 1201, 1530 because the first two elements are separated by only 2 minutes.

A few hundred (however many I am able to give) points will be awarded to the most efficient algorithm. The answer can be language agnostic, but answers either in pseudocode or JavaScript are preferred.

Note:

  • The number of intervals, and the length of each interval, are completely determined by the user.
  • The distance between two randomly selected points is also completely determined by the user (but must be less than the length of the next interval)



How to run a group of functions in a random order [duplicate]

I want to run 4 functions in a random order. Not sure where to start. Here is my code without the random order.

generate.addEventListener('click', generateclick)

function generateclick(){
fifth()
fourth()
majthird()
minthird()
}



While loop causing function to return 0 in c

I have the following c function working on implementing a rejection sampler. MersenneTwiser.h generates a random number between 0 and 1. The issue I'm having is with the rnorm function. I'm using a while loop to reject some samples. It's nonsense at the moment as it's not finished. In it's current form, the program returns 0.00000.

#include<stdio.h>
#include<math.h>
#include"MersenneTwister.h"
MTRand rng;

double p;
double prop;
int sign;


double dubexp(double theta){
    p = rng.rand();

    if ((p-0.5) > 0) sign= 1;
    if ((p-0.5) < 0) sign= -1;

    prop = -(1/theta)*sign*log(1-2*abs(p-0.5));
    return(prop);
}


double u;
double theta;
double t;
double z;
double c;
double x;

double rnorm(double theta, double c){

    t=rng.rand();
    while (z == t)
    {
        x=dubexp(theta);
        u=rng.rand();
        z=x;

    }
    return z;
}

int main(){
    theta=1;
    c=1;
    
    u = rnorm(theta,c);
    printf("%f",u);
}

However if I remove the while loop, it returns the correct value of z. As below:

double rnorm(double theta, double c){

    t=rng.rand();
     x=dubexp(theta);
        u=rng.rand();
        z=x;
    
    
    return z;
}



Random numbers with orders less than E-1

I'm currently working on a Monte Carlo simulation in Python, so I need to generate pseudo-random numbers, but the thing is, I need to generate numbers between 0 and 1, that follow the uniform distribution, but also with orders less than E-1, specifically, I'm searching numbers with orders of E-5.

My first thought was to use random.uniform, but I found that the numbers obtained were at least with an order of E-2 and also that's not too common.

Later, I thought that my problem could be solved by making the following function:

from scipy.stats import uniform


def numrand():
        vec=np.linspace(uniform.ppf(0),uniform.ppf(1), 10000) 
        return random.choice(vec)

But I don know if it is the more efficient way to do it because I need to optimize my code the most possible.

I wanted to ask you if you can give me some ideas.




why does my randomizer show the same number when i run the program?

i'm new in C# and trying to make a dice game. i've made a do while loop, and it works. my problem is i've made a randomizer with number, but once i throw the dice and it shows 5. it keeps showing 5, and not a new number. kinda destroying the game.

heres my codes

ps. im danish, thats why, some of the words you may not understand. hope you can help

static void Main(string[] args) {

        int liv; ; // det er monsterets liv
        Random rnd = new Random();
        int dice = rnd.Next(1, 6); /*den vælger et random tal mellem 1 til 6*/

        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("velkommen til monster terning spil. du vinder spillet ved at dræbe monsteret");
        Console.WriteLine("indtast hvor mange liv monsteret skal have ");

        liv = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("du har givet monsteret {0} liv", liv);

        Console.Write("tryk på en knap for at komme videre");
        Console.ReadKey();//når du trykker på en knap kommer du videre
        Console.Clear();

        Console.WriteLine("slå med terningen tryk på en knap for");
            Console.ReadKey();

        do {
            if ((dice == 3) || (dice == 2)) { //hvis der bliver slået 3 eller 2 skal den gøre følgende
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("du slog {0} monsteret slog tilbage", dice);
                Console.WriteLine("tryk på en knap for at slå med terningen igen");
                Console.ReadKey();
            }
            if (dice == 1) { //hvis der bliver slået 1 skal den gøre følgende
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("du slog {0} monsteret giver dobbelt skade.", dice);
                Console.WriteLine("tryk på en tast for at slå med terningen igen");
                Console.ReadKey();
            }
            if ((dice == 4) || (dice == 5)) { //hvis der bliver slået 4 eller 5 skal den gøre følgende
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("du slog {0} monsteret har taget 1 skade.", dice);
                Console.WriteLine("monsterets liv er nu {0}", --liv);
                Console.WriteLine("tryk på en tast for at slå med terningen igen");
                Console.ReadKey();
            }
            if (dice == 6) { //hvis der bliver slået 6 skal den gøre følgende
                Console.Clear();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("du slog {0} dobbelt skade er givet. monsterets liv er nu {1}", dice, liv = -2);
                Console.WriteLine("tryk på en tast for at slå med terningen");
                Console.ReadKey();
            }
        }
        while (liv > 0); //jeg vil have spillet til at kører så længe liv er større end 0
                
        if (liv == 0) {
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("du vandt! monsteret er dræbt!!");
        }



Is the random function in Kotlin slow?

I was using the random function to make a dice app in Kotlin. I also added a button to roll the dice and a Toast to notify that the dice are rolled. But, if I keep on pressing the roll button repeatedly, the app seems to skip some button clicks. Also, the Toast is showing absurd behaviour, it doesn't refresh on some clicks. I think that this could be due to the slow random function where I press the roll button even before the roll has been executed. Could anyone please confirm.

Here's my MainActivity.kt:

  package com.example.diceroller

  import android.os.Bundle
  import android.widget.Button
  import android.widget.TextView
  import android.widget.Toast
  import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val toast = Toast.makeText(this, "Dice Rolled!", Toast.LENGTH_SHORT )

    val rollButton: Button = findViewById(R.id.button)
    rollButton.setOnClickListener {
        toast.cancel()
        toast.show()
        rollDice()
    }
}

private fun rollDice() {
    val dice = Dice(6)
    val diceRoll = dice.roll()
    val resultTextView: TextView = findViewById(R.id.textView)
    resultTextView.text = diceRoll.toString()
 }
}

class Dice(private val numSides: Int) {
fun roll(): Int {
    return (1..numSides).random()
 }
}



How to generate random numbers from a function in rStudio

I'm having difficulty generating a random sample of size 1000 from a function. Say the function is function(x){0.25*x}. Please help




Give lower values a higher weight in a `randint()` function

Using randint() how do I give lower values a higher weight (higher chance to be picked)?

I have the following code:

def grab_int():
    current = randint(0,10) 
    # I want the weight of the numbers to go down the higher they get (so I will get more 0s than 1s, more 1s than 2, etc)

Is it possible to do with only 1-2 lines of code, or do I need an entire function for giving them weight?




make up a new word using python [closed]

In different contexts, it may be of interest to randomize things under set conditions. An example of this could be to come up with words that could be found in the Swedish language. This is because you may want to suggest a new password that is not so difficult to come up with but that perhaps no one would think of guessing.

The rules around which words are built are:

· A vowel is followed by a consonant

· A vowel cannot be next to another vowel

· A consonant is followed by a vowel or a consonant, if there are not already 2 consonants in a row

Requirements

· The program must be able to come up with a word that meets the rules above.

· The user should be able to determine the length of the word. Either as an exact length or as a range.

· The word that is random should be able to start with a vowel and a consonant

· The word should always start with a capital letter

· The program can randomize a compound word

Please let me knoe if you can help!!




jeudi 22 avril 2021

I have been trying to get the turtle to keep going to a random spot

This is my code so far or go here https://trinket.io/python/6ded35a6a8

import turtle
import time
import random
mason = turtle
import random

number = 7 



for i in range(15):
  mason.goto(qty, qty)
  mason.circle(2)



Random Point System

I am currently working on my final project for my introduction to programming class we are using Python. I wanted to make a pong game but with a twist. Since I figured that normal pong is overused, I wanted to make it so that there was a different point system.

That said, I want to make a point system that will randomly add and subtract points to player a and b and have them switch scores at least once a game. Any advice on how to do it?




python random IndexError: list index out of range

i try to use this python code this but i dont know what wrong pls help

def bbl(size):
    out_str = ''
    for _ in range(0, size):
        a = random.randint(65, 160)
        out_str += chr(a)
    return(out_str)

def UserAgProces():
    global t_user_agent
    global t_referer_list
    param_joiner = '&'
    uat = open('randua.txt', 'r')
    rft = open('randrf.txt', 'r')
    t_user_agent = uat.read().splitlines()
    t_referer_list = uat.read().splitlines()
    uareq = urllib.request.Request(url + param_joiner + bbl(random.randint(3,10)) + '=' + bbl(random.randint(3,10)))
        uareq.add_header('User-Agent', random.choice(t_user_agent))
        uareq.add_header('Cache-Control', 'no-cache')
        uareq.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
        uareq.add_header('Referer', random.choice(t_referer_list) + bbl(random.randint(50,100)))
        uareq.add_header('Keep-Alive', random.randint(110,160))
        uareq.add_header('Connection', 'keep-alive')
        uareq.add_header('Host',host)

url=input('Url Or IP (eg. http/s://www.example.com/) : ')
UserAgProces()

error i get when try to run this. can someone help me i confused whats wrong with this

Traceback (most recent call last):
  File "main.py", line 39, in <module>
    UserAgProces()
  File "main.py", line 33, in UserAgProces
    uareq.add_header('Referer', random.choice(t_referer_list) + bbl(random.randint(50,100)))
  File "random.py", line 347, in choice
    return seq[self._randbelow(len(seq))]
IndexError: list index out of range

randrf.txt (some random referer text)

http://www.google.com/?q=
http://www.usatoday.com/search/results?q=
http://engadget.search.aol.com/search?q=
http://www.google.com/?q=
http://www.usatoday.com/search/results?q=
http://engadget.search.aol.com/search?q=
http://www.bing.com/search?q=
http://search.yahoo.com/search?p=
http://www.ask.com/web?q=
http://search.lycos.com/web/?q=
http://busca.uol.com.br/web/?q=
http://us.yhs4.search.yahoo.com/yhs/search?p=
http://www.dmoz.org/search/search?q=
http://www.baidu.com.br/s?usm=1&rn=100&wd=
http://yandex.ru/yandsearch?text=
http://www.zhongsou.com/third?w=
http://hksearch.timway.com/search.php?query=
http://find.ezilon.com/search.php?q=
http://www.sogou.com/web?query=
http://api.duckduckgo.com/html/?q=
http://boorow.com/Pages/sitebraspx?query=
http://validator.w3.org/check?uri=
http://validator.w3.org/checklink?uri=
http://validator.w3.org/unicorn/check?ucntask=conformance&ucnuri=
http://validator.w3.org/nu/?doc=
http://validator.w3.org/mobile/check?docAddr=
http://validator.w3.org/p3p/20020128/p3p.pl?uri=
http://www.icap2014.com/cms/sites/all/modules/ckeditorlink/proxy.php?url=
http://www.rssboard.org/rss-validator/check.cgi?url=
http://www2.ogs.state.ny.us/help/urlstatusgo.html?url=
http://prodvigator.bg/redirect.php?url=
http://validator.w3.org/feed/check.cgi?url=
http://www.ccm.edu/redirect/goto.asp?myURL=
http://forum.buffed.de/redirect.php?url=
http://rissa.kommune.no/engine/redirect.php?url=
http://www.sadsong.net/redirect.php?url=
https://www.fvsbank.com/redirect.php?url=
http://www.jerrywho.de/?s=/redirect.php?url=
http://www.inow.co.nz/redirect.php?url=
http://www.automation-drive.com/redirect.php?url=
http://mytinyfile.com/redirect.php?url=
http://ruforum.mt5.com/redirect.php?url=
http://www.websiteperformance.info/redirect.php?url=
http://www.airberlin.com/site/redirect.php?url=
http://www.rpz-ekhn.de/mail2date/ServiceCenter/redirect.php?url=
http://evoec.com/review/redirect.php?url=
http://www.crystalxp.net/redirect.php?url=
http://watchmovies.cba.pl/articles/includes/redirect.php?url=
http://www.seowizard.ir/redirect.php?url=
http://apke.ru/redirect.php?url=
http://seodrum.com/redirect.php?url=
http://redrool.com/redirect.php?url=
http://blog.eduzones.com/redirect.php?url=
http://www.onlineseoreportcard.com/redirect.php?url=
http://www.wickedfire.com/redirect.php?url=
http://searchtoday.info/redirect.php?url=
http://www.bobsoccer.ru/redirect.php?url=

randua.txt (some random user agent text)

Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.94 Chrome/37.0.2062.94 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safari/600.8.9
Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240
Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.7.12 (KHTML, like Gecko) Version/8.0.7 Safari/600.7.12
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/7.1.8 Safari/537.85.17
Mozilla/5.0 (iPad; CPU OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H143 Safari/600.1.4
Mozilla/5.0 (iPad; CPU OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12F69 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.1; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.6.3 (KHTML, like Gecko) Version/8.0.6 Safari/600.6.3
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (iPhone; CPU iPhone OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H321 Safari/600.1.4
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (iPad; CPU OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)
Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (X11; CrOS x86_64 7077.134.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.156 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.7.12 (KHTML, like Gecko) Version/7.1.7 Safari/537.85.16
Mozilla/5.0 (Windows NT 6.0; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (iPad; CPU OS 8_1_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B466 Safari/600.1.4
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_1_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B440 Safari/600.1.4
Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; KFTT Build/IML74K) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12D508 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (iPad; CPU OS 7_1_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D201 Safari/9537.53
Mozilla/5.0 (Linux; U; Android 4.4.3; en-us; KFTHWI Build/KTU84M) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.6.3 (KHTML, like Gecko) Version/7.1.6 Safari/537.85.15
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.4.10 (KHTML, like Gecko) Version/8.0.4 Safari/600.4.10
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.78.2 (KHTML, like Gecko) Version/7.0.6 Safari/537.78.2
Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) CriOS/45.0.2454.68 Mobile/12H321 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; Touch; rv:11.0) like Gecko
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B410 Safari/600.1.4
Mozilla/5.0 (iPad; CPU OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53
Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; TNJB; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; ARM; Trident/7.0; Touch; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MDDCJS; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Windows NT 6.2; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (iPhone; CPU iPhone OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12H143 Safari/600.1.4
Mozilla/5.0 (Linux; U; Android 4.4.3; en-us; KFASWI Build/KTU84M) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) GSA/7.0.55539 Mobile/12H321 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12F70 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MATBJS; rv:11.0) like Gecko
Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; KFJWI Build/IMM76D) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D167 Safari/9537.53
Mozilla/5.0 (X11; CrOS armv7l 7077.134.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.156 Safari/537.36
Mozilla/5.0 (X11; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.25
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like Gecko) Version/8.0.2 Safari/600.2.5
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.1.25 (KHTML, like Gecko) Version/8.0 Safari/600.1.25
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56
Mozilla/5.0 (Linux; U; Android 4.4.3; en-us; KFSOWI Build/KTU84M) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3
Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_1_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B435 Safari/600.1.4
Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240
Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; LCJB; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MDDRJS; rv:11.0) like Gecko
Mozilla/5.0 (Linux; U; Android 4.4.3; en-us; KFAPWI Build/KTU84M) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; Touch; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; LCJB; rv:11.0) like Gecko
Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; KFOT Build/IML74K) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (Linux; U; Android 4.4.3; en-us; KFARWI Build/KTU84M) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; ASU2JS; rv:11.0) like Gecko
Mozilla/5.0 (iPad; CPU OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A405 Safari/600.1.4
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.77.4 (KHTML, like Gecko) Version/7.0.5 Safari/537.77.4
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; yie11; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MALNJS; rv:11.0) like Gecko
Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) GSA/8.0.57838 Mobile/12H321 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (Windows NT 10.0; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MAGWJS; rv:11.0) like Gecko
Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/7.1.5 Safari/537.85.14
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; TNJB; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; NP06; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36 OPR/31.0.1889.174
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.4.8 (KHTML, like Gecko) Version/8.0.3 Safari/600.4.8
Mozilla/5.0 (iPad; CPU OS 7_0_6 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B651 Safari/9537.53
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/7.1.3 Safari/537.85.12
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko; Google Web Preview) Chrome/27.0.1453 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A365 Safari/600.1.4
Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 AOL/9.7 AOLBuild/4343.4049.US Safari/537.36
Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) CriOS/45.0.2454.68 Mobile/12H143 Safari/600.1.4
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 8_4_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12H321
Mozilla/5.0 (iPad; CPU OS 7_0_3 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B511 Safari/9537.53
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.1.17 (KHTML, like Gecko) Version/7.1 Safari/537.85.10
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.2.5 (KHTML, like Gecko) Version/7.1.2 Safari/537.85.11
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; ASU2JS; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; MDDCJS; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.3; rv:40.0) Gecko/20100101 Firefox/40.0
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.34 (KHTML, like Gecko) Qt/4.8.5 Safari/534.34
Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53 BingPreview/1.0b
Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0
Mozilla/5.0 (iPad; CPU OS 8_4 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) GSA/7.0.55539 Mobile/12H143 Safari/600.1.4
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Mozilla/5.0 (X11; CrOS x86_64 7262.52.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.86 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MDDCJS; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/600.4.10 (KHTML, like Gecko) Version/7.1.4 Safari/537.85.13
Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko
Mozilla/5.0 (iPad; CPU OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) CriOS/45.0.2454.68 Mobile/12F69 Safari/600.1.4
Mozilla/5.0 (Android; Tablet; rv:40.0) Gecko/40.0 Firefox/40.0
Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10) AppleWebKit/600.2.5 (KHTML, like Gecko) Version/8.0.2 Safari/600.2.5
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Linux; U; Android 4.4.3; en-us; KFSAWI Build/KTU84M) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 AOL/9.8 AOLBuild/4346.13.US Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; MAAU; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.74.9 (KHTML, like Gecko) Version/7.0.2 Safari/537.74.9
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A501 Safari/9537.53
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; MAARJS; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53
Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko
Mozilla/5.0 (iPad; CPU OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) GSA/7.0.55539 Mobile/12F69 Safari/600.1.4
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.78.2 (KHTML, like Gecko) Version/7.0.6 Safari/537.78.2
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MASMJS; rv:11.0) like Gecko
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36 OPR/31.0.1889.174
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; FunWebProducts; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MAARJS; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; BOIE9;ENUS; rv:11.0) like Gecko
Mozilla/5.0 (Linux; Android 4.4.2; SM-T230NU Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.84 Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; EIE10;ENUSWOL; rv:11.0) like Gecko
Mozilla/5.0 (Windows NT 5.1; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:39.0) Gecko/20100101 Firefox/39.0
Mozilla/5.0 (Linux; U; Android 4.0.4; en-us; KFJWA Build/IMM76D) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36

I dont know what wrong i try another code but still have same error result