It's not the program, it's the choice of numbers. prev is in the beginning equal to zero, so the first number becomes C. Then, prev is equal to C, which makes prev A*C + C. However, A*C is so small, that when adding it as a floating point to the...
You could try using $random = substr(str_shuffle(MD5(microtime())), 0, 8);, which will output the same amount of random characters as you have in your example. I actually prefer this method over most as it doesn't require you to put in the expected characters and even more importantly, it can be done...
random,psychopy,experimental-design
Adding a pretty simple code component in builder will do this for you. I'm a bit confused about the conditions, but you'll probably get the general idea. Let's assume that you have your 72 "fixed" conditions in a conditions file and a loop with a routine that runs for each...
I tied your code inside simple main method and works ok. Try it yourself: public static void main(String[] args) { Main main = new Main(); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { list.add(main.prizegenerator()); } Collections.sort(list); for (Integer integer : list) { System.out.println(integer);...
You can fetch the random questions by running this query: db.rawQuery("SELECT * FROM YOUR_TABLE ORDER BY RANDOM() LIMIT 5", null);...
I think you may have some confusion about how sample() works. First, let's examine sample()'s behavior with respect to this simple vector: 1:5; ## [1] 1 2 3 4 5 When you pass a multi-element vector to sample() it basically just randomizes the order. This means you'll get a different...
This random selects jpg files with files created or modified in the last hour being selected three times as likely and files created or modified in the last six hours selected twice as likely as older files: { find . -name '*.jpg' -mmin -60 find . -name '*.jpg' -mmin -360...
random,brute-force,stochastic,sat-solvers,sat
State-of-art sat solver currently uses CDCL(Conflict Drive Clause Learning) based on the DPLL.
It is because of your initialization order class RandomCharSource { public: explicit RandomCharSource() : _re{_rd()}, _dist{0, 255} {}; inline char get_next_char() { return _dist(_re); }; private: std::mt19937 _re; std::uniform_int_distribution<int> _dist; std::random_device _rd; }; You need to have _rd before _re. The members are initialized in the order they are declared...
javascript,jquery,html,css,random
Edit As to why your code isn't working: You can't apply randomimage to the source of the image in plain HTML. You have to do that using Javascript. To do that you have to select the element you want to manipulate and modify the src attribute through Javascript. Since you...
One quick way to shuffle items is to sort by a "random" value - Guid.NewGuid() usually works well enough. Then just pull the first row from each group: Dim query = _ From rows As DataRow In surveyAnswerKeys.Rows _ Order By Guid.NewGuid() _ Group By questionSortKey = rows(answerGroup) _ Into...
javascript,jquery,random,height
Simply check if there are more li elements in the list than the current value of i and if there are, update the corresponding element instead of creating a new one. var i=0; while( i++ < 100) { if ($('#container > li').length > i - 1) $('#container > li').eq(i -...
jquery,random,tooltip,delay,show
You have not included jquery-ui.css. Just add it in document and everything will be fine!! You can get it from here UPDATE If you need it in the div the along with html add title attribute too and as below remove the title attribute from other elements $('#show').html($('#' + $(this).attr('aria-describedby')).children().html());...
arrays,swift,dictionary,random
Your check should be done by using dictionary subscript method with String parameter because your dictionary keys are Strings. Also since your sure that darePersons exits in your dictionary and its value is Bool you can force unwrap both of them if dare.randomDare()["darePerson"]! as! Bool{ println("dare person is true") }...
If you want to fill the array with random values, you need to generate random values in a loop, and then write them to the array in that loop. So far you are only generating one value (and putting it in an invalid location). Additionally, since arrays are 0-based, your...
If I am interpreting what you want correctly, for each unique 3D position in this matrix of 7 x 4 x 24, you want to be sure that we randomly sample from one out of the 10 stacks that share the same 3D spatial position. What I would recommend you...
python,numpy,random,random-seed
When I don't want an upper bound I'll often use sys.maxint for the upper bound as an approximation
You seem to be confused between defining a function and calling it and how parameters work. def blackjack(A,B): print "Welcome to Blackjack!" print "Your cards are",name[A-1],"&",name[B-1] total = value[A-1] + value[B-1] print "Your card total is",total In your function A and B are place holders. They will be replaced by...
In Java arrays are indexed starting from 0. So the index of the 1st element will be 0 and index of the Nth element will be N-1. So since you need to keep 110 bits in an array the arrays will be indexed from 0 - 109. As an work...
@Oleg is right, but here's why it's the problem. Where scans through the list looking for elements that match the given criteria. In this case the criteria changes for each element. If you made the problem smaller, say an array of 5 elements: List<Int32> (5 items) 1 2 3 4...
You need to specify what is the desired distribution of the random numbers. If there are no further requirements, I would suggest one of the following: (1) pick random number a[1] in interval 0 .. k pick random number a[2] in interval 0 .. k-a[1] pick random number a[3] in...
As /dev/random and urandom are vital for security functions, allowing to tamper them would contradict their purpose. But you can add your own driver, or just replace calls to them with dummies (or use named pipes from a dummy for testing) instead. Note: do not replace the driver on a...
Your Permutation constructor takes the engine in by value. So, in this loop: for (int i = 0; i < n; i++) Permutation test(length, generator); You are passing a copy of the same engine, in the same state, over and over. So you are of course getting the same results....
Simply use set.seed just before you create index: > set.seed(1) > index <- sample(7009728, 50000) > head(index) [1] 1861144 2608487 4015546 6366287 1413735 6297463 It sets random number generator seed and ensure consistent results. ...
ios,swift,dictionary,random,xcode6
So without all of your code I can only give you an educated guess as to a good way of handing your infinite loop situation with your current code. An easy way to prevent an infinite loop here is to verify you still have remaining questions you want to ask....
This should work for you: Just shuffle() your array and then array_chunk() it into groups of 2, e.g. <?php $players = ["A","B","C","D","E","F","G","H","I","J","L","M","N","O","P","Q"]; shuffle($players); $players = array_chunk($players, 2); foreach($players as $match => $player) echo "Match " . ($match+1) . ": " . $player[0] . "x" . $player[1] . "<br>"; ?> ...
bash,shell,unix,random,passwords
#! /bin/bash chars='@#$%&_+=' { </dev/urandom LC_ALL=C grep -ao '[A-Za-z0-9]' \ | head -n$((RANDOM % 8 + 9)) echo ${chars:$((RANDOM % ${#chars})):1} # Random special char. } \ | shuf \ | tr -d '\n' LC_ALL=C prevents characters like ř from appearing. grep -o outputs just the matching substring, i.e. a...
In Swift you cannot read a value before it's set, which you're doing here: if Int(randomNum) == guessInt If you change your declaration from this: var guessInt:Int to this: var guessInt = 6 then your code will work as expected (assuming you want the user's guess to be 6)....
javascript,random,numbers,type-conversion
Lose the + signs and you should be fine: function randomGen(){ return (Math.random()*11).toFixed(2) } // console.log(randomGen()) // some times i would get 10.5 when i want 10.50 var num1 = randomGen(); // i want 10.50, for example not 10.5 var num2 = randomGen(); console.log(num1, " ", num2) console.log((num1 + num2).toFixed(2))...
arrays,algorithm,random,insert,time-complexity
First consider the inner loop. When do we expect to have our first success (find an open position) when there are i values already in the array? For this we use the geometric distribution: Pr(X = k) = (1-p)^{k-1} p Where p is the probability of success for an attempt....
javascript,arrays,random,javascript-objects
From the Mozilla Javascript Reference on what Array.prototype.splice() returns: an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. This means that you must be taking the first element ([0]) of...
javascript,arrays,button,random,onclick
function postmessage() { var firstnames = ["John", "Jacob", "Eric", "Conroy", "Vincent", "Laurence", "Jack", "Harry", "Richard", "Michael", "Kevin", "Daniel", "Cody", "Brody", "Chase", "Cash", "Norman", "Trevor", "Todd", "Ellis", "Quentin", "Zachary", "Bruce", "Sam", "Horace", "George", "Tom", "Tim", "Wallace", "Walter", "Alex", "Alan", "Sean", "Seamus", "Dudley", "Duke", "Damian", "Nash", "Horton", "Robert", "Mitchell", ]; var...
Your code looks good, the only possible failure point is your erroridcox variable not being set. Add a Debug Sampler and View Results Tree listener to double-check erroridcox and rnd_erroridcoxvariable values. Also you can put debug(); function at the beginning of your script and look into STDOUT to observe its...
You can sample your list regardless of if the elements are hashable or not: data = create_dataset() # List of data to be sampled n_samples = 100000 samples = random.sample(data,n_samples) ...
To fully understand the display.newText api of Corona SDK you can view it here: https://docs.coronalabs.com/api/library/display/newText.html For the Tap event you can view it here: https://docs.coronalabs.com/api/event/tap/index.html But I have fixed your code for you. But I really can't understand why you have "Impact" there. but here is a working code you...
Could you try something like, dt2 = dt.Clone(); dt.AsEnumerable().Select(x => x["IC_NUMBER"].ToString()).Distinct().ToList().ForEach(x => { DataRow[] dr = dt.Select("IC_NUMBER = '" + x + "'"); dt2.ImportRow(dr[0]); dr.ToList().ForEach(y => dt.Rows.Remove(y)); dt.AcceptChanges(); }); EDIT: int totalWinners = 10; Random rnd = new Random(); dt2 = dt.Clone(); for (int i = 1; i <= totalWinners;...
Does something like this rand_obj() { shift $(( $(rand 1 $#) - 1 )); echo "$1" } do what you want? The above has problems with arguments that end with newlines. Command Substitution always removes trailing newlines. To handle that scenario you'd need to stick a dummy character/etc. at the...
arrays,swift,dictionary,random
Your list of dictionaries is not declared correctly. Instead of being : var theDare: [String: String, String: Bool;] It should be : var theDare: [[String: AnyObject]] as you always have String keys but sometimes have String values and sometimes Bool values. Your randomDare() function return needs to be changed accordingly...
Make sure you are localizing your variables properly. You need to declare "mmDis" outside your function, and then do not localize it inside the function. Something like this local mmDis* -- this will ensure code from here on out all use the SAME "mmDis" function randomText(event) display.remove(mmDis) local a =...
Do this instead: source1 = "First text" source2 = "Second text" randomtext = random.choice([source1, source2]) liste_source = randomtext.rstrip('\n\r').split(" ") Or even simpler: sources = ["first text", "second text"] randomtext = random.choice(sources) liste_source = randomtext.rstrip('\n\r').split(" ") ...
ruby-on-rails,arrays,ruby,string,random
The algorithm is straightforward once you notice that the first level and the others are formatted with different rules. So for clarity I had to use two different functions. Other than that, the algorithm is pretty self-explanatory. But even so I've commented it to be as clear as possible. data...
No, setting either the seed or the state is sufficient: import random # set seed and get state random.seed(0) orig_state = random.getstate() print random.random() # 0.8444218515250481 # change the RNG seed random.seed(1) print random.random() # 0.13436424411240122 # setting the seed back to 0 resets the RNG back to the original...
matlab,random,distribution,gaussian,sampling
Might use Irwin-Hall from https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution Basically, min(IH(n)) = 0 max(IH(n)) = n peak(IH(n)) = n/2 Scaling to your [1.9...2.1] range v = 1.9 + ((2.1-1.9)/n) * IH(n) It is bounded, very easy to sample, and at large n it is pretty much gaussian. You could vary n to get narrow...
java,arrays,random,combinations
Here is some code which creates 10 random pairs from your input a[] and b[] arrays, and stores them into an HashSet which you can use later as you see fit. The HashSet will automatically remove duplicate pairs. public class Pair { int x; int y; public Pair(int x, int...
According to https://docs.python.org/2/library/random.html, the RNG was changed in Python 2.4 and may use operating system resources. Based on this and the other answer to this question, it's not reasonable to expect Random to give the same result on two different versions of Python, two different operating systems, or even two...
You can workaround your issue by always reinitializing the srand with the last random number generated. You "mix up" the seeds but you still have a reproducable way to generate random numbers. Here is some code : function getNextRandomNumber() { $mySeed = 0; // a default seed value if (isset($_SESSION['seed']))...
You're only drawing that circle for the instant myThread.timer is greater than 100. What you need to do is add it to an ArrayList, or whatever data structure you want, and then constantly loop over that ArrayList and draw all the circles.
You can use array_slice to first take a part of the array before you take random items from it $part = array_slice($arr, 1, 7); // outputs array(2,3,4,5,6,7,8) ...
python,loops,random,while-loop
There are three different options you have to choose from here, I will explain each one: Option 1 - break while first_draw == second_draw: first_draw = random.choice(card_values) + random.choice(card_classes) second_draw = random.choice(card_values) + random.choice(card_classes) break break will end the innermost loop. In this case, the loop will only run once....
c#,arrays,algorithm,random,cycle
What you are doing is generating a random permutation of size count. Then you check the properties of the permutation. If your random number generator is good, then you should observe the statistics of random permutations. The average number of cycles of length k is 1/k, for k<count. On average,...
According to the function's doc, a : 1-D array-like or int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n) So following that lista_elegir[np.random.choice(len(lista_elegir),1,p=probabilit)] should do what you want. (p= added as per comment; can...
You should use the random header. #include <random> std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for...
The while true loop is definitely not good practise, I'd suggest doing something like this. But you should make it in the same structure as Michael's answer above like this: void reroll(int lastNumber, int amountOfNumbers) { int newRand = std::rand() % (amountOfNumbers); while (newRand == lastNumber) { newRand = std::rand()...
The line: randgend = random.choice(gend) makes randgend a single random choice from [ 'male', 'female' ], you're basically writing: randgend = 'male' # or female, whichever gets picked first If you want it to be a function that returns a different random choice each time, you need: randgend = lambda:...
The plugin author loads a single custom image into a hidden element with if (settings.image != false) { $("<img src='"+settings.image+"' style='display: none' id='lis_flake'>").prependTo("body") } and loads the snowflakes with this ctx.drawImage($("img#lis_flake").get(0) This solution hasn't been tested, but if you are willing to hack the plugin a bit, you could potentially...
The different numbers resulted in a piece of glm code we used. They use undetermined order of argument evaluation, which is fine for nearly random purposes, but not when you want deterministic numbers (obviously). So we corrected the code for our purposes and successfully use boost::mt19937 on Windows, Mac, Linux,...
python,variables,python-3.x,random,introspection
Don't assign numbers OR strings. Use a list. choices = ['Arkansas', 'Manchuria', 'Bengal', 'Baja California'] # etc. Then take a random.choice random_choice = random.choice(choices) ...
Function: function generateRandomString($length = 12) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } Then call it: $randomString = generateRandomString(); Slightly adapted from Stephen Watkins' solution here...
python,matrix,random,permutation,shuffle
You need to make a copy of vec before you shuffle it: import random vec=[1,2,3,4,5] for i in range(5): vec.append(10) Matpreferences=[] for i in range(10): v = vec[:] random.shuffle(v) Matpreferences.append(v) Explanation From your code: a=vec Matpreferences.append(a) Here, a points at the same data that vec points at. Consequently, when a...
You can try the following: #get the combos outside the loop combos<-combn(length(mydata),2) R<-ncol(combos) delta<-numeric(R) #in the loop, replace the first line a <- mydata[,combos[,i]] #the rest should be ok There are some improvements you could make in the code but they are not relevant in what you are asking....
On Windows there is a secure random generator, CryptGenRandom, which will do all that for you. Most languages have a SecureRandom class, dev/random or similar to access it. Other OS's will have similar arrangements. Basically they import entropy from within the system to seed their own generator. For a more...
I'm assuming you meant "ten non-negative integers less than 60". With possibility of repeats: my @rands = map { int(rand(60)) } 1..10; For example, $ perl -E'say join ",", map { int(rand(60)) } 1..10;' 0,28,6,49,26,19,56,32,56,16 <-- 56 is repeated $ perl -E'say join ",", map { int(rand(60)) } 1..10;' 15,57,50,16,51,58,46,7,17,53...
The problem isn't with shuffle - it's with Random with small seeds. Here's a program demonstrating that: import java.util.Random; public class Test { public static void main(String[] args) { int total = 0; for (int seed = 0; seed < 4000; seed++) { Random rng = new Random(seed); total +=...
the problem is here is this line: factLabel.setText(randomNumber);. You want to set the String representing your randmNumber. Use factLabel.setText(String.valueOf(randomNumber)); the version of setText you are using looks up for a String with id the int your provided. If this can't be found, it throws that exception ...
c++,c++11,random,double,double-precision
The maximum value dist(engine) in your code can return is std::nextafter(1, 0). Assuming IEEE-754 binary64 format for double, this number is 0.99999999999999988897769753748434595763683319091796875 If your compiler rounds floating point literals to the nearest representable value, then this is also the value you actually get when you write 0.99999999999999994 in code (the...
For the record, a (rather slow) solution as discussed above: public byte[] rand(byte[] seed, int n) { try { byte[] data = null; ByteArrayOutputStream ret = new ByteArrayOutputStream(n); while (ret.size() < n) { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(seed); if (data != null) md.update(data); data = md.digest(); ret.write(data, 0, Math.min(n -...
Rather than generate your own random value, which may or may not point to an actual object (but probably not), you could get the real ROWID of a random row from a real table. If you don't have your own data you could use any table you can see; look...
php,database,random,laravel-5,unique
The error you're seeing is telling you that you're trying to call a method on a value which is not an object. Most likely in your code you're returning null as the where in your query didn't return anything results. You can always see what you're returning in Laravel queries...
function,python-3.x,random,dice
this line if die == 'a' or 'A': will always return True. That is because the way the items are grouped, it is the same as if (die == 'a') or ('A'): and 'A' (along with any string except "") is always True. Try changing all those lines to if...
Python has a very simple method for this: random.choice import random class_list = ['Noah','Simone','Ji Ho','Thanh','Nathanial','Soo','Mickel','Tuan','Thuy Linh'] print(random.choice(class_list)) Regarding why your answer isn't working: print (ClassList[{}].format(Random1)) .format is for interpolating a value into a string - for example"{}".format(5). Obviously this is something different than what you're doing. If you wish to...
If you also have mixed (numeric + non-numeric) template names, Create an array with all template names like, $templates = ['module_sidebar_1','module_sidebar_2','module_sidebar_non_numeric']; and call random template file by <?php get_template_part($templates[array_rand($templates)])?> ...
As you´re using a timestamp as srand seed: If both runTours are in the same second, what do you think will happen with your code? ... srand is supposed to be called exactly one time, not one time per function call of runTour
To have the same result, you need to put byrow=FALSE instead of byrow=TRUE for the second option. the first way you're computing the random matrix, it computes rbinom(things,1,probs) length(probs) times, obtaining each time a things long vector. To obtain the exact same matrix with the second way, which computes a...
To assign a variable a value, use the SET command: SET subkey1=%random%%random%%random%%random%%random%%random% SET subkey1=%subkey1:0=a% SET subkey1=%subkey1:1=b% SET subkey1=%subkey1:2=c% . . . ECHO %subkey1% And, of course, beware that %random% should never, ever be used as a source for cryptographic purposes....
Hope this helps - first_value = random.randint(0, 10) randarray = [i for i in random.sample(range(0, 10), 10) if i != first_value] randarray.insert(0, first_value) ...
random.SystemRandom is an class. It needs to be instantiated; In [5]: foo = random.SystemRandom() In [6]: foo.randint(0, 10) Out[6]: 0 The complete docstring gives a hint; In [12]: random.SystemRandom.randint? Signature: random.SystemRandom.randint(self, a, b) Docstring: Return random integer in range [a, b], including both end points. File: /usr/local/lib/python3.4/random.py Type: function The...
Each time your code calls inputFiles.Count(), you're effectively re-reading the entire file, since File.ReadLines is using deferred execution, and you aren't materializing it. Since you need the entire list in-memory anyway, use File.ReadAllLines instead, which returns a string[] and has a Length property, which is an O(1) operation instead of...
Here's an example of how you can shuffle the result array of jQuery (using Fisher-Yates-Knuth shuffling) before iterating over it using .each(). Btw, you can also use this same technique to shuffle elements on the page as well. (function($) { $.fn.shuffle = function() { // credits: http://bost.ocks.org/mike/shuffle/ var m =...
Use the random.sample() function to pick n random elements without repetition: sampled = random.sample(choices, best_of) for choice in sampled: print(choice) If all you need is an integer from the user, don't use eval(); stick to using int() instead: best_of = int(input("How many maps do you want to choose? : "))...
vb.net,visual-studio-2010,random,numbers,64bit
Signed Integer data types only go to 32 bits Unsigned Integer data types only got to 32 bits For 64 bits of data you should use LONG or ULONG The reason the integer OVERFLOWS is because the data type is not large enough to hold your 64 bits of data!...
python,string,python-2.7,random
you can use random.sample() random.sample(population, k) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. In [13]: "+".join(random.sample(sentences,3)) Out[13]: 'a+b+c' ...
Here is a simple example (@luqui mentioned) you should be able to generalize to your need: module Main where import Control.Monad (replicateM) import System.Random (randomRIO) main :: IO () main = do randomList <- randomInts 10 (1,6) print randomList let s = myFunUsingRandomList randomList print s myFunUsingRandomList :: [Int] ->...
32767 + 1 is a power of 2 Binary representation of numbers uses powers of 2. So, in an 4-bit structure, 0101 is 2^0 x 1, 2^1 x 0, 2^2 x 1, and 2^3 x 0 which is 5. The MSB is used for sign and unsigned integers....
python,loops,numpy,random,normal-distribution
There are two minor issues - the first relates to how to select the name of the files (which can be solved using pythons support for string concatenation), the second relates to np.random.normal - which only allows a size parameter when loc is a scalar. data = pl.loadtxt("20100101.txt") density =...
Store the string values in an array of size 3. Generate a random number between 0 and 2. Keep that value in a variable and assign the string associated to that value to your button. Reduce your array by deleting the string you've already assigned. Then generate a random int...
The "bulky" way, leading to the most code (albeit readable), would be: Read all lines, close the file Find the blocks to randomize Randomize those blocks Write the result to a new file Move the new file over the old file Something like this: var linesInFile = File.ReadAllLines(); var newLines...
The ratio can be interpreted as deterministic (you want 500 ones and 500 zeros in each realization of 1000 values) or as probabilistic (a realization may have more ones than zeros, but the ratio holds over a very large number of realizations). Your code works for the probabilistic interpretation, so...
Unity already provide an unique id for every object instance, have a look at GetInstanceID.
@echo off setlocal enableextensions enabledelayedexpansion for /l %%a in (0) do ( set /a "A=!random! %% 255", ^ "B=!random! %% 255", ^ "C=!random! %% 255", ^ "D=!random! %% 255" ping -w 1000 -n 1 "!A!.!B!.!C!.!D!" | find "TTL=" > nul && ( >>"online.txt" echo !A!.!B!.!C!.!D! ) ) This creates and...
I think you would be looking for the following for (int x = 0; x < word.length(); x++) { if (x == i) { chararray[x] = word.charAt(j); } else if (x == j) { chararray[x] = word.charAt(i); } } Interchange the i and j values in the if and else...