Menu
  • HOME
  • TAGS

Generate random binary sequence with a specific ratio

arrays,matlab,random

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...

How to uninitialize the entropy of /dev/urandom in C?

c,random,syscall,libc

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...

How to change random element heights

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 -...

How to make sure to draw two different random cards [closed]

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....

jQuery tooltip random appear

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());...

Print a variable selected by a random number

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) ...

spawn at random position Android

java,android,random,spawn

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.

How do I produce quality random numbers without maintaining internal state?

random

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...

Generate Two Arrays of Non-Duplicate Numbers

c#,arrays,random

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...

Sparse random matrix in Python with different range than [0,1]

python,random,scipy,sparse-matrix

Looks like the feature that you want was added about two months ago and will be available in scipy 0.16: https://github.com/scipy/scipy/blob/77af8f44bef43a67cb14c247bc230282022ed0c2/scipy/sparse/construct.py#L671 You will be able to call sparse.random(10, 10, 0.1, random_state=RandomState(1), data_fvs=func) where func "should take a single argument specifying the length of the ndarray that it will return. The...

How can I get full-ranged random float values?

java,random,floating-point

I would suggest generating a bound double and then converting to float: return Double.valueOf(random.nextDouble(Float.MIN_VALUE, Float.MAX_VALUE)).floatValue(); The nextDouble method has been replaced in Java 8 with a method to produce a stream of doubles. So in Java 8 you would use the following equivalent: DoubleStream randomDoubles = new Random().doubles(Float.MIN_VALUE, Float.MAX_VALUE); Double.valueOf(randomDoubles.findAny().getAsDouble()).floatValue();...

Batch Random Pinging(Trying to determine if a ping is successful)

batch-file,random,ip,ping

@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...

time complexity of randomized array insertion

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....

Crossplatform reproducible number generator

c++,random,c++98,boost-random

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,...

Creating random character unique URLS [closed]

php,random,unique

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...

Android :: How do I randomize my quiz questions?

java,android,random

You can fetch the random questions by running this query: db.rawQuery("SELECT * FROM YOUR_TABLE ORDER BY RANDOM() LIMIT 5", null);...

Exception (integer overflow) when initializing 64-bit Mersenne Twister

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!...

How to print a 2D array with random numbers

java,arrays,random

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...

Displaying random questions by looping through a dictionary

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....

From randomly to not randomly selecting columns

r,random

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....

How do you create a button that will display a random result from an array in javascript?

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...

Linear congruential generator in C++

c++,random,generator

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...

How to take same random sample from dataset every time

r,random,random-seed

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. ...

how to return a number with 2 decimal places all the time from a function

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))...

random.randint not generating random values

python,python-2.7,random

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...

Corona sdk random text

text,random,sdk,corona

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 =...

Maintain random seed for duration of session

php,random,random-seed

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']))...

How do I loop a piece of code in my main activity?

java,android,loops,random

Random rand = new Random(); Handler handler = new Handler() Runnable r=new Runnable() { public void run() { int value = rand.nextInt(10); handler.postDelayed(this, 500); } }; handler.postDelayed(r, 500); ...

How to get random item from array only from the specified keys (e.g x key first)

php,arrays,random

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) ...

Array of random numbers with sum in given range?

c,algorithm,random

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...

Why do the random number crashes my Android app? [closed]

java,android,random

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 ...

Haskell - generate and use the same random list

haskell,random

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] ->...

Selecting only a small amount of trials in a possibly huge condition file in a pseudo-randomized way

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...

Corona sdk not view random text

text,random,lua,corona

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...

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random

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...

Generate random pairs of numbers, without duplicates

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...

multiple random images in let it snow plug-in

javascript,image,random

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...

Swap dynamic amount of lines in text file

c#,random

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...

HTML - How to generate a random number in an img=src address inside a div

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...

JMeter 2.10 Random Variable that gets data from string

variables,random,jmeter

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...

How to produce multiple output files with a single input file using the command 'np.random.normal'?

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 =...

How to make n-D array into a string in ruby? [closed]

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...

Is there an error in Python 3's random.SystemRandom.randint, or am I using in incorrectly?

