w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to test that a method generating random numbers does generate random numbers
The links in comment by mob provide much detail on how difficult it is to assert that a data source is random. For your unit test, you may be better off using srand in the test setup (making this technically a "white box" test), and relying on the fact that behaviour of rand() is well known. This is normal practice as far as I know, unless you want to test a PRNG or entropy source that you have written.

Categories : Perl

How to generate 6-8 digit random numbers without colliding with previous generated numbers in time critical fashion?
The easiest thing to do is generate random numbers and generating a new random id if you get a duplicate. This works because with your figures the probability of getting a duplicate is pretty small. If that doesnt convince you, you can think of many schemes that guarantee mathematically that the numbers will be unique and still look random, but it gets complex.

Categories : C#

java random numbers generator which generate twenty four numbers
Here's the easiest way I can think of: @Test public void random24Numbers() { String random = RandomStringUtils.random(24, false, true); System.out.println(random); } This uses RandomStringUtils.random. The first parameter is the length, the second says, "no letters". The third says, "give me numbers". Here's an example output: 564266161898194666197908 Yes, it's a String, but I'm going to assume you know how to convert a String into a number.

Categories : Java

PHP generate two random numbers without repeating eachother neither previous numbers
I am just shooting in the dark here, but if the numbers are in the same call i.e $ticket_number1 and $ticket_number2 are same in one call to the page, you can fix this by telling the function to reject an already chosen number function getTicket($exclude=-1){ $count=1; while($count){ $ticket_number = mt_rand(01990, 32000); $query = "SELECT ticket1 FROM `tickets` WHERE `ticket1` == '$ticket_number' or `ticket2` == '$ticket_number'"; $count = mysql_num_rows(mysql_query($query)); if(!$count) $count=$ticket_number==$exclude; } return $ticket_number; } $ticket_number1 = getTicket(); $ticket_number2 = getTicket($ticket_number1);

Categories : PHP

Generate 30 Random Numbers from a given sum
If you want to have 23 random numbers with sum of 2345, you can use this code: int sum = 2345; int nums = 23; int max = sum / nums; Random rand = new Random(); int newNum = 0; int[] ar = new int[23]; for (int i = 0; i < nums-1; i++) { newNum = rand.Next(max); ar[i] = newNum; sum-= newNum; max = sum / (nums-i-1); } ar[nums - 1] = sum; It will give you:

Categories : C#

How do I generate a sum of random numbers?
In pure Ruby sum = [*0..70].sample(5).inject(&:+) until (140..220) === sum if you use ActiveSupport then you can use #sum instead of inject(&:+).

Categories : Ruby

PHP Generate x amount of random odd numbers within a range
Generate x integer values over half the range, and for each value double it and add 1. ANSWERING REVISED QUESTION: 1) Generate a list of candidates in range, shuffle them, and then take the first x. Or 2) generate values as per my original recommendation, and reject and retry if the generated value is in the list of already generated values. The first will work better if x is a substantial fraction of the range, the latter if x is small relative to the range. ADDENDUM: Should have thought of this approach earlier, it's based on conditional probability. I don't know php (I came at this from the "random" tag), so I'll express it as pseudo-code: generate(x, upper_limit) loop with index i from upper_limit downto 1 by 2 p_value = x / floor((i + 1) / 2) if rand <= p_value

Categories : PHP

How would I generate a random sample in python with numbers between 1-x?
sample = random.sample(range(classNumber+1), classNumber+1) Here's your problem. This sample makes no sense. First, you didn't set a lower bound on the range, so it defaults to 0 instead of 1. Second, if you just increase the lower bound, you'll be trying to draw more numbers from the range than the range actually has. There's no part of your code that says random.sample(range(1,16), classNumber). Is that what this line was supposed to say?

Categories : Python

How to generate 100 random 3 digit numbers in java?
Try for loop for(int i=0;i<100;i++) { int pick = rand.nextInt(900) + 100; System.out.println(pick); }

Categories : Java

Trying to generate a series of unique random numbers
Instead of picking random integers, shuffle a list and pick the first two items: import random choices = ['Candy', 'Steak', 'Vegetables'] random.shuffle(choices) item1, item2 = choices[:2] Because we shuffled a list of possible choices first, then picked the first two, you can guarantee that item1 and item2 are never equal to one another. Using random.shuffle() leaves the option open to do something with the remaining choices; you only have 1 here, but in a larger set you can continue to pick items that have so far not been picked: choices = list(range(100)) random.shuffle(choices) while choices: if input('Do you want another random number? (Y/N)' ).lower() == 'n': break print(choices.pop()) would give you 100 random numbers without repeating. If all you need is a

Categories : Python

Generate random numbers from a three dimensional probability distribution
If your spatial coordinate system is discrete, treat it as a univariate generation problem to generate triplets. If you're talking about a continuous distribution you probably want to use conditional probability. In principle you should be able to derive the marginal distribution of the X's, the conditional distribution of Y given X, and the conditional distribution of Z given X & Y. Then generate X, Y, and Z sequentially from their marginal and conditional distributions. In practice this may be quite challenging. Addendum Perhaps the easiest scheme would be to generate a multidimensional normal vector of length 3. This would give the highest density near the origin and taper off symmetrically in all directions. You could displace it with a mean vector if the density is highest

Categories : Misc

Generate more than one random numbers using native or built-in function
try something like this Create an ArrayList and add your random number and while adding check if ArrayList already contains the number or not. Eg: ArrayList<Integer> numbers = new ArrayList<Integer>(); while (numbers.size()<=YOUR_MAX_SIZE) { int randomInteger = ( int )( Math.random() * 9999 ); if (!numbers.contains(randomInteger)) { { numbers.add(randomInteger); } }

Categories : Java

Generate a specific amount of random numbers that add up to a defined value
You will have no problem meeting any two out of your three constraints, but all three might be a problem. As you note, the standard way to generate N random numbers that add to a sum is to generate N-1 random numbers in the range of 0..sum, sort them, and take the differences. This is basically treating your sum as a number line, choosing N-1 random points, and your numbers are the segments between the points. But this might not be compatible with constraints on the numbers themselves. For example, what if you want 10 numbers that add to 1000, but each has to be less than 100? That won't work. Even if you have ranges that are mathematically possible, forcing compliance with all the constraints might mean sacrificing uniformity or other desirable properties. I suspect the only way to

Categories : R

How to generate random double numbers with high precision in C++?
In a typical system, RAND_MAX is 231-1 or something similar to that. So your "precision" from using a method like:L double r = rand()/RAND_MAX; would be 1/(2<sup>31</sup)-1 - this should give you 8-9 digits "precision" in the random number. Make sure you print with high enough precision: cout << r << endl; will not do. This will work better: cout << fixed << sprecision(15) << r << endl; Of course, there are some systems out there with much smaller RAND_MAX, in which case the results may be less "precise" - however, you should still get digits down in the 9-12 range, just that they are more likely to be "samey".

Categories : C++

How do I generate random numbers from a column, without duplicates - SQL Server
You could try using newid(): INSERT INTO #RandomUsers Select TOP 10 userId From Profile WHERE userId <> @UserID ORDER BY newid() This way you get ten different users that are not the one you passed in parameter. But I don't know how you can get really good randomness in SQL Server. Edit: I think you can also use tablesample() for this kind of issue, but I don't really know how to use this. By the way, if a hole appears in the id sequence (like user 34 is deleted), you could still pick 34 with your method, while methods taking a sample from the table directly will still work.

Categories : Sql Server

How do I generate random numbers in an array that add up to a defined total?
A good way to achieve uniformity is, for example, to fill up a = 15 units into an 8 element array: Put 1 in each element in the array as this is your requirement, you have now 7 values left to distribute Roll a random number between 0 and the max index of the array, and add 1 to that element, and subtract 1 from 7. Do this until 7 goes down to zero. In this way, you'll meet your minimum conditions by having each element have minimum value 1. Then you distribute the remaining totals in a completely random way.

Categories : Java

Generate a random number from a density object (or more broadly from a set of numbers)
If all you need is to draw values from your existing pool of numbers, then sample is the way to go. If you want to draw from the presumed underlying distribution, then use density , and fit that to your presumed distribution to get the necessary coefficients (mean, sd, etc.), and use the appropriate R distribution function. Beyond that, I'd take a look at Chapter7.3 ("rejection method") of Numerical Recipes in C for ways to "selectively" sample according to any distribution. The code is simple enough to be easily translated into R . My bet is someone already has done so and will post a better answer than this.

Categories : R

How to generate scale-independent random floating point numbers?
You are correct that your approach doesn't return some numbers. For example, there is no floating-point number between 1.0 and 1.0000000000000002, but 10**1.0000000000000002 is 10.000000000000005, and there are two numbers between 10.0 and 10.000000000000005: 10.000000000000002 and 10.000000000000004. Those two numbers will never be returned by your algorithm. But you can cheat and use Decimal to exponentiate with greater precision: >>> float(10 ** Decimal('1')) 10.0 >>> float(10 ** Decimal('1.0000000000000001')) 10.000000000000002 >>> float(10 ** Decimal('1.00000000000000015')) 10.000000000000004 >>> float(10 ** Decimal('1.0000000000000002')) 10.000000000000005 So, arbitrary needs to generate random Decimal exponents of sufficient precision and use

Categories : Python

Very non-random factor of Math.random when filling an array with random numbers
If the length is even, you add all the numbers once and subtract all of them once – of course, the result is 0. Example with length==6: /*i==0*/ sum += rand[0] + rand[5]; /*i==1*/ sum -= rand[1] + rand[4]; /*i==2*/ sum += rand[2] + rand[3]; /*i==3*/ sum -= rand[3] + rand[2]; /*i==4*/ sum += rand[4] + rand[1]; /*i==5*/ sum -= rand[5] + rand[0]; Did you try any uneven lengths?

Categories : Java

Given 4 numbers of array of 1 to 10 elements. Find 3 numbers whose sum can generate all the four numbers?
Since the solution contains only 3 numbers which are in 1..10 range, brute force is an effective algorithm here (at most 1000 possibilities to check even in naive implementation). So C# code could be public static int[] BruteForce(int[] data) { HashSet<int> hs = new HashSet<int>(); for (int x = 1; x <= 10; ++x) for (int y = x; y <= 10; ++y) for (int z = y; z <= 10; ++z) { hs.Clear(); for (int i = 0; i < data.Length; ++i) hs.Add(data[i]); hs.Remove(x); hs.Remove(y); hs.Remove(z); hs.Remove(x + y); hs.Remove(x + z); hs.Remove(y + z); hs.Remove(x + y + z); if (hs.Count <= 0) return new int[] { x, y, z }; // <- Solution } return new in

Categories : Arrays

Java arraylist. I need to pass random numbers to an array list and pass them to another class to check those numbers against another set of numbers
You can always transform the random int to a string by using Integer.toString() before inserting into your array list. You can convert the String back to int using Integer.parseInt() E.g. for (int i = 0 ; i < 3 ; i++) { locations.add(Integer.toString((int)(Math.random() * 5)); }

Categories : Java

Adding the sum of all the random numbers in a random number generator
You'll want to put this inside of the for loop: sum = sum + n; (or sum += n;) Then after the loop, the average will be the sum divided by 100. Also you can take out the min and max part, unless that is needed for something else.

Categories : C#

How many random numbers can I get with .nextInt() from Random class in Java?
StackOverflowError is what you get when your recursion runs too deep. Solution: convert it to an iterative version. Way to go from recursion to iteration

Categories : Java

Generate Random Number Using Random Series
$series = array( 'BT4YX***1', 'BT4YX**X1', 'BT4Y**X*1', 'BT4YXXXX1', ); $result = preg_replace_callback( '/[X*]/', function ($matches) { switch($matches[0]) { case '*' : return range(0,9)[array_rand(range(0,9))]; case 'X' : return range('A','E')[array_rand(range('A','E'))]; } }, $series ); var_dump($result); EDIT Requires PHP >= 5.4.0; but if you refactored the array dereferencing, you could use it with 5.3.0 or above, e.g. $series = array( 'BT4YX***1', 'BT4YX**X1', 'BT4Y**X*1', 'BT4YXXXX1', ); $result = preg_replace_callback( '/[X*]/', function ($matches) { switch($matches[0]) { case '*' : $range = range(0,9);

Categories : PHP

Find random numbers in a given range with certain possible numbers excluded
If you have no constraints at all, i guess this is the easiest way: create an array containing the valid values, a[0]...a[m] . Return a[rand(0,...,m)]. If you don't want to create an auxiliary array, but you can count the number of exceptions e and of elements n in the original range, you can simply generate a random number r=rand(0 ... n-e), and then find the valid element with a counter that doesn't tick on exceptions, and stops when it's equal to r.

Categories : Algorithm

How to specify upper and lower limits when using numpy.random.normal
It sounds like you want a truncated normal distribution. Using scipy, you could use scipy.stats.truncnorm to generate random variates from such a distribution: import matplotlib.pyplot as plt import scipy.stats as stats lower, upper = 3.5, 6 mu, sigma = 5, 0.7 X = stats.truncnorm( (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma) N = stats.norm(loc=mu, scale=sigma) fig, ax = plt.subplots(2, sharex=True) ax[0].hist(X.rvs(10000), normed=True) ax[1].hist(N.rvs(10000), normed=True) plt.show() The top figure shows the truncated normal distribution, the lower figure shows the normal distribution with the same mean mu and standard deviation sigma.

Categories : Python

SPSS: generating random data on a normal distribution
You are using the old form of the normal RNG. In that function, the parameter is sigma, not the mean. Use RV.NORMAL(mean, std deviation). The RV.xxx notation can be used for all the random number generators, including RV.UNIFORM(min, max).

Categories : Misc

Random() not generating new random numbers
You haven't shown your RandomizePosition() method, but it is likely that you are calling randomise with the same time seed in quick succession, i.e. creating the Random object inside your RandomizePosition() method. To stop this happening create the Random object outside your RandomizePosition() method. Update: you have now shown the code for RandomizePosition() and that is indeed the problem. As mentioned by @dlev, the reason you see the expected behavior when you step through the code is that you are causing enough time to elapse for your newly created Random() object to use a new seed (since by default it is based on the current time) .

Categories : C#

How to generate a random number from 1 to 100 only once?
check out this for more detail class NonRepeatedPRNG { private final Random rnd = new Random(); private final Set<Integer> set = new HashSet<>(); public int nextInt() { for (;;) { final int r = rnd.nextInt(); if (set.add(r)) return r; } } }

Categories : Actionscript

PHP generate random usernames
Place the random number generator and nickname building variable at the start of your loop. Also increase the range of numbers that rand is allowed to return, as it will always return 2 at the moment $usernames = array(); do { // inside generate random number, // build nickname, // query to see if its taken, // and if NOT taken, add to the usernames array } while(count($usernames) < 3);

Categories : PHP

Generate random names in sql
Store the 5 random names for male in one table and the 5 random names for female in another table. Select a random integer between 1 and 5 and cross reference to male or female table using an inner join.

Categories : SQL

Generate a random DB insert with PHP
This takes multiple statements to do one row... and I may have misunderstood your requirements, but here goes: EDIT: Modified to be one statement and actually work with RAND() INSERT INTO matrix SELECT NULL, 1, -- NO idea what round_id should be... IF( 0 in (one8, two8), 8, (SELECT element_id FROM matrix_elements ORDER BY RAND() LIMIT 1)), IF( 1 in (one8, two8), 8, (SELECT element_id FROM matrix_elements ORDER BY RAND() LIMIT 1)), IF( 2 in (one8, two8), 8, (SELECT element_id FROM matrix_elements ORDER BY RAND() LIMIT 1)), IF( 3 in (one8, two8), 8, (SELECT element_id FROM matrix_elements ORDER BY RAND() LIMIT 1)), IF( 4 in (one8, two8), 8, (SELECT element_i

Categories : PHP

generate a random number between 1 and 10 in c
You need a different seed at every execution. You can start to call at the beginning of your program: srand(time(NULL)); Note that % 10 yields a result from 0 to 9 and not from 1 to 10: just add 1 to your % expression to get 1 to 10.

Categories : C

Generate random uint
The simplest approach would probably be to use two calls: one for 30 bits and one for the final two. An earlier version of this answer assumed that Random.Next() had an inclusive upper bound of int.MaxValue, but it turns out it's exclusive - so we can only get 30 uniform bits. uint thirtyBits = (uint) random.Next(1 << 30); uint twoBits = (uint) random.Next(1 << 2); uint fullRange = (thirtyBits << 2) | twoBits; (You could take it in two 16-bit values of course, as an alternative... or various options in-between.) Alternatively, you could use NextBytes to fill a 4-byte array, then use BitConverter.ToUInt32.

Categories : C#

How to generate a Random number?
This is how you generate a random number: Random r = new Random(); int random = r.nextInt(100); // returns a value between 0 (incl) and 100 (excl) Random r = new Random(); int random = r.nextInt(100) + 20; // returns a value between 20 (incl) and 120 (excl) Concerning your issue that the numbers should be unique, you could probably save each generated number somehow. Then, when drawing a new Random number check the saved numbers if the new random number has already been generated. If so, redraw. Java Random doc: http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

Categories : Java

Trying to Generate a Random password
$alphabet=$NULL;For ($a=65;$a –le 90;$a++) {$alphabet+=,[char][byte]$a } GET-Temppassword –length 10 –sourcedata $alphabet New-ADUser $cn -SamAccountName $sAMAccountName -GivenName $givenName -Surname $sn -DisplayName $displayName -UserPrincipalName $userPrincipalName -accountPassword (ConvertTo-SecureString -AsPlainText $alphabet -Force) -PasswordNeverExpires $true -Path "OU=Service,OU=Accounts,DC=rjfdev,DC=com" You aren't capturing the value returned from Get-Temppassword. You're passing $alphabet as the new password for the user account. Try this (untested): $alphabet=$NULL;For ($a=65;$a –le 90;$a++) {$alphabet+=,[char][byte]$a } $TempPassword = GET-Temppassword –length 10 –sourcedata $alphabet New-ADUser $cn -SamAccountName $sAMAccountName -GivenName $givenName -Sur

Categories : Powershell

vb.net generate random number and string
The first problem to solve is the random number generator. You should use only one instance and not multiple instances that gives back the same sequence if called in short time distance. Then it is difficult to say what 'something' means in your requirements, but supposing you are fine with rougly 70% numbers and 30% a mix of numbers and strings then you call the random generator to decide for a sequence of only numbers or a mixed one. Based on the output of the random selection of the sequence build from the appropriate string ' A global unique random generator' Dim rng As Random = New Random Sub Main Console.WriteLine(rand()) Console.WriteLine(rand()) Console.WriteLine(rand()) Console.WriteLine(rand()) End Sub Public Function rand() As String Dim sb As New StringBu

Categories : Vb.Net

PHP generate a random minus or plus percentage of a given value
A bit of basic mathematics $number = 1000; $below = -20; $above = 20; $random = mt_rand( (integer) $number - ($number * (abs($below) / 100)), (integer) $number + ($number * ($above / 100)) );

Categories : PHP

Can you use 'rand' to generate random operators?
well you can put operators in an array and then call array_rand to retrive it $ops = array('+','-','*','/'); $rand_key = array_rand($ops); $operator =- $ops[$rand_key];

Categories : PHP

Generate random BLOB in MySQL
I happened to require something similar lately. I therefore created a UDF for generating random BLOBs. You can find it on my github.com account: https://github.com/adrpar/mysql_udf_randomBlob After compilation using cmake and following the post compilation procedures as described in the README file you can use the UDF like this: SELECT randomBlob( sizeOfBLOBInBytes); e.g. for a 128 byte BLOB: SELECT randomBlob( 128 ); or combine it with your INSERT statement.

Categories : Mysql



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.