vendredi 30 septembre 2016

Random ints with different likelihoods

I was wondering if there was a way to have a random number between A an b and where if a number meets a certain requirement it is more likely to appear than all the other numbers between A and B, for example: Lower numbers are more likely to appear so if A = 1 and B = 10 then 1 would be the likeliest and 10 would be the unlikeliest.

All help is appreciated :) (sorry for bad English/grammar/question)




Writing random numbers without repeating using localStorage

So I want to write a different random number between 0 and 5 to the of a page everytime I refresh, how can I prevent it for generating a number thats already been generated? I guess I need to use localStorage API for this but i can't wrap my head around it. Here's the code of the script I'm trying:

var random = Math.floor(Math.random() * 6);
var lastRandom = 0;
localStorage.setItem('random', random.toString());
if (localStorage.getItem('random') === lastRandom.toString()) {
    localStorage.setItem('random', lastRandom.toString()) 
}




Generating a random value, and inserting to the db in php

Alright so I am trying to generate a random value, using random_bytes, tell the user his unique ID, and then insert to the database.

I'm using isset so I tried doing $id = bin2hex(random_bytes(16)) but it generates another ID when the user clicks the Register button, meaning the value he saved is not the one that was inserted to the database.

Basically, a random identifier that is generated for him and he needs to save in order to log in (serves as the username).

Thanks!




Spawn items based on rarity

I am trying to spawn items in my small game based on rarity,

I have something like this

Item {
 int id;
 int rarity; // from 1 to 100, the higher the rare the item will be
}

Can someone point me the direction to how to spawn based on the rarity of the item.




Repeatable random number sequence in swift [duplicate]

This question already has an answer here:

Is it possible to create a repeatable random number sequence in swift?

Something like srand() and rand():

import Foundation

// With srand we start a sequence of random numbers.
// ... Each rand call returns a value in a predictable sequence.
print("Test")
srand(5)
for i in 0...3
{
    print(rand())
}

// Demonstrate the repeat sequence.
print("Test again")
srand(5)
for i in 0...3
{
    print(rand())
}

Which would output something like:

Test

84035

1412376245

1670799424

629750996

Test again

84035

1412376245

1670799424

629750996

Seems like only arc4random() is available and it does not appear to be repeatable.




Read a specific line in a file java [duplicate]

This question already has an answer here:

I am a beginner programmer and a I have trouble finding a simple way to read a line from a file.

There is a file in the second directory called "first". My code generates a random number, (ex. 9) and has to print that line of that file. The files won't ever exceed 100 lines. I would like to know how to print line number 9 from the file "first".

Remember that I have very little experience and that there are no stupid questions.




C# WPF Random ListBox - Remove object from one list box and add to another using a random

I am using a basic WPF application. In it I have a list of Persons with a few properties. When I run the application it populates a listbox with the Persons. I have a button to random an Persons based off of a selection(1-5). When this happens, I need to remove that Person/s and move him/her to another list box I have.

I get an error while in the first foreach loop. Not sure how to loop through the personListBox. Also need to move the person from personListBox1 to personListBox2.

I need the person removed from the 1st list so that when it loops again, it will not be there to be selected again. I plan on doing something with only the second list of persons. Thanks in advance guys.

Below is the random button I am trying this with.

private void randomButton_Click(object sender, RoutedEventArgs e)
    {
        if (this.numberComboBox.SelectedIndex != -1)
        {
            List<Person> personList = new List<Person>();                
            int number = Convert.ToInt16(this.numberComboBox.SelectedItem);

            // Add each person from the one list box to the other.
            foreach (Person P in this.personListBox.Items)
            {
                personList.Add(P);
            }

            // Loop the the selected number of times to remove and add from list to list.
            for (int i = 0; i < number; i++)
            {
                int randomValue = random.Next(personListBox.Items.Count);                    
                // Need to remove the person from personListBox1 here
                // Then move them to personListBox2
            }
        } 
        else
        {
            MessageBox.Show("Please select a number before trying to random.");
        }
    }




With Sound Arrays, how do I play random unique sounds?

So far, this code sounds out the words "This is a test" in random order, but the words can repeat more than once. myWordArray is a static Sound array set up in the program that reads splice points from the specific sound.

public void playRandomOrder(int totalWords, int pause) throws InterruptedException {
    Random random = new Random(); // Random number generator for array shuffle
    for (int i =0; i< numWords; i++) {
        int randomPosition = random.nextInt(totalWords); // how many words to sound out (4)
        Sound temp = myWordArray[i];
        myWordArray[i] = myWordArray[randomPosition];
        myWordArray[randomPosition] = temp;
        myWordArray[i].blockingPlay();
        Thread.sleep(pause); // 320 m.seconds, as listed in main method parameter
}
}

I want it to be so that the words can play randomly, but without a single word repeating. For example "This a test is" instead of "This is is test" Here is what I have so far for the unique random words...

public void playRandomUnique(int pause) throws InterruptedException {
    final Random random = new Random();
    List<Sound> list = Arrays.asList(myWordArray);
    Collections.sort(list, new Comparator<Sound>(){
        @Override
        public int compare(Sound o1, Sound o2){
            return random.nextInt() % 2 == 0 ? 1 : -1;
        }
    });
    list.toArray(myWordArray);
    for (Sound sound: myWordArray)
        sound.blockingPlay();
        Thread.sleep(pause);

}

This however, results in "Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!" and no sound plays out when I run it in main.




normrnd of MATLAB generating different values for the same setting

I do not know how to describe the problem so I titled it like that. If you have any better idea, please fix it. I apologize in advance.

My problem came up with when I was writing a code using normal random generator of MATLAB.

clear all; 
clc; 
close all;
rng(0,'twister');

sigma=50; 
mean(normrnd(10,sigma,20,1))

n=20;
mean(normrnd(10,sigma,n,1))

When I generate 20 normally-distributed numbers while controlling it by setting generator to Mersenne Twister and seed to 0, I can use that code that I provided above. I can write the sample size inside the normrnd function or I can define it out of function but when you run it and find the means of generated numbers for both ways, you will also release that they differ greatly. Such first mean is 43.2294 and the second mean is 7.1280. Does anyone have any idea about this situation?




How to make a True Random with equal chance in AS3?

I'm developing a rock-paper-scissor game player vs computer. There's nothing special except player playing 3 rounds per game.

I'm using this code to generate random number from 1 to 3

Math.floor(Math.random()*(1+3-1))+1

1 = Scissor, 2 = Paper, 3 = Rock

I'm not sure but this code favor on Number 2.

Meaning the computer generate Paper-Paper-Paper so the player notice it and taking the advantage and select scissor-scissor-scissor. I bet you will do it also.

How can I generate real randomness in AS3?




Purescript Halogen, side effect (random number)

In a PureScript Halogen project, I would like to set the state to a random number, but how do I extract the value? The normal

r <- randomInt 1 10

does not compile when it's inside the eval function.

module Main where

import Prelude
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Random (randomInt, RANDOM)
import Halogen as H
import Halogen.HTML.Events.Indexed as HE
import Halogen.HTML.Indexed as HH
import Halogen.Util (runHalogenAff, awaitBody)

type State = { n::Int }

initialState :: State
initialState = { n: 3}

data Query a = NewRandom a

ui :: forall e. H.Component { n :: Int } Query e
ui =
    H.component { render, eval }
    where
    render :: State -> H.ComponentHTML Query
    render state =
        HH.button
            [ HE.onClick $ HE.input_ NewRandom ]
            [ HH.text $ show state.n ]


    eval :: Query ~> H.ComponentDSL State Query e
    eval (NewRandom next) = do
        H.modify (\state -> state { n=12 } )

        --I'd like to set n to a random number
        --but I don't know how.
        --let r = randomInt 1 10
        --H.modify (\state -> state { n=r } )
        pure next

main :: Eff (H.HalogenEffects ()) Unit
main =
    runHalogenAff do
    body <- awaitBody
    H.runUI ui initialState body




Multiple Choice Quiz With Randomising Answer Positions PYTHON 3.5.2

I am creating a Que Card quiz in which a keyword from a text file is chosen at random, the program should then show the correct definition along with 2 other incorrect definitions that are in the text file as well. So far I have the keyword, the correct definition and the 2 incorrect definitions stored inside a list. Is there anyway that I can randomise the order of the items in the list and randomise their positions when the user is answering the question. I have tried to look this up but I can't find anything.

Example:

"Keyword is frog 1: Frogs are blue 2: Frogs are Green 3: Frogs are purple " But then the next time the keyword frog comes up they will be in different orders.

"Keyword is frog 1: Frogs are green 2: Frogs are blue 3: Frogs are purple "




Dealing with normal (Gaussian) distribution

I basically stucked on rather simple problem:

Toss N coins and discover, how many of them land heads

Solution performance must not depend on N, so we can't just call Math.random() < 0.5 N times. Obviously, there is Gaussian distribution to the rescue.

I used Box-Muller method for it:

function gaussian_random(mean, variance) {
  var s;
  var x;
  var y;
  do {
    x = Math.random() * 2.0 - 1.0;
    y = Math.random() * 2.0 - 1.0;
    s = Math.pow(x, 2) + Math.pow(y, 2);
  } while ( (s > 1) || (s == 0) );

  var gaussian = x * Math.sqrt(-2*Math.log(s)/s);
  return mean + gaussian * Math.sqrt(variance);
}

Math says, that mean of N coin tosses is N/2 and variance is N/4

Then, I made test, which tosses N coins M times, giving Minimum, Maximum, and Average number of heads.

I compared results of naive approach (Math.random() many times) and Gaussian Box-Muller approach.

There is typical output of tests:

Toss 1000 coins, 10000 times
Straight method: 
Elapsed time: 127.330 ms
Minimum: 434
Maximum: 558
Average: 500.0306
Box-Muller method: 
Elapsed time: 2.575 ms
Minimum: 438.0112461962819
Maximum: 562.9739632480057
Average: 499.96195358695064

Toss 10 coins, 10000 times
Straight method: 
Elapsed time: 2.100 ms
Minimum: 0
Maximum: 10
Average: 5.024
Box-Muller method: 
Elapsed time: 2.270 ms
Minimum: -1.1728354576573263
Maximum: 11.169478925333504
Average: 5.010078819562535

As we can see on N = 1000 it fits almost perfectly.

BUT, on N = 10 Box-Muller goes crazy: it allows such tests outcomes, where i can get (quite rarely, but it is possible) 11.17 heads from 10 coin tosses! :)

No doubt, i am doing something wrong. But what exactly?

There is source of test, and link to launch it




jeudi 29 septembre 2016

Is it possible to shuffle the values in an array in random order? [duplicate]

This question already has an answer here:

I have the following array in javascript.

    var numbers = [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8];

I'm trying to get these numbers in a random order in an array, the array has to have a size of 0-15 and has to contain these numbers. I have tried using different functions to generate random numbers between 1-8 and add them in the array but I cannot figure out how to have exactly two of each of these numbers.

I.E. the result has to be (in random order):

    var numbers = [5,4,2,1,3,6,5,4,2,1,3,6,7,8,7,8];

Is there a convenient way to do this in javascript?




How to print random string from a selection of user form inputs javascript/jquery

var textEntered = function() {
    var input = document.userNameForm.userInput.value;
    if(input) {
        document.getElementById("resultText").innerHTML += input + "<br>";
    }
}

This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).

I'm a beginner just so you know




Generating psuedo random lists with specific constraints in Python

I am relatively new to python and am trying to implement it (and psychopy) in a simple experiment that loads either target or distractor images in a new order every time it is run.

The experimenter puts constants into a GUI when it initiates that dictate specific constraints about the order of the list as follows (percentages and locations can change)

  • % distractors 90

  • % targets 10

  • min number of distractors between targets = 4

  • targetdirectory = (directory of where the target images are)

  • distractordirectory = (directory of where the distractor images are)

My goal would be to have something generate a list of the image names based on the directories that meet the criteria that the experimenter would input.

The only way I can think of doing this now is by having python generate a list of images from the two directories given the percentages, then randomize it, and finally loop to check the number between targets is more than 4.

Does anyone have any ways that I could simplify this?

Are there other random snippets of code I might be missing that would make this easier? Or that would make this approach easier?

Thank you!




SQL Select distinct values from one column Randomly

I have a table showing available dates for some staff with two fields - staffid and date with information that looks :`

staffid     date  
1           2016-01-01
1           2016-01-02
1           2016-01-03
2           2016-01-03
3           2016-01-01
3           2016-01-03

I need to generate a list of distinct available dates from this table, where the staff selected to each date is selected randomly. I know how to select rows based on one distinct field, (see for example the answer here, but this will always select the rows based on a given order in the table (so for example staff 1 for January 1, while I need selection to be random so sometimes 1 will be selected as the distinct row and sometimes staff 3 will be selected.

The result needs to be ordered by date.




vb6 legacy application freezing in Windows 10. Analyse wait chain shows csrss.exe

I've got a legacy VB6 application that runs on over 200 machines,mostly Windows 10 but also some 7 and 8. Its working great on the vast majority of computers but it randomly crashes on a small number of Win 10 systems. Randomly = between 1 and 5 times a day.

By crashing I mean it simply freezes. No other message. Nothing in the event viewer. The screen does grey out.

The crash occurs when a user clicks a button. Not the same button each time. The code behind the button(s) could be anything from opening a help form to running a search on an SQL Server. There is no consistency. I don't believe its actually the code causing the issue.

When I analyse the wait chain its always csrss.exe. csrss.exe has been scanned to ensure its not a virus. Its clean.

I know csrss.exe is something to do with the Windows sub system but its beyond my knowledge at the moment.

I'm looking for any help, ideas on the next step to finding the problem and of course curing it.

Thanks in advance

Sam




uniform_real_distribution not giving uniform distribution

I am trying to generate high quality random numbers in the range (0,1) in my project and I tried testing the uniform_real_distributionfrom a sample code from here. When I ran it the code it worked fine but when I tried to modify the same with seeding the generator like:

#include <random>
#include <iostream>
#include <chrono>

using namespace std;
// obtain a seed from the system clock:
unsigned seed = static_cast<int> (chrono::system_clock::now().time_since_epoch().count());

// globally defining the generator and making it static for safety because in the
// actual project this might affect the flow.

static default_random_engine gen(seed);
uniform_real_distribution<double> distribution(0.0,1.0);

int main(){
  const int nrolls=10000;  // number of experiments
  const int nstars=95;     // maximum number of stars to distribute
  const int nintervals=10; // number of intervals

  int p[nintervals]={};

  for (int i=0; i<nrolls; ++i) {
    double number = distribution(gen);
    ++p[int(nintervals*number)];
  }

  std::cout << "uniform_real_distribution (0.0,1.0):" << std::endl;
  std::cout << std::fixed; std::cout.precision(1);

  for (int i=0; i<nintervals; ++i) {
    std::cout << float(i)/nintervals << "-" << float(i+1)/nintervals << ": ";
    std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
  }

  return 0;

}

The random numbers were not uniformly distributed. The output of the same when executed repeatedly is:

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: **********

0.2-0.3: ********

0.3-0.4: *********

0.4-0.5: *********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: **********

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: *********

0.2-0.3: *********

0.3-0.4: *********

0.4-0.5: *********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: *********

F:\path>randtest

uniform_real_distribution (0.0,1.0):

0.0-0.1: *********

0.1-0.2: *********

0.2-0.3: *********

0.3-0.4: *********

0.4-0.5: **********

0.5-0.6: *********

0.6-0.7: *********

0.7-0.8: *********

0.8-0.9: *********

0.9-1.0: *********

Is it because of the seeding? or is it better to use a different generator?

I use G++ 5.1.0 compiler c++11 standards.




How do I generate a random string without certain characters?

I’m using Java 6 with Apache Commons. I have this code for generating a random string

        temporaryPassword = RandomStringUtils.random(TEMPORARY_PASSWORD_LENGTH,
                                                     true,
                                                     true);

My question is, how can I generate this random string without certain characters? For instance I wish to generate the string without zeroes and ones and “i”s and “o”s. There might be some others but if we can solve the problem with the characters I list, then we’re good.




php variable based on a random variable

I'm new to php and I wrote a code that takes a random winner out of an array and displays it, then I wanted to try to display all the names without the winner's, but how can I unset the winner by using the random number generated? I managed to unset a random name but not the same as the winner...

    <?php

// array

$winner = array();
    array_push($winner,"sonia");
    array_push($winner,"ice");
    array_push($winner,"sasha");
    array_push($winner,"isa");
    array_push($winner,"omar");
    array_push($winner,"anwar");

// random winner

    $giocatori = count($winner);   
        $random = rand(0,$giocatori -1);   
            unset($winner[$random]);

// Sort the list

sort($winner);
    echo "I giocatori sono: ";
        print join(", ",$winner);

// Print the winner's name in ALL CAPS

$truewinner = strtoupper($winner[$random]);
    echo "<br><br>";
    echo "il vincitore è: ";

// Print winner + sentence   

$losers = "losers";
$losers = strtoupper($losers);    
    echo (strtoupper($winner[$random]));
    echo "<br><br>";
    echo "all the players are: $losers beside $truewinner"; 

?>




mercredi 28 septembre 2016

Time VS Random Number

I have been wondering, is there any merits to using current time instead of generating a random number in terms of security. For instance, before hashing, using Time as the salt instead of generating a random number as the salt?




Python- Entry Level Programming

I need to set up a code that has a 50% chance of selecting the first character of the mother string or the first character of the father string and add it to the child string, and so on for each letter.

import random
mama_string = "0>Y!j~K:bv9\Y,2"
papa_string = "OkEK=gS<mO%DnD{"
child = ""

while len(child) < 15:

    random_number = random.randint(0,100)
    if random_number <= 50:
        for mama_char in mama_string:
            child += mama_char
            break

    if random_number > 50:
        for papa_char in papa_string:
            child += papa_char
            break




Python simulation of a company's

I have an assignment where I have to use Python code to simulate a company's hourly average maximum customer volume. The homework prompt says to import the random module and use the random.random() method. My issue is that I don't know what to put into the function itself. Here's the code I have so far:

import random

#Function to calculate the average maximum of customers per hour

def ave_max_calc(C, H, D):

    **HELP**


print('Hello, welcome to my average maximum hourly customer volume calculator!')

C = int(input('Give the number of customers per day: '))
H = int(input('Give the number of business hours per day: '))
D = int(input('Give the number of days to simulate: '))

print('The average maximum hourly customer volume is: ', ave_max_calc(C,H, D))




Shuffle not working on random array

Could someone tell me why this keeps returning repeated values

void d(){
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<12; i++) {
    list.add(new Integer(r.nextInt(50-1)+1));
    Collections.shuffle(list);
}

for (int i=0; i<11; i++) {
    random[i]=list.get(i);
    System.out.println(list.get(i));
}

}




Mersenne Twister 64: origin of 'd' tempering parameter?

Short version: common MT (and MT64) implementations have an extra tempering parameter 'd'. The papers I've looked at describing MT don't include it. Where is it from? When was it added?

Long version! :)

I'm looking at using a family of MT's with different parameters (for reasons). Nishimura published this paper describing a 64-bit MT implementation and a number of alternatives for the A matrix and (u,s,t,l,b,c) tempering parameters. Like the original 32-bit MT paper, this describes the tempering procedure as:

y := x xor (x >> u)
y := x xor ((y << s) and b)
y := x xor ((y << t) and c)
z := x xor (y >> l)

However, real implementations ( a b ) and the parameters described in the MT Wikipedia page have an extra bit mask parameter (referred to as 'd'), applied to the first step of the tempering procedure:

x ^= (x >> 29) & 0x5555555555555555ULL;
x ^= (x << 17) & 0x71D67FFFEDA60000ULL;
x ^= (x << 37) & 0xFFF7EEE000000000ULL;
x ^= (x >> 43);

I don't want to just 'blindly' use the tempering parameters that exclude the parameter 'd' without understanding what it's for... but I can't seem to find any references for why this 'd' parameter was added. (Presumably, it's an improvement...)

Any ideas on what it's for, any references to why it was added?




Batch File - Random 10 Digit Number

I'm looking for a batch file code that will generate a random 10 digit number and will show up to the user using the batch file... (I'm making a generator)




How to randomly generate a float between two values with a variable number of ranges excluded?

For example, if I wanted to generate a random float between 0 - 100, but exclude the values 1.097 - 3. 346, 7.0001 - 8.9996, 14.5 - 38.6, 50 - 50.389, 75.648 - 88.8975, etc? I thought this would be a simple problem, but there doesn't even seem to be Range object in c#, and there is no RandWithExclusion() method.

I have seen all these questions,
How can I generate a random number within a range but exclude some?
http://ift.tt/2cLRJNE
How to get a random number from a range, excluding some values
none of them are even remotely useful. Is what I'm doing really such a rare problem?

How would I even go about doing this? (Without brute-forcing, please.)




precision in sum of random floats in numpy

I have an array of random floats and I need to compare it to another one that has the same values in a different order. For that matter I use the sum, product (and other combinations depending on the dimension of the table hence the number of equations needed).

Nevertheless, I encountered a precision issue when I perform the sum (or product) on the array depending on the order of the values.

Here is a simple standalone example to illustrate this issue :

import numpy as np

n = 10
m = 4

tag = np.random.rand(n, m)

s1 = np.sum(tag, axis=1)
s2 = np.sum(tag[:, ::-1], axis=1)

# print the number of times s1 is not equal to s2 (should be 0)
print np.nonzero(s1 != s2)[0].shape[0]

If you execute this code it sometimes tells you that s1 and s2 are not equal and the differents is of magnitude of the computer precision.

The problem is I need to use those in functions like np.in1d where I can't really give a tolerance...

Is there a way to avoid this issue?




Do I need a random geometry, material, or something else? - SceneKit, Swift

In my game, I add a new a tempLeftBox (an SCNNode with an SCNBox geometry, and an SCNMaterial) every 5 seconds or so along a straight path. The tempLeftBox has its own geometry and its own material. For each tempLeftBox that is added, the color of the box should be random. This random color should ONLY affect that ONE box that was just added. Not all of the boxes that are going to be added or have been added already. How should I go about doing this? Swift, SceneKit




How do you generate a random uint64 in Go?

Go's math/random library is missing a function to generate 64-bit numbers. This has been an open issue for about four years. In the meantime, what does a workaround look like?




Random Video via MySQL

I have a MySQL database in which i store the URL to 8 videos. What i want to do know is display them random in a slider. It's alls working until now, besides that the Video is not random but all the time the same, which means: The video gets randomly picked from the database, but each time i refresh the page, it's 8 times video number 1, next refresh is 8 times number 6 etc.

<?php                            $mysqli = new mysqli("####", "####", "###", "clearchannel");
                                 if ($mysqli->connect_errno) {
                                 echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
                                 }                      

                                $res = $mysqli->query("SELECT EmbedURL FROM Videos where location_id='2' ORDER BY RAND() LIMIT 3");
                                $vid = $res->fetch_assoc();
                            ?>  
                        <ul class="bxslider">
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                            <li><iframe src="<?php echo $vid['EmbedURL']; ?>" frameborder="0" autoplay="0" allowfullscreen></iframe></li>
                        </ul>           

?>

You can see the result here: http://ift.tt/2dlvL1D

Thanks a lot!




Error: Java symbol not found; called correctly

I'm doing an assignment for AP Computer Science at my high school. I am trying to simulate a game of Craps. The dice is supposed to return a random int between 1 and 6. The teacher looked at it and couldn't figure it out.

public class TestDie
{
   public static void main(String[] args)
   {
      Die die = new Die();
      die.roll();
      System.out.println(die.getNumDots());
      die.roll();
   }
}

Error: TestDie.java:7: error: cannot find symbol

System.out.println(die.getNumDots());

It is testing this, which compiles fine import java.lang.Math;

public class Die
{
   private int numDots;

   private void roll()
   {
   //double random = Math.random() * 50 + 1;
   numDots = (int )(Math.random() * 6 + 1);
   }

   public int getNumDots()
   {
   return numDots;
   }
}




sync randomization between R and Python

Are there off-the-shelf approaches in R and Python that will allow me to generate identical PRNG results?

Background: I am trying to migrate some code from R to Python. It contains an algorithm that uses sample without replacement.

I can validate the migrated code by either (simpler) show that it produces identical results on a small set of inputs or (more complex) show that the results converge given a larger set of inputs.

Let's say I wanted to take the simple route. Obviously, the following do not produce identical results, because there are different PRNGs and implementations of sampling functions under the hood.

# R
set.seed(1)
sample(0:9,3)
# returns vector 2 3 4

and:

# Python
import random
random.seed(1)
random.sample(range(10),3)
# returns list 2 1 4

I could just suck it up and write my own PRNG, which would be educational but would require more programmer time (on non-optimized code). If it came to that I would probably opt for the more complex validation.

Are there any alternatives to doing so using existing libraries? I would prefer not to introduce third-party dependencies (like Java API). Currently leaning toward rPython implementation but open to anything.




How to solve for importance in r

When i typed the command for importance as below importance(model.rf)

I obtained the error as below

Error in UseMethod("importance") : no applicable method for 'importance' applied to an object of class "c('randomForest.formula', 'randomForest')"

How to solve this error?




Map rand5 to number in range

I Have a function call Rand5, that random number between 1..5, for example (1,1,1) (1,2,5) ...

I call random 5 three time so i have three numbers between 1-5.

generally there is 125 options.

I want to map the 125 options to numbers between 1 to 125.

so (1,1,1) map to 1. (1,1,5) map to 5. (1,2,2) map to 7. (5,5,5) map to 125.

Can you help me with pseudo-code.

Thank!




Reproduce the same result of the C++ 11 random generator

Is it guaranteed by the standard that if std::mt19937 was seeded by the same number, it will produce the same sequence of numbers on all platforms?

In other words, is its implementation well-defined by the standard or it is like std::rand() which was considered as implementation details?




mardi 27 septembre 2016

Making random rectangles w/ random (linewidth,color, and position)

I'm completely new to compute programming I've got an "Intro to JavaScript" class that I'm in and we've been asked to create a very basic HTML code using canvas that has randomly drawn rectangles with linewidths, colors, and positions.

This class uses w3schools as a teaching aid (I've seen it bashed for being outdated), and has referenced us there.

I'm supposed to use;

 function getRandomColor() {   
 var chars = '0123456789ABCDEF'.split('');
 var hex = '#';
 for (var i = 0; i < 6; i++) {
    hex += chars[Math.floor(Math.random() * 16)];
 }
 return hex;
 }

and manipulate this functions properties to make;

 function getRandomlinewidth() 

//this function sets the line width of the rectangles ranging between 1 and 8.

Hoping someone could point me in the right direction? Also any "new to JS" or "JS for beginners" tutorials or similar are VERY appreciated!

Cheers!




Does using hashmap to store input makes an algorithm randomized?

I'm currently studying Algorithms in which I need to find both deterministic and randomized algorithms for the same problem.

So, the input for the algorithm is a finite set of value pairs something like below

[(a,b),(b,c),(c,d),(d,e)................]

If I'm looping through the above array and inserting each set(a,b) into a standard hashmap with key = a and Value = b, and use it derive the solution. Does that make my algorithm randomized?

I'm confused because one of the TA's for the course said it will make this case for randomized algorithms.

The example given in the CLRS(Hiring problem) to introduce the concept Randomized algorithm, randomizes the input data before accessing the input.

Does using a hashmap to store the input data makes it come under the category of a randomized algorithm? If yes, how?




Distributed Random Number Generator

I am thinking about starting a project based around the idea of distributing the work and entropy of random number generation between a number of devices ranging from androids to computers; I want to gather entropy on the machines and send and receive packets of encrypted data to mix into the entropy pools. I want the program to run in the background if the program closes. I will have access to a web server to handle negotiation of connections from client to client.

My question is what sorts of things do I need to think about when creating such a system? My programming (and mathematics) knowledge is limited, what are the best areas I should spend energy brushing up on in order to create such a project?




spawn box next to each other over and over for ever? Swift

HI im trying to make a game where theres a character and he jumps up on boxes like this

enter image description here

but i cant seem to get spawning down, all i need is to use the runblock function to keep spawning boxes but next to the previous box each time if you know what i mean, just make the block coming in next to the previous block so makes stairs i can get the height randomized so i just need them side to side thank you




Spawn gameObject horde, modify concentration of spawned objects

How would I create a non-uniform random generation of gameObjects (enemies) that mimic the formation of a "horde" like this image: enter image description here

I want there to be more gameObjects in the front and less as it trails off towards the back. I thought of making an Empty gameObject and having the enemies target with code like this:

public Vector3 target : Transform;
if (target == null && GameObject.FindWithTag("Empty"))
{
       target = GameObject.FindWithTag("Empty").transform;
}

However, doing that would not give me the "trail" effect where there are fewer int he back.

Here is my code for randomly generating enemies, if it helps:

void SpawnHorde()
{
    for (int i = 0; i < hordeCount; i++) 
    {
        Vector3 spawnPosition = new Vector3(Random.Range (0, 200), 50, Random.Range (0, 200));
        Instantiate(Resources.Load ("Prefabs/Sphere"), spawnPosition, Quaternion.identity);
    }
}

Does anyone have a suggestion as to how to achieve this?




Java Random.nextDouble() probability

I'm trying to get random double numbers between 1.0 and 10.0 using the Random.nextDouble() as such:

double number = 1.0 + (10.0-1.0) * Random.nextDouble();

Simulating this 10,000 times I find out that the probability of 1.0 and 10.0 is lower than the rest. The only way to get these number would require Random.nextDouble() to be either 0.0 or 1.0. So essentially since Random.nextDouble() gives a random number inbetween 0.0 and 1.0 it's less likely to actually result in 0.0 or 1.0.

Is there a way to mend this I wonder? Or should I try a completely different way as a whole?




Generate uniform random variable in R when lower boundary is close to zero

When I run in R runif(100,max=0.1, min=exp(-10)), I get 100 uniformly distributed random variables between 0.1 and 0.0001. So, there is no random values between 0.0001 and the min value (min=exp(-10)). How to generate uniform random variables on the whole interval (between min and max values).




lundi 26 septembre 2016

Generating random doubles in Jav between 0 and 1 inclusively or [0..1]

Java Math.random() returns a random number in [0..1). Is there a way to make 1.0 inclusive? Eventually I would like to have a random number (floating point number) in a specific range such as [Min..Max]. We know that for integers it will be

Min + (int)(Math.random() * ((Max - Min) + 1))




random number generation using python

I'm looking to create random numbers since due to circumstances I cannot use the random library. Basically I'd like to be able to replicate the random.randint() and random.random() methods using pure python.

I don't expect anyone to dump an entire code in python (though that would be great), but can someone refer me to a similar C/C++/Java algorithm that can be easily replicated into python?




UNITY C# Input Field with a word that cannot be deleted

I'm pretty new to Unity. I'd like to create a mini-game. I wanted to ask if it's possible to create something like this using InputField and C#:

Example: http://ift.tt/2deGNpn

In this example "dog" is a random-generated word (from text file) which cannot be deleted but user can type in some "text" before and after "dog" to create a sentence. I want "dog" to be a part of InputField because I will use that InputField content later on.

Thanks




Python 3 - How to randomize what text displays

I am a beginner at python and I am trying to figure out how I can randomly display text. For example, 60% chance of "Hello", 40% chance of saying "Goodbye", etc. Right now, for fun, I am trying to create sort of a bottle flip game. If you don't know what it is, its basically when you flip a half empty water bottle and try to land it. This is what I have: (This is more than likely completely wrong.)

import random

number = random.randrange(10)

if number == "1":

    print ("You have landed the bottle!")

elif number == "2":

    print ("You have landed the bottle!")

elif number == "3":

    print ("You have landed the bottle!")

elif number == "4":

    print ("You have landed the bottle!")

elif number == "5":

    print ("The bottle did not land, better luck next time.")

elif number == "6":

    print ("The bottle did not land, better luck next time.")

elif number == "7":

    print ("The bottle did not land, better luck next time.")

elif number == "8":

    print ("The bottle did not land, better luck next time.")

elif number == "9":

    print ("The bottle did not land, better luck next time.")

elif number == "10":

    print ("The bottle landed on the cap!")

Any help would be appreciated. - ICE




Python: random choice executing all function calls listed

I'm stuck on a probably simple issue: when using choice with functions, it seems like all of them gets executed while only one should. Example:

from ordereddict import OrderedDict
from random import choice

def PrintStrings():
    Text = choice(["Gutentag!", "Ni hao!", "Hola!"])
    print "Chosen Text is:", Text
    return Text

class Greeting():
    fields = OrderedDict([
         ("Morning",     "Hi"),
         ("Afternoon",   "Good Afternoon!"),
         ("Evening",     "Good Evening!"),
    ])

    def change(self):
        self.fields["Morning"] = "Good morning!"

    def changerandom(self, n = 1): 
        function=[
                    {self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},
                 ]
        result = {}
        for i in range(n):
            result.update(choice(function))
            print "Updated string:",result
            return result

text = Greeting()
text.change()
text.changerandom()

When running this script, I get all 3

                    {self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},

executed, while it shouldn't. This script returns:

Chosen Text is: Ni hao!
Chosen Text is: Gutentag!
Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}

Expected result is:

Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}




Random Number Generator (with parameters) in Swift 3

I am trying to create a random number generator in swift, however I can't seem to find a way to make a random number generator with a given parameter. I am looking with such I can give it a parameter, say "5" and it will generate a random number between 0 and 5.




Random fraction with random operator calculator in Java

I'm trying to create fraction calculator with Java and with random operation, there will be 10 question, my problem is the answerKey always give me answer = null; i think the wrong code is in answerKey() method, because can't convert String into Fraction.

here's my code:

public class TesterFractionTugas1 {
    public static void main(String[] args){
    Scanner in               = new Scanner(System.in);
    Random rand              = new Random();
    final int jumlahSoal     = 10;
    int count                = 0;
    String output            = "";

    while(count < jumlahSoal){
        int angka1 = (int) (Math.random() * 10 + 1);
        int angka2 = (int) (Math.random() * 10 + 1);
        int angka3 = (int) (Math.random() * 10 + 1);
        int angka4 = (int) (Math.random() * 10 + 1);

        char operator = genOperator(rand.nextInt(3));

        Fraction pecahan1 = new Fraction(angka1, angka2);
        Fraction pecahan2 = new Fraction(angka3, angka4);

        System.out.println("Question :" + evaluateQuestion(pecahan1.getFraction(), pecahan2.getFraction(), operator));
        System.out.println("AnswerKey: " + answerKey(pecahan1, pecahan2, operator)); // wrong code in here

        System.out.println("your answer: ");
        Fraction pecahanAnswer = new Fraction();
        String answer          = in.nextLine();
        String[] sptext        = new String[2];

        sptext = answer.split("/");
        pecahanAnswer.setNumerator(Integer.parseInt(sptext[0]));
        pecahanAnswer.setDenominator(Integer.parseInt(sptext[1]));

        if(answer == answerKey(pecahan1, pecahan2, operator)){
            System.out.println("You right");
            count++;
        } else {
            System.out.println("You Wrong");
            count++;
        }
    }       
}

// giving operator for math
public static char genOperator(int a){
    switch(a){
        case 0: return '+';
        case 1: return '-';
        case 2: return '*';
        case 3: return '/';
        default: return '+';
    }
}

// the question here
public static String evaluateQuestion(String pecahan1, String pecahan2, char operator){
    return  pecahan1 + " " + operator + " " + pecahan2;
}

// answerkey
public static String answerKey(Fraction pecahan1, Fraction pecahan2, char operator){
    switch (operator){
        case '+': pecahan1.addFraction(pecahan2);
        case '-': pecahan1.subtractFraction(pecahan2);
        case '*': pecahan1.multiplyByFraction(pecahan2);
        case '/': pecahan1.divideByFraction(pecahan2);
        default: return null;
    }

  }
}


class Fraction {
    private int numerator, denominator;

public Fraction(){
    numerator = 0;
    denominator = 1;
}

public Fraction(int numerator, int denominator){
    this.numerator = numerator;
    this.denominator = denominator;
}

public void setNumerator(int numerator){
    this.numerator = numerator;
}

public int getNumerator(){
    return this.numerator;
}

public void setDenominator(int denominator){
    this.denominator = denominator;
}

public int getDenominator(){
    return this.denominator;
}

public String getFraction() {
    return numerator + "/" + denominator;
}

public String toString(){
    return numerator + "/" + denominator;
}

public String addFraction(Fraction pecahan2) {
    // Sum formula: a/b + c/d = (ad + cb)/bd
    int a = this.numerator;
    int b = this.denominator;
    int c = pecahan2.numerator;
    int d = pecahan2.denominator;
    return ((a*d) + (c*b)) + "/" + (b*d);
}

public String subtractFraction(Fraction pecahan2) {
    // Subtraction formula: a/b - c/d = (ad - cb)/bd
    int a = this.numerator;
    int b = this.denominator;
    int c = pecahan2.numerator;
    int d = pecahan2.denominator;
    return ((a*d) - (c*b)) + "/" + (b*d);
}


public String multiplyByFraction(Fraction pecahan2) {
    // Multiplication formula: a/b * c/d = ac/bd
    int a = this.numerator;
    int b = this.denominator;
    int c = pecahan2.numerator;
    int d = pecahan2.denominator;
    return (a*c) + "/" + (b*d);
}

public String divideByFraction(Fraction pecahan2) {
    // Division formula: (a/b) / (c/d) = ad/bc
    int a = this.numerator;
    int b = this.denominator;
    int c = pecahan2.numerator;
    int d = pecahan2.denominator;
    return (a*d) + "/" + (b*c);
    }
}

Any answer? thank you




Weighted distribution among buckets with no look-ahead

I have N workers that need to process incoming batches of data. Each worker is configured so that it knows that it is "worker X of N".

Each incoming batch of data has a random unique ID (being random, it is uniformly distributed), and it has a different size; processing time is proportional to the size. Size can vary wildly.

When a new batch of data is available, it is immediately visible as available to all N workers, but I want only one to actually process it, without coordination among them. Right now, each worker calculates ID % N == X, and it it's true, the worker self-assigns the batch, while the others skip it. This works correctly and makes sure that, on average, each worker processes the same number of batches. Unfortunately, it doesn't take into account the batch size, so some workers can finish processing much later than others, because they might happen to self-assign very large jobs.

How can I change the algorithm so that each work self-assigns batches in a way that also takes into account the size of the batch, so that on average, each worker will self-assign the same total size of work (from different batches)?




Find seed from previously-run code in R? How many possibilities are there?

I forgot to use set.seed myself in R and I'm trying to figure out what the seed was set to.

Anybody know how many possibilities there are?

I'm currently using the code below to generate 100 random values for each seed to check whether the list matches rand100, the 100 random values I'm trying to match.

t0= Sys.time()
for (i in 600000:1000000){

  set.seed(i)
  rand = runif(100,0,1)
  if (!(all.equal(rand100,rand) > 0)){
    print("match found!")
    print(i)
    break
  }

  t1= Sys.time()

  if(t1-t0>50){

    print("timeout")
    print(i)
    break
  }
}




Generate a Random Number in between 1 to 7 and reset it again so that it can generate the value from 1 to 7 again

I want to generate a number from 1 to 7. After I use all the values from 1 to 7 I want to reset the random generator to reset and generate the values again.

Is it possible in JAVA?




Generating an array of random numbers such that the numbers at the higher indexes are greater

I am trying to generate an array of random numbers such that the numbers at the higher indexes should be greater than the numbers at the lower indexes.

For example, an array like this:

array = [1.5  1.7  2.4  5.6  8.5  8.9  9.2  9.5  10.2  11.3]

I can do this using:

array(1:10) = 0;       % Pre-allocation
array(1) = abs(randn); % Generating a +ve rand no.
for k=2:10
    array(k) = abs(randn) + array(k-1);  % adding a +ve rand no. to the previous value 
end

I am looking for a better (and/or vectorized) way!




Can I increase linux entropy by using rngd or script?

I want to continuously increase /prco/sys/random/entropy_avail when it reduced.

I first check the rngd (http://ift.tt/2d2AWGQ)

It says /dev/random is very slow since it only collects entropy from device drivers and other (slow) sources and I think that is why we use rngd.

And it says rngd mainly uses hardware random number generators (TRNG), present in modern hardware like recent AMD/Intel processors, Via Nano or even Raspberry Pi.

problem is here. When I start rngd it says

[root@localhost init.d]# rngd 
can't open entropy source(tpm or intel/amd rng)
Maybe RNG device modules are not loaded

But I don't have intel rng confirmed by cat /proc/cpuinfo | grep rdrand

[root@localhost init.d]# cat /proc/cpuinfo | grep rdrand | wc -l
0

If there is any possible resources that I can use???
or
Is it possible making script to increase /proc/sys/random/entropy_avail ??

Thanks. Any comments are appriciated.




Generating random Number ATMega168, AVR STUDIO 4

how can I generate a random number(command) in Avr Studio 4. I have an ATMEGA168. I want to generate the random number, so the "warten"(waiting) has an non defined waiting time and is changing all time. So if it has decreased from 255 to 0 etc. I want it to generate a random number which defines if its going another time through the waiting or if it's going to ret. Here's my code:

.include "m168def.inc" ;ATMega 168

rjmp main                

main:
ldi r16, 0b00000100

out ddrB, r16           

loop:
ldi r16, 0b00000100
out portB, r16

rcall warten            

ldi r16, 0b00000000     
out portB, r16          
rcall warten

rjmp loop

warten: ldi r17,2
w3:
ldi r18,255
w2:
ldi r19,255
w1:
dec r19
brne w1

dec r18                 
brne w2                 



dec r17                 
brne w3                 

ret




dimanche 25 septembre 2016

rand() only sets variable to 0

I am working on a rock, paper, scissors game and one of the ways I am setting the computer's choice is through rand(). I #include , seed rand at the start of main with srand (time(0)); and I call it in a function definition with computerWeaponChoiceV = (rand() % 3) + 1;. However, when I test my program it always prints computerWeaponChoiceV to be 0.

Am I doing something wrong with rand()? If you need more of my code please let me know.




python: how can I test if data is independently identically distributed

do you know, if scipy or any other pythonmodule provides tests, so I can check wether some data is identically independently distributed (iid) ?

Thank you for your help




Random List, Find Max

I need to generate a random list of 100 numbers, then go through that list until I find the max number using a for loop, but it only runs through once (because num is outside the loop), but when I put num in the loop nothing happens

import random

def main():

    largest = None

    num = []
    num.append(random.randint(1,500))

    count = 0

    for n in num:


        count = count + 1

        print 'The largest known number is,', largest

        if n > largest:

            largest = n
            print 'Next largest number known is,',largest,'\n'
            print 'It took', count,'trys to find the largest number'


main()




How can I add 100 random elements to an empty array with duplicates?

In this code, I'm shuffling 100 random elements instead of adding 100 random elements with duplicates, and returning 10 unique keys. How can I do that?

import java.util.ArrayList; import java.util.Collections;

public class UniqueRandomElements {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here

    ArrayList<Integer> uniqueKeys = new ArrayList<Integer>();
    for (int i = 0; i < 101; i++) {
        uniqueKeys.add(new Integer(i));
    }
    Collections.shuffle(uniqueKeys);
    for (int i = 0; i < 101; i++) {
        System.out.println(uniqueKeys.get(i));
}
}

}




Edit executavble command to make random number generator in Perl

I was using this module for Perl, Crypt::PRNG, to generate random numbers. The number-generation seems truly random when using the random string command, it can use digits 0-9 as well as other characters and create a random string of the specified number of digits, the problem is the leading 0's.

perl -MCrypt::PRNG=:all -E "say random_string_from("1234567890", n)"

where n is the number of digits, is there a executable command similar to the one above to fix the leading 0's so I can for sure get an n digit number? My intent is to fix only the first digit to "123456789". Does anyone know how to do this? Thanks in advance.




Generate random XML document

i try to create an app with some questions. I want button to generate random questions but I couldn't find anything so far (some shorter solution if possible). Thank you :)

something.java file code:

public class something extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.somethingXML);

}
public void generate (View view){
    Intent intent = new Intent(this, ???? .class);
    startActivity(intent);
}}

somethingXML.xml layout file code:

<Button
        android:layout_width="fill_parent"
        android:layout_height="30pt"
        android:text="@string/buttonM"
        android:id="@+id/buttonM"
        android:layout_marginTop="46dp"
        android:onClick="generate"
        android:clickable="true"
        android:textStyle="bold" />

Simply if I use button with id "generate", I want to generate it random xml page, but Intent(this, ???? .class) has only one option [example: Intent(this, question1.class)], but I do not want user to solve question1 page always he turns this app on.




samedi 24 septembre 2016

Theano - Shared variable to record randomly generated value

I don't understand how to use shared variable to record a randomly generated value.

I am doing the following operation:

import theano 
import theano.tensor as T 
from theano import function
from theano.tensor.shared_randomstreams import RandomStreams

srng = RandomStreams(seed=22)
a = srng.uniform((10,1))
b = srng.uniform((10,1))
sum = a + b
f = function([], sum)

Now I want to use a shared variable to record the the randomly generated value of a, and another shared variable to record the randomly generated value of b.

I tried using get_value but I get the error "'TensorVariable' object has no attribute 'get_value'". I also tried initializing the shared variable with the value of the randomly generated variable, but I get the error "Shared variable constructor needs numeric values and not symbolic variables."

Sorry I am new to theano and am getting stuck on basics. Please help me. Thanks!




Filling An Array With random Integer Values

I bought a JavaScript book and am working my way through. I've reached a part of the book that doesn't make sense. I'm hoping you guys and girls will be able to clarify as the book doesn't.

Please see the code below that generates 6 random numbers and renders them to a div with id=panel.

function init(){
var panel = document.getElementById('panel');
var i, rand, temp, str, num = [];

for (i = 1; i < 50; i ++){
    num[i] = i;
}

for (i = 1; i < 50; i ++){
    rand = Math.ceil(Math.random()*49);
    temp = num[i];
    num[i] = num[rand];
    num[rand] = temp;
}

str = 'Your six lucky numbers:<br>';
for (i = 1; i < 7; i ++){
    str += num[i];
    if (i !==6){str += ' - ';}
}
panel.innerHTML += str;

}
document.addEventListener('DOMContentLoaded', init, false);

The book says that the second loop (that initilizes the random variable) contains a sort algorithm that ensures no two elements contain the same number.

I'm not sure how this is possible, I don't see any code in there that stops rand containing a duplicate number and consequently having that value stored in num. The book doesn't really provide much of an explanation of what is going on.

Could someone please let me know how, if at all, loop two is preventing 'num` from containing the same number?

Thanks all

P.S. Sorry if this question doesn't adhere to Stack Overflow guidelines. I don't come on here often, only when I get really stuck and can't find an answer elsewhere.




random.randrange does not seem quite random

I am pretty new to python so i dont know many things. So lets say i got this piece of code

for i in range(10000):
n = random.randrange(1, 1000**20)
ar.append(n)
print(n)

The smallest number i get out of the 10000 is always 3-4 digits smaller than 1000^20 in this particular example the smallest numbers are

2428677832187681074801010996569419611537028033553060588
8134740394131686305349870676240657821649938786653774568
44697837467174999512466010709212980674765975179401904173
50027463313770628365294401742988068945162971582587075902
61592865033437278850861444506927272718324998780980391309
71066003554034577228599139472327583180914625767704664425
90125804190638177118373078542499530049455096499902511032
100371114393629537113796511778272151802547292271926376588

i have tried multiple ranges on multiple occasions and every time i get the same results.Maybe i am doing something wrong?




Does ramsey/uuid version 4 use "true" or pseudo-random numbers?

I'm using ramsey/uuid in my project. I'm creating new data entities with uuid4, which generates random UUIDs:

Uuid::uuid4();

But I'm using this approach while bulk importing many thousands of data too. Now I'm worrying about the entropy pool of my system: does uuid4 use a "true" random number which will deplete my entropy pool at some time? Or will it use pseudo-random numbers and I don't have to worry about?

Thanks a lot!




Picking primes to use for Halton Sequences in R

I'm trying to generate some two-dimensional Halton Sequences in R, and am using the randtoolsbox package. It seems as if this function defaults to choosing 2 and 3 as the prime bases, but I'd like to generate sequences using others. The documentation does not indicate (as far as I can tell) any way of setting this option.

Does anyone know of a way, using randtoolsbox or another package, of generating Halton Sequences in R based on user-chosen prime bases?




Is my subroutine correct for generating a random Barabasi-Albert graph?

I would like to generate a random Barabasi-Albert graph with 10,000 node, but my program is very slow. Can anybody help if my subroutine is correct or not? In my code ran1() is the standard random number generator. Thanks for the help.

 ***********************************************************************
      subroutine barabasi_albert(kon,n,m0,m,a,idum)
***********************************************************************
      implicit real*8(a-h,o-z)
      implicit integer*4(i-n)
      logical linked(n)    ! logical array for storing if a node is connected 
                           ! to the current one
      dimension kon(n,n)   ! connectivity matrix 
                           ! m0: number of initial nodes
                           ! m: minimal degree
                           ! a: scale parameter
                           ! idum: argument to the random number generation
c
c Initialize kon(:,:)
c                           
      kon(:n,:n)=0
c
c Create complete graph of m0 node 
c                          
      kon(:m0,:m0)=1
      do i=1,m0
         kon(i,i)=0
      end do
c
c Extend the graph with n-m0 node
c      
      do i=m0+1,n
         linked(:i)=.false.
c
c Add edges while the vertex degree of the ith node is less than m
c         
         do
            if(sum(kon(i,:i-1)).eq.m) exit
            ii=floor(dble(i-1)*ran1(idum))+1
            if(.not.linked(ii)) then
               p=(dble(sum(kon(ii,:i-1)))/sum(kon(:i-1,:i-1)))**a
               if(p.gt.ran1(idum)) then
                  kon(i,ii)=1
                  kon(ii,i)=1
                  linked(ii)=.true.
               endif
            endif
         end do
      end do
      end

Some links connected to:

http://ift.tt/2cult3h

http://ift.tt/2d7cMtz

Implementing Barabasi-Albert Method for Creating Scale-Free Networks




valgrind: Unrecognised instruction at address 0x5111715

I've a function that looks something like this -

std::string func()
{
    std::string result;

    ...

    auto seed = std::random_device()();
    std::mt19937 gen(seed);
    std::uniform_int_distribution<> dis(0, 61);

    ...
    return result;
}

which compiles fine across variety of compilers and their versions, but still fails to pass the valgrind test on Ubuntu. I explicitly mentioned ubuntu because it passes successfully on my machine which has Arch Linux installation.

Both valgrind installations report their version as valgrind-3.11.0 and the only difference is Arch Linux installation is on my machine with no virtualization, while Ubuntu tests have been done on DO/CI servers which probably are under some kind of virtualization. But should that matter?


Here is the log for valgrind run -

 --- stderr ---
==13849== Memcheck, a memory error detector
==13849== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==13849== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==13849== Command: file/path/here
==13849== 
vex amd64->IR: unhandled instruction bytes: 0xF 0xC7 0xF0 0x89 0x6 0xF 0x42 0xC1
vex amd64->IR:   REX=0 REX.W=0 REX.R=0 REX.X=0 REX.B=0
vex amd64->IR:   VEX=0 VEX.L=0 VEX.nVVVV=0x0 ESC=0F
vex amd64->IR:   PFX.66=0 PFX.F2=0 PFX.F3=0
==13849== valgrind: Unrecognised instruction at address 0x5111715.
==13849==    at 0x5111715: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.22)
==13849==    by 0x51118B1: std::random_device::_M_getval() (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.22)
==13849==    by 0x4809FB: std::random_device::operator()() (random.h:1612)
==13849==    by 0x47F0C2: isaac::deviceList::genId[abi:cxx11](unsigned int) (deviceList.cpp:21)
==13849==    by 0x47F2A7: isaac::deviceList::place(isaac::deviceType, nlohmann::basic_json<std::map, std::vector, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool, long, unsigned long, double, std::allocator>) (deviceList.cpp:38)
==13849==    by 0x40D06E: DeviceList_place_Test::TestBody() (test.cpp:194)
==13849==    by 0x45D5A7: void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) (gtest.cc:2078)
==13849==    by 0x4588D2: void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) (gtest.cc:2114)
==13849==    by 0x43EBB3: testing::Test::Run() (gtest.cc:2151)
==13849==    by 0x43F3F5: testing::TestInfo::Run() (gtest.cc:2326)
==13849==    by 0x43FA52: testing::TestCase::Run() (gtest.cc:2444)
==13849==    by 0x446911: testing::internal::UnitTestImpl::RunAllTests() (gtest.cc:4315)
==13849== Your program just tried to execute an instruction that Valgrind
==13849== did not recognise.  There are two possible reasons for this.
==13849== 1. Your program has a bug and erroneously jumped to a non-code
==13849==    location.  If you are running Memcheck and you just saw a
==13849==    warning about a bad jump, it's probably your program's fault.
==13849== 2. The instruction is legitimate but Valgrind doesn't handle it,
==13849==    i.e. it's Valgrind's fault.  If you think this is the case or
==13849==    you are not sure, please let us know and we'll try to fix it.
==13849== Either way, Valgrind will now raise a SIGILL signal which will
==13849== probably kill your program.
==13849== 
==13849== Process terminating with default action of signal 4 (SIGILL): dumping core
==13849==  Illegal opcode at address 0x5111715
==13849==    at 0x5111715: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.22)
==13849==    by 0x51118B1: std::random_device::_M_getval() (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.22)
==13849==    by 0x4809FB: std::random_device::operator()() (random.h:1612)
==13849==    by 0x47F0C2: isaac::deviceList::genId[abi:cxx11](unsigned int) (deviceList.cpp:21)
==13849==    by 0x47F2A7: isaac::deviceList::place(isaac::deviceType, nlohmann::basic_json<std::map, std::vector, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool, long, unsigned long, double, std::allocator>) (deviceList.cpp:38)
==13849==    by 0x40D06E: DeviceList_place_Test::TestBody() (test.cpp:194)
==13849==    by 0x45D5A7: void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) (gtest.cc:2078)
==13849==    by 0x4588D2: void testing::internal::HandleExceptionsInMethodIfSupported<testing::Test, void>(testing::Test*, void (testing::Test::*)(), char const*) (gtest.cc:2114)
==13849==    by 0x43EBB3: testing::Test::Run() (gtest.cc:2151)
==13849==    by 0x43F3F5: testing::TestInfo::Run() (gtest.cc:2326)
==13849==    by 0x43FA52: testing::TestCase::Run() (gtest.cc:2444)
==13849==    by 0x446911: testing::internal::UnitTestImpl::RunAllTests() (gtest.cc:4315)
==13849== 
==13849== HEAP SUMMARY:
==13849==     in use at exit: 84,300 bytes in 108 blocks
==13849==   total heap usage: 622 allocs, 514 frees, 530,112 bytes allocated
==13849== 
==13849== LEAK SUMMARY:
==13849==    definitely lost: 0 bytes in 0 blocks
==13849==    indirectly lost: 0 bytes in 0 blocks
==13849==      possibly lost: 0 bytes in 0 blocks
==13849==    still reachable: 84,300 bytes in 108 blocks
==13849==         suppressed: 0 bytes in 0 blocks
==13849== Rerun with --leak-check=full to see details of leaked memory
==13849== 
==13849== For counts of detected and suppressed errors, rerun with: -v
==13849== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
-------




vendredi 23 septembre 2016

JAVA HELP: how to print 20 random phone numbers

HOW DO YOU DO THIS???

PhoneNumber.java Write a program that create and prints 20 RANDOM phone numbers of the form

(XXX) YYY – ZZZZ (XXX) YYY – ZZZZ (XXX) YYY – ZZZZ (XXX) YYY – ZZZZ

Include the parenthesis and the dash in your output.

Do not let an 8 or 9 appear ANYWHERE in the area code (first three digits – XXX). Do not let the area code start with a 0 or 1. There are no other restrictions on this number!

Do not let the second set of three digits, YYY, be greater than 742. Do not let the second set of three digits start with a 0 or 1 either. (In other words, 571 is valid but 175 is not.) There are no other restrictions on this number.

There are no restrictions on the value of the last four digits.

Warning: each digit MUST print in your answer. You need to let the computer pick a random number for you.

Hint: Think this through. Sometimes you have to determine each digit separately, and sometimes you don’t. You may way want to use the DecimalFormat class.

Error Checking: Depending on your algorithm, make sure it is a valid phone number. (571) 555 – 0022 should not read (571) 555 – 22 with the zeros missing.

THANK YOU FOR YOUR TIME!!!




How to Generate Seeded 2D White Noise

I am trying to write a function so that f(x, y, seed) returns some float between 0.0 and 1.0. x and y are two floats, and the seed would be an integer. The result should look like a random number, but using the same arguments will always return the same result. I am planning to use this for terrain generation (using Perlin Noise), but the effect should be that white noise could be created from a given seed (with the x and y arguments corresponding to positions in the image).

I have looked into using hash functions to achieve this, but all of the ones I have come across either don't accept floats, don't produce uniform results (so that each number between 0.0 and 1.0 is equally likely), show an obvious pattern, or the result doesn't change much for close co-ordinates)




Random sampling with Hypothesis

In Hypothesis, there is an corresponding sampled_from() strategy to random.choice():

In [1]: from hypothesis import find, strategies as st

In [2]: find(st.sampled_from(('ST', 'LT', 'TG', 'CT')), lambda x: True)
Out[2]: 'ST'

But, is there a way to have random.sample()-like strategy to produce subsequences of length N out of a sequence?

In [3]: import random

In [4]: random.sample(('ST', 'LT', 'TG', 'CT'), 2)
Out[4]: ['CT', 'TG']




JavaScript Get a Random Image in a for loop

So I created a for loop which creates (determining on a textfield) a number of images.

E.g. I type "23" in the textfield and on a button click it displays 23 images randomly placed on the screen.

for(i=0; i < box2; i++) {

     this.y = Math.floor(Math.random() * 100) + 1;
     this.x = Math.floor(Math.random() * 100) + 1;

     this.img = document.createElement("img");
     this.img.src = sourceArray[num];
     this.img.setAttribute("height", "100px");
     this.img.style.position = "absolute";
     this.img.style.top = this.y + "vh";
     this.img.style.left = this.x + "vw";
     this.img.addEventListener("click", Remove);

     document.getElementById("bildausgabe").appendChild(this.img);

}

I also already have an array to pick 1 out of 3 random images which works fine, but it will only display 1 of the 3 for all images. When I reload it will pick another one from the list.

 var sourceArray = ["strand.jpg","weg.jpg","haengematte.jpg"];
 var num = Math.floor(Math.random() * 3);

How can I change it that it displays all 3 images randomly?

e.g. I type "12", click the button and get 12 images randomly from the given 3 sources.




How to convert string to UInt32?

I am a beginner in swift and I am having a problem with convering string to UInt32.

   let Generator = (ReadableJSON ["People"] [Person]["F1"].string! as NSString).doubleValue

    if Generator == 1 {

        NameLabel1 = ReadableJSON ["People"] [Person]["A1"].string as String!
        NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String!
        Picture = ReadableJSON ["People"] [Person] ["E1"].string as String!

    } else {

         let RGen = arc4random_uniform ("\(Generator)")

    }

Would you advise me how to fix it. The problem is in the last line, which is red and it says Cannot convert value of type String to UInt32. The main idea is that I am reading the number from a JSON file and I have to populate this number into the arc4random_uniform.




R Generate Bounded Random Sample Arround Specific Mean

I've been stuck with this for a while, so I decided to write a question.

Problem: How to generate a random sample (of lenght n) with a lower/upper bound and arround a specific mean.

Observation: distribution doesn't need to be specific (it could be normal, beta, etc).

Aproaches considered:

  • One aproach is to use the rtnorm function (package msm) which generates a random numbers with a normal distribution within specified bounds but it doesn't hold your wanted mean value.
  • A second aproach I've tried is this function which I found in a question I can't find anymore

    rBootstrap<-function(n,mean,sd,lowerBound,upperBound){
      range <- upperBound - lowerBound
      m <- (mean-lowerBound) / range #mapping mean to 0-1 range
      s <- sd / range #mapping sd to 0-1 range
      a <- (m^2 - m^3 - m*s^2)/s^2 #calculating alpha for rbeta 
      b <- (m-2*m^2+m^3-s^2+m*s^2)/s^2 #calculating beta for rbeta
      data <- rbeta(n,a,b)  #generating data
      data <- lowerBound + data * range #remaping to given bounds
      return(data)
    }
    
    

    this function actually gives great results unless: upperBound > lowerBound + (2* mean - lowerBound) (upper bound exceeds two times the distance from the lowerBound to the mean).

Particularly, I would like to generate a random sample of lenght 1,800, with values between 50,000 and 250,000 with mean value = 70,000.




C - Generate random array with no repeats without shuffling

I want to generate an array of 1,000,000 integers without repeats without shuffling. This means that I don't want to do:

int arr[1000000];
for (int i = 0; i < 1000000; i++)
{
    arr[i] = i; 
}
shuffle(arr);
shuffle(arr);
// Done.

I want to figure out a way how to do it without using that technique. I also don't want to randomly select an index between 1 and 1,000,000 because at number 999,999 there would be only a 1/1,000,000 chance to continue.

I've been trying to think of a solution and I think the key is parallel arrays and looping backwards then using modulus to limit only to the indexes that you haven't already been to, but then I can't guarantee that the value I get is unique. I don't want to use a HashSet or TreeSet implementation as well.




Random name without repeating it self

Please tell me, what is my mistake here:

$myarrayofnames = ["Tisha","Vesta","Josphine"];
$randompick = array_rand($myarrayofnames,1);
if($myarrayofnames[$randompick] === "Tisha") {
  $myarrayofnames = ["Vesta","Josphine"];
  return $mymyarrayofnames[$randompick];
}
elseif($myarrayofnames[$randompick] === "Vesta") {
  $myarrayofnames = ["Tisha","Josphine"];
  return $mymyarrayofnames[$randompick];
}
elseif($myarrayofnames[$randompick] === "Josphine") {
  $myarrayofnames = ["Tisha","Vesta"];
  return $mymyarrayofnames[$randompick];
}

What I'm trying to do is to pick a random name and make sure the next random name won't be the same as it is now.




How does MD5 hashing not run out of hashes?

If I am not mistaken, MD5 is a randomized hash 32 chars long. If MD5 is only 32 chars long and we can make a string infinitely long, how is every hash different? what is the upper limit of MD5 and how exactly is it completely unpredictable?




Random value options

I want to pick some value from array randomly, but I'm not sure about best way to do it(in terms of performance etc). I'm only a beginner, so I don't know many ways to random values and don't know how they affect performance and exact differences of them. For example: "mt_rand" is four times faster than "rand" function.

If I have this array of names:

$myarrayofnames = ["Marcelle","Caroll","Kristina","Tisha","Filomena","Vesta","Josphine"];

And I want to pick from them, what are my options?




Python random while multiple conditions

Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:

import random

a = 0
b = 0
c = 0

while a < 190 and b < 140 and c < 110: # <-- This condition here
    a = 0
    b = 0
    c = 0

    for i in range(1, 465):
        v = random.randint(1, 3)

        if v == 1:
            a = a + 1
        elif v == 2:
            b = b + 1
        else:
            c = c + 1

    result = ""
    result += "a: " + str(a) + "\n"
    result += "b: " + str(b) + "\n"
    result += "c: " + str(c) + "\n"

    print (result)

I want to loop this until a is above 190 AND b above 140 AND c above 110 but it stops everytime after the first run.

Can someone help me there?




Initialize RcppZiggurat RNG-Generator on snow cluster

I'm trying to use the RNG of the package RcppZiggurat on a snow cluster. To seed the RNG on each node, I use L'Ecuyer's algorithm built into clusterSetupRNG. However, the sequence of random numbers turns out to be the same on each node. The result of the code stays exactly the same even if I run it without the clusterSetupRNG-command.

Here's what I tried:

library(RcppZiggurat)
library(snow)

myFun <- function(i){
    rn <- zrnormLZLLV(10)
    return(rn)
}

nodes <- rep("localhost",2)

cl <- makeCluster(nodes, type="SOCK")
vars <- list("zrnormLZLLV")
clusterExport(cl=cl,list=vars,envir=environment())
clusterSetupRNG(cl=cl,type="RNGstream")

res <- parLapply(cl,c(1,2,3,4),myFun)
res 

Does anybody have an idea how I can make this work? Of course I could always resort to the standard RNG rnorm, but it would be nice to have the speed of RcppZiggurat also on a cluster.

Thanks a lot for your help!




how to use random string to let or var to url link

how to use random string to let or var to url link i want to make random string for url let url = URL(string:"http://ift.tt/2cHKHHt")

or see the code when i change values in the site linke in the app do not changed,but if i chnage name of url it change the code not reload if i change the value in json and keep same file if i want to reload i have to change the name of file how to do some thange auotmatic change the url and keep the orginal in the ftp server

import Foundation


class Episode
{
    var title: String?
    var description: String?
    var thumbnailURL: URL?


    var url: URL?
    var episodes = [Episode]()

    init(title: String, description: String, thumbnailURL: URL, createdAt: String, author: String)
    {
        self.title = title
        self.description = description
        self.thumbnailURL = thumbnailURL


    }

    init(espDictionary: [String : AnyObject])
    {
        self.title = espDictionary["title"] as? String

       // description = espDictionary["description"] as? String
        thumbnailURL = URL(string: espDictionary["thumbnailURL"] as! String)


        self.url = URL(string: espDictionary["link"] as! String)
    }

    static func downloadAllEpisodes(completion: @escaping ([Episode]) -> ()) {
        var episodes = [Episode]()

        let url = URL(string:"http://ift.tt/2cHKHHt")


        URLSession.shared.dataTask(with: url!) { (data, response, error) in

            if error != nil {
                print(error)
                completion(episodes)
            }
            else {
                if let jsonData = data ,let jsonDictionary = NetworkService.parseJSONFromData(jsonData) {

                    let espDictionaries = jsonDictionary["episodes"] as! [[String : AnyObject]]
                    for espDictionary in espDictionaries {

                        let newEpisode = Episode(espDictionary: espDictionary)
                        episodes.append(newEpisode)


                    }
                }
               completion(episodes)

                DispatchQueue.main.async(execute: {
                    completion(episodes)
                })


            }

            }.resume()
    }

    func randomString(_ length: Int) -> String {

        let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let len = UInt32(letters.length)

        var randomString = ""

        for _ in 0 ..< length {
            let rand = arc4random_uniform(len)
            var nextChar = letters.character(at: Int(rand))
            randomString += NSString(characters: &nextChar, length: 1) as String
        }

        return randomString

    }


}




jeudi 22 septembre 2016

R: How to randomly sample from each row of matrix into new column but only switch columns with rng

I'm new to R and I'm having difficulty finding answers to my question. I found this question that was asked years ago which leads me in the right direction: R: How to add a column with a randomly chosen value from each row of a matrix?

The difference in mine is that I want to build the third column with conditional sampling while randomly choosing which one to start with. If I have two columns in my matrix, I want to 1. randomly pick which column to start sampling from and 2. only switch columns if I run an rng and it falls below a certain threshold. I want to be able to run the rng before sampling each row.

I haven't been able to find much in the way of help and that might be a consequence of just not knowing what to look for. Thank you.




Random object won't generate for java.util.Random

this is my first post. I am relatively new to java and so I am working on a basic graphics program which creates a circle bouncing off the edge of the screen.

I am currently facing issues with the java.util.Random class, as occasionally the values it generates don't display the circle on the screen. The other issue is that my circle won't bounce off the walls. Here is my code: import java.awt.*; import java.util.Random;

/**
* MyArtwork
* Inspired by a lab from Jeff Ondich
* @author Dave Musicant
* @version 3.0
*
*/

class Graph
{
    public static void main(String[] args)
    {
        Random rand= new Random(); //sets up random
        int windowWidth = 2560;//sets width of window
        int windowHeight = 1600;//sets height of window
        int circplacex = rand.nextInt(2510);//sets xloc of initial circle
        int circplacey = rand.nextInt(1650);// sets yloc of initial circle
        int circspeedx = 1;// sets speed of circle
        int circspeedy = 1;
        int change1 = 1;//sets color change amount
        int change2 = 1;
        int change3 = 1;
        int x = 5;
        Canvas canvas = new Canvas("Hi there");//sets up canvas.
        canvas.setSize(windowWidth,windowHeight);
        canvas.setVisible(true);
        int color1 = rand.nextInt(256);
        int color2 = rand.nextInt(256);//creates random colors
        int color3 = rand.nextInt(256);
        while (x == 5){//infinite loop
            if(color1 == 255){
                change1 = -1;
            }
            if(color2 == 255){//changes color if to high
                change2 = -1;
            }
            if(color3 == 255){
                change3 = -1;
            }
            if(color1 == 0){
                change1 = 1;
            }
            if(color2 == 0){//changes color if too low
                change2 = 1;
            }
            if(color3 == 0){
                change3 = 1;
            }
            color1 = color1 + change1;
            color2 = color2 + change2;
            color3 = color3 + change3;
            canvas.fillBackground(Color.black);//clears screen
            Color fun = new Color(color1,color2,color3);
            canvas.setInkColor(fun);
            canvas.fillOval(circplacex,circplacey,50,50);//makes circle
            circplacex = circplacex + circspeedx;//moves circle by speed
            circplacey = circplacey + circspeedy;
            if(circplacex == 2510){//should make it bounce
                circspeedx = circspeedx*-1;
            }
            if(circplacey == 1550){
                circspeedy = circspeedy*-1;
            }
            if(circplacex == 0){
                circspeedx = circspeedx*-1;
            }
            if(circplacey == 0){
                circspeedy = circspeedy*-1;
            }
            canvas.wait(10);
        }
        }
            }




Swift: Getting EXC_BAD_INSTRUCTION when trying to append random array elements

I am getting the error, "Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)" when trying to append random array elements into a new array.

The debug log says "fatal error: Index out of range"

//If there are more than 6 players prioritizing the event, make a random choice. garudaLocations is an array containing the players who prioritized the event "Garuda".

    if garudaLocations.count > 6 {

        var finalGarudaPlayers : [Int] = []
        let getRandom = randomSequenceGenerator(1, max: garudaLocations.count) //Tell RNG how many numbers it has to pick from.
        var randomGarudaPrioritiesIndex = Int()
        for _ in 1...6 {
            randomGarudaPrioritiesIndex = getRandom() //Generate a random number.
            finalGarudaPlayers.append(garudaLocations[randomGarudaPrioritiesIndex]) //ERROR: Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)
        }
        debugPrint(finalGarudaPlayers) //Print array with the final priority Garuda members.

randomSequenceGenerator is a function I got from here, which does work to generate the random numbers.

 func randomSequenceGenerator(min: Int, max: Int) -> () -> Int {
    var numbers: [Int] = []
    return {
        if numbers.count == 0 {
            numbers = Array(min ... max)
        }

        let index = Int(arc4random_uniform(UInt32(numbers.count)))
        return numbers.removeAtIndex(index)
    }
}

To get a better understanding, I am trying to write a piece of a "team making" program where players are automatically sorted into events, but they can choose which events they would like to prioritize.

I can only have 6 people per event, however, so the goal is to take the existing garudaLocations array, choose a random 6 index locations, and get rid of the rest of the players.

I get the error only after I submit more than 6 players to the same event.

Any help is very much appreciated!




Looking to randomly select, concatenate string of text stored in variable

Problem

In my scripts.js the variable var fullURL = not getting the actual text to be tweeted out in the teaser1, teaser2 and teaser3 that I've stored in a variable. I basically want one of the three teasers to be randomly selected when people click fa-twitter

scripts.js

function shareTeam(){
    $(".fa-twitter").click(function(){

         // Grabs the names of all the players in the span
         // Sets a variable marking the indexOf each of the names
         // If the index doesn't find a space, it returns -1, which returns the full name
         // Otherwise it will return only what follows the space
         var lastNames = $("li span").map(function() {
           var name = $(this).text();
           var index = name.indexOf(" ");
           return index == -1 ? name : name.substring(index + 1);
         }).get();
         console.log(lastNames);

        var regularNames = lastNames.slice(0, 3); // Same as below, but no shuffling

        regularName1 = regularNames[0]; // Forward
        regularName2 = regularNames[1]; // Forward
        regularName3 = regularNames[2]; // Defenseman

        // Find me a random number between 1 and 3
        // Where 1 is the start number and 3 is the number of possible results
        var teaser = "teaser";
        var rand = Math.floor(Math.random() * 3) + 1;
        console.log(rand);

        // Concatenate the two strings together
        teaseRand = teaser.concat(rand);

        // These are the components that make up that fullURL
        var baseURI = "https://twitter.com/intent/tweet?url=";
        var twitterUsername = "stltoday";
        var interactiveURL = "http://graphics.########.com/STLblues";

        // Randomly generate one of three teasers
        var teaser1 = regularName3 + " to " + regularName2 + " back to " + regularName1 + " — GOAL! Create your own all-team #STLBlues team: ";
        var teaser2 = "I picked my #STLBlues dream team. See which players I've chosen and build your own: ";
        var teaser3 = "My #STLBlues team will skate circles around yours! Pick your team: ";

        // This is the full url that will be switched in and out
        // var fullURL = baseURI+interactiveURL+"&via="+twitterUsername+"&text="+teaseRand;
        var fullURL = baseURI+interactiveURL+"&via="+twitterUsername+"&text="+teaseRand;

        // It needs to be encoded properly as well
        var encodedURL = encodeURIComponent(fullURL)
        console.log(fullURL);
        console.log(encodedURL);



        // Change the href to the link every time the Twitter button is clicked
        var changeLink = $("link--twitter").attr("href", encodedURL);

        // if (lastNames.length === 6) {

        // } else {
        //     // Generic teaser
        //     var teaser4 = "Pick your #STLBlues dream team from 50 of the best @StLouisBlues to hit the ice: " + interactiveURL + " (via @stltoday)";
        // }
    });
}




How to remove a value from an external text file if it is used PHP

I was just wondering if it is possible to remove a value from an external .txt file once it is randomly chosen.

// Opens file with key values
$randomkeys = file('keys.txt');

// Takes keys from file and puts it into an array
$random_keys = array_rand($randomkeys, 2);

// Outputs the random key chosen
echo "Your code is: ";
echo $randomkeys[$random_keys[0]];

This is the code I am currently using and it works by reading the file that includes all the keys and then it is put into an array that would later be shown to the user that is using the site.

Screenshot of keys.txt file contents

What I want to add to this is that when the user views the site that the key shown to them will be removed from the list so no one else can get that same key.




Simple, random encounters in a python text-adventure.. I´m stuck

i recently started simple coding with python 3 and i´m stuck with a simple problem:


import random

def enemy_bandit01():
     bandit01 = {'race': 'human', 'weapon': 'a sword'}

def enemy_orc01():
     orc01 = {'race': 'orc', 'weapon': 'a club'}

def enemy_wolf01():
     wolf01 = {'race': 'wolf', 'weapon': 'claws'}

encounter_choice = [enemy_bandit01, enemy_orc01, enemy_wolf01]

print('You fight against a ____. He has ____!')


I simply want python to pick a random enemy_x - function and then print out a text which includes the race/weapon etc.. without writing a new text for every enemy.

I am aware that this is a noob question, but i was not able to figure this out by myself.

Greetings, BobJohn :)




C# Poker Game, Duplication issue [duplicate]

This question already has an answer here:

I'm doing a Poker Game but I've a problem with the random distribution of cards how can i get always a different number from a

for(int i = 0; i <= 4; i++)
{ 
    A = R.Next(1, 53); 
    // Other code
}




Guessing Game in C# where User selects Max value

I have been tasked in my class to create a random number generating guessing game using c# and do/while, if/else loops. This task seems easy enough; however, I am running into problems because I am supposed to start the game by prompting the user to "Enter a max value you want to guess from". I cannot get my program to work properly, as every time I run it, no matter what value I enter it says to "select a value between 1 and 0"

I have attached my exe.

Thanks in advance !!

        Random generator = new Random();
        bool truth = true;
        int MaxRange = Convert.ToInt32(truth); ;
        int userguess = 0;
        int outputnumber = generator.Next(MaxRange);

        do
        {
            Console.WriteLine(" Enter a max number you want to guess from!", MaxRange);
            Console.ReadLine();

            Console.WriteLine("please make a guess between 1 and {0}", outputnumber);

            if (userguess != outputnumber)
            {
                userguess = Convert.ToInt32(Console.Read());

                if (userguess < outputnumber)
                {
                    Console.WriteLine("That is not correct, Guess again");
                    Console.ReadLine();

                }
                if(userguess > outputnumber)
                {

                    Console.WriteLine("That is not correct, Guess again");
                    Console.ReadLine();
                }

                else if (userguess == outputnumber)
                {

 console.writeline("That is correct, the number is {0}, outputnumber);

                }
            }

        } while (truth == false);






        }
    }
}




Prepend a random number to pairs of files

I have in a folder, pairs of files, mp4 and srt subtitle files. e.g. video1.mp4 video1.srt video2.mp4 video2.srt I want to prepend a random number to each video file but I must also prepend the same number to the set file. Does anyone know how I can do this? I'm using a mac, so it could be a bash script, automator, or even PowerShell.




A roll dice returns the same value to both

I built a simple class:

class Die
{
    //Vars

    int number;
    Random R = new Random();

    //Buliding Command

    public Die ()
    {
        number = R.Next(1, 7);
    }

    // Roll
    public void Roll()
    {
         R = new Random();
        number = R.Next(1,7);
    }

    // Get Number

    public int GetNum()
    {
        return number;
    }
}

But whenever I write 2 Dices, it gives the same value to both of them when rolling:

static void Main(string[] args)
{
    Die Dice1 = new Die();
    Die Dice2 = new Die();

    while (Dice1.GetNum() != 6 && Dice2.GetNum() != 6)
    {
        Dice1.Roll();
        Dice2.Roll();
        Console.WriteLine("Dice 1: "+Dice1.GetNum()+"     Dice 2: "+Dice2.GetNum());
    }


    Console.ReadKey();
}

What I get in return is that Dice1 and Dice2 is ALWAYS equal to each other after rolling:

Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 1 Dice 2: 1 Dice 1: 6 Dice 2: 6




select randomly from string array without repetitions

Good day I have some problem regarding selecting a random string from my string array I am currently developing a guessing word game. this is my string array:

 string[] movie = {"deadpool", "batmanvssuperman", "findingdory", "titanic", "suicidesquad", "lordoftherings", "harrypotter", "jurassicpark", "hungergames", "despicableme" };

while this is the process in selecting a random string to my array, what should i do next, because I want to select the string not repeated. e.g when the program starts it will select a string then when i select random string again i want to not select the previous word that i've already selected previously.

string word = movie[r.Next(0, movie.Length)].ToUpper();

Thank you for immediate response! Have a nice day.




Java Random Number with seed changes after a day

I was using the code below to generate random number with seed so that I can generate back the same results next time.

int seed = 100;    
Random rand = new Random(seed);

I manage to get back the same results from the program on the same day, but after a day or two i get a completely different results. Is there a problem of the way I implement the random seed? Anyone encounter this before?




Randomize background image using button onClick event

I want to randomize the background image when the user clicks a button.

Here's what I have.

Every time the button at the bottom right is cliked, I want to randomize the background image from a set array of externally hosted images.

How can I achieve that? (Without PHP, if possible.)