python,random

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...

Giving objects unique ids onStart

c#,random,unity3d

Unity already provide an unique id for every object instance, have a look at GetInstanceID.

Initializing classes in constructor causes segfault

c++,c++11,random

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...

Randomize a each loop

jquery,random

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 =...

Sequence contains no elements

c#,linq,random

@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...

Generate a random array ignoring a selected value

python,arrays,random

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) ...

Make a random string in batch

batch-file,random

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....

How to make a random function in fortran to generate the same random distribution into array?

random,fortran,fortran90

In modern Fortran, an initialization of variables such as real(real64) :: sum_val = 0 means that sum_val is a variable with the SAVE attribute (which is similar to static in C), which is initialized only once when the program starts. It is equivalent to real(real64), save :: sum_val = 0...

SAT-Solving: DPLL vs.?

random,brute-force,stochastic,sat-solvers,sat

State-of-art sat solver currently uses CDCL(Conflict Drive Clause Learning) based on the DPLL.

Cannot understand why random number algorithms give different results

r,random

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...

random.choice gives different results on Python 2 and 3

python,random,mocking

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...

How to populate a single tournament elimination randomly in PHP without repeat?

php,arrays,random,tournament

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>"; ?> ...

Random number generator problems

java,random

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);...

Default_random_engine passed into a function gives repeatable results

c++,c++11,random,shuffle

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....

Output random element from struct array

c,arrays,random,struct,arduino

You are overflowing memory buffers test and question. Their length should be 8 chars not 7 (space for 0 terminating string). Try: struct questionStructure { char question[8]; int answer; }; and char test[8];...

Python: Non repeating random values from list [duplicate]

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' ...

Python Get Random Sample of List of Tuples

python,list,random

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) ...

pick a random records from a datatable

c#,random,datatable

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;...

Python 3 random.randint() only returning 1's and 2's

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...

Sample a random number following a distribution between two values

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...

Using rand() to get a number but that number can't be the number that was last generated

c++,random,std

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()...

Random function keeps on getting same result [duplicate]

c++,random,dev-c++

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

Randomly select Elements of 4D matrix in Matlab

matlab,matrix,random,4d

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...

How to fill array with random values 1-110

java,arrays,for-loop,random

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...

Random password generate in shell script with one special character

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...

Python random use both state and seed?

python,random,random-seed

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...

How to access the properties of a random object in an array?

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...

How to generate random numbers in a data.frame with range

r,random,data.frame,seq

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...

random between to php function

php,random

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)])?> ...

How to obtain a random string from a list

python,list,random

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...

I made a for loop to swap two indiv char variables in a string

java,string,random,char,swap

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...

Having problems with python's random.shuffle

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...

How to select a specific number of random elements from a set?

python,python-3.x,random

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? : "))...

Swift If program

swift,if-statement,random

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)....

How to return random dictionary

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...

Multiple random choices with different outcomes

python,python-3.x,random

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:...

What is the significance of the number, 32767? [duplicate]

php,random

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....

Random text with numbered variables

python,random

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(" ") ...

Java random shuffle list with two elements using Collections.shuffle

java,random,collections

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 +=...

Generate n random bytes based on m-byte seed in Java

java,random,random-seed

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 -...

Generate random integer without an upper bound

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

VB LINQ - Take one random row from each group

vb.net,linq,random

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...

How to use numpy.random.choice in a list of tuples?

python,numpy,random

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...

bash - Selecting random object from an array

arrays,bash,random

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...

Can std::uniform_real_distribution(0,1) return a value greater than 0.99999999999999994?

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...

Random string generator PHP [duplicate]

php,random

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...

FatalErrorException: Call to a member function count() on a non-object

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...

Lengths of cycles in random sequence

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,...

Random flling the array - perl

arrays,perl,random

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...

Generate random ROWID

oracle,random,plsql,rowid

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...

How to Randomly Choose Button Text in Java?

java,android,button,random

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...

How to pick random images so the newer ones are more likely to be selected in Linux

bash,random

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...

How to check bool inside of dictionary

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") }...