lundi 31 octobre 2016

Regex Python - Modify random generated string

I need to read from file, two strings, one 'static' string from file, and one random dynamically generated one, which is also written on a file.

Then, replace one character in the random generated string with another random one.

And repeat the process. Until I get the "static" string which is on a file, in this case "THIS IS A STRING".

I'm pretty lost trying to achieve this, this is what I have so far:

import string
import random
import os
import re

file = open('file.dat', 'r')
file=file.read().split(',')
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

if os.path.exists('newfile.txt'): os.remove('newfile.txt') else: file = open("newfile.txt", "w") file.write(id_generator()) file.close() if re.search(r"THIS IS A STRING", file): print("success!")

I'm trying to achieve this with re module, since it should read character by character, finding it's position in the random generated string.

Not just comparing but also finding the position of the matching characters (if any)

The file.dat file contains the THIS IS A STRING string, which I call the 'static' one, it doesn't changes, it should be matched by the random generated ones process .

The newfile.txt prints the random generated string.

So, in a nutshell, how can I read the string on file.dat character by character, and same goes for the random generated string on newfile.txt?

I hope I've explained myself.




Prevent ZMQ c++ from calling rand()

I am using ZMQ 4.1.2 on Ubuntu 10.04.5 LTS.

I have a c++ program that seeds srand() with a fixed number, and then calls rand() ~100k times and exists. I found that I was getting different random numbers when re-running the same program twice.

If I have a ZMQ socket open before I start my 100k draws it seems like the ZMQ library itself is calling rand() and messing up my repeatability.

this->context = new zmq::context_t(1);
this->socket = new zmq::socket_t(*this->context, ZMQ_PUB);
socket->connect("tcp://localhost:5556"); // offending line

All I need to do is omit calling socket->connect() and my calls to rand() behave deterministically.

Is this a bug (feature) in ZMQ? Or does this also happen with the underlying TCP socket?




How can I generate a random number greater or less than a previous random number?

I am currently in a Java 1 class, and made a number guessing game for fun. Basic take input, tells you if it's too high or low, then lets you guess again. I thought it would be interesting to make it so the computer guesses as well, then compares your guesses to its. I have all of the generation and comparing working, but it continues to guess numbers without taking the greater/less than into account, which I want to add. I have:

    public static void autoPlay(int num){
    Random rand = new Random();
    int guess1 = rand.nextInt(100) + 1;
    int counter = 0;
    while(guess1 != num){
        counter++;
        int guess = rand.nextInt(100) + 1;
        int initialHigh = 100;
        int initialLow = 0;
        // I want it to guess smart and recognize if it were too high or too low, and generate a number between there

        if(guess1 > num){   
            int newGuess = rand.nextInt(initialHigh - guess1) + 1;
        }else if(guess1 < num){
            int newGuess2 = rand.nextInt(initialLow + guess1) + 1;
        }
        initialLow = guess;
        initialHigh = guess;
        guess1 = guess;
        System.out.printf("%3d", guess1);
    }
    System.out.println("It took " + counter + " guesses to get the correct number");
}

I can't tell what is wrong with my math in the if statement, or if theres just something I can call to do that.




Python : How to hash strings into a float in [0:1]?

I have a dataset with multiple strings.

I want to associate each of these strings to a float, "randomly" distributed in the [0;1] range.

=> I am looking for myfunction. myfunction is expected to give me a float between 0 and 1, for each of my strings. Examples :

myfunction(string_1) = 0.26756754
myfunction(string_2) = 0.86764534

NB : random() does not fulfill my need because it does not take any string as input / deterministic parameter. I am looking for something more like a hash function




Position images randomly and avoid overlapping with wordpress plugins

I am trying to randomly position thumbnail images on an CPT archive-page on wordpress. The images should not overlap. Also, the z-index in not really working (the images should go behind all other elements. I cannot use pluggins.

The content is dynamically generated through a php document. I am trying to do it like this:

<?php if ( has_post_thumbnail() ) : ?><div class="js-container bottomdrag">
<script type="text/javascript">

$( document ).ready(function() {       
$('.js-container a').each(function() { 
    var height = window.innerHeight/2;
    var width = window.innerWidth/2;
//This var top should provide a scroll so that the user gradually finds the images
    var top = Math.floor(Math.random() * (($(window).height() * 3) - height)); 
        var left = Math.floor(Math.random() * 55);
    $(this).css({
        "z-index":"-999",
        "top": top,
//this margin-bottom is there to allow some space after the last image so that the user can scroll it
        "margin-bottom":"30" + "vh", 
        "left": left  + "vw", 
        "position":"absolute", 
        "display":"block",
    }); 

});

});
</script>
 <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail(); ?></div> <!--end of js-container-->

Would you be able to light my way? Here is the page: http://ift.tt/2dCivKL




Using text file separated with comma for get Random phrases

I want add my personal blog one random message when one user visit at first time the blog or when refresh the site, I'm using a text file (separated by a comma) with the following content:

Hello! Welcome,have a nice day,the best it's be happy!

I have added to my page the following code:

<?php include('message.php');?>

content from my message.php:

    $text = file_get_contents('./saludo/hola.txt');
    $textArray = explode(",", $text);
    $randArrayIndexNum = array_rand($textArray);
    $saludo = $textArray[$randArrayIndexNum];

the problem is that when i use this show all messages:

Hello! Welcome,have a nice day,the best it's be happy!

and i want to show only 1 message:

Hello! Welcome

how could I fix this and display only a message and using a comma.

Regards!.




How to generate random numbers from defined ranges in R

I want to generate random numbers in R. Say I have some ranges:

20  3293601
3295601 3653454
3655454 3877785
3879785 4454406
4456406 4772139
4774139 4948406
4950406 5188645
5190645 5641009
5643009 5731188
5733188 5993268...

Definitely, I can first generate sequences of this ranges by seq(start, end) and append all these sequences together. Then I can use sample(sequences, n) to generate random numbers. But the thing is I have many of these ranges, say I have thousand ranges, so it is not very feasible to generate all these sequences. Is there any faster way to generate random numbers in these ranges in R?




Restricting the rand function in C

How do I generate a random number in a range? i have to generate a random number from 0-5 using the rand() function and mod math (%) to get those numbers




Score not increasing after new random array variable is read (Java) - Android Studio

There's a game with 9 colored squared. A random one of those colors is displayed on the screen, in one of those 9 colors (e.g: 'orange' in green). The user scores a point when they tap the colored square which corresponds with the word, ignoring the color of the word (e.g if 'orange' in any color and orange square is tapped, one point is added to score). All these color strings are stored in an array (colorString[]). When the score reaches 10, I introduce new values to the colorString array in the onClick method of each button. The values are ciphered versions of each color string. The issue is, even when the right color boxed is tapped for the ciphered value, the score goes no higher than 10. The newer array values are not working. All is explained in the code below:

int score = 0;
Random colStr = new Random();
int decider = colStr.nextInt(9);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game3);


    final Button greenButton;
    greenButton = (Button) findViewById(R.id.greenButton);

    final Button yellowButton;
    yellowButton = (Button) findViewById(R.id.yellowButton);

    final Button blueButton;
    blueButton = (Button) findViewById(R.id.blueButton);

    final Button blackButton;
    blackButton = (Button) findViewById(R.id.blackButton);

    final Button orangeButton;
    orangeButton = (Button) findViewById(R.id.orangeButton);

    final Button brownButton;
    brownButton = (Button) findViewById(R.id.brownButton);

    final Button whiteButton;
    whiteButton = (Button) findViewById(R.id.whiteButton);

    final Button purpleButton;
    purpleButton = (Button) findViewById(R.id.purpleButton);

    final Button redButton;
    redButton = (Button) findViewById(R.id.redButton);


final Button loseStarter3;

    loseStarter3 = (Button) findViewById(R.id.Starter3);
    loseStarter3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            infoG3.setVisibility(View.GONE);
            loseStarter3.setVisibility(View.GONE);
            final TextView word = (TextView) findViewById(R.id.word);
            word.setVisibility(View.VISIBLE);
            greenButton.setVisibility(View.VISIBLE);
            purpleButton.setVisibility(View.VISIBLE);
            blueButton.setVisibility(View.VISIBLE);
            blackButton.setVisibility(View.VISIBLE);
            redButton.setVisibility(View.VISIBLE);
            whiteButton.setVisibility(View.VISIBLE);
            brownButton.setVisibility(View.VISIBLE);
            orangeButton.setVisibility(View.VISIBLE);
            yellowButton.setVisibility(View.VISIBLE);

                final String[] colorString = new String[9];
                colorString[0] = "yellow";
                colorString[1] = "red";
                colorString[2] = "green";
                colorString[3] = "black";
                colorString[4] = "white";
                colorString[5] = "purple";
                colorString[6] = "blue";
                colorString[7] = "brown";
                colorString[8] = "orange";
                word.setText(colorString[decider]);

                int[] androidColors = getResources().getIntArray(R.array.androidcolors);
                int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
                word.setTextColor(randomAndroidColor);

                yellowButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (word.getText() == colorString[0] || word.getText() == colorString[9] || word.getText() == colorString[10] || word.getText() == colorString[11]) {
                            score++;
                        }
                        Random colStr = new Random();
                        if (score<=9) {
                            int decider = colStr.nextInt(9);
                            final String[] colorString = new String[9];
                            colorString[0] = "yellow";
                            colorString[1] = "red";
                            colorString[2] = "green";
                            colorString[3] = "black";
                            colorString[4] = "white";
                            colorString[5] = "purple";
                            colorString[6] = "blue";
                            colorString[7] = "brown";
                            colorString[8] = "orange";
                            word.setText(colorString[decider]);
                        }
                        if (score>9) {
                            int decider = colStr.nextInt(27)+9;
                            final String[] colorString = new String[36];
                            colorString[0] = "yellow";
                            colorString[1] = "red";
                            colorString[2] = "green";
                            colorString[3] = "black";
                            colorString[4] = "white";
                            colorString[5] = "purple";
                            colorString[6] = "blue";
                            colorString[7] = "brown";
                            colorString[8] = "orange";
                            colorString[9] = "weyoll";
                            colorString[10] = "loyelw";
                            colorString[11] = "oelwyl";
                            colorString[12] = "erd";
                            colorString[13] = "der";
                            colorString[14] = "edr";
                            colorString[15] = "enrge";
                            colorString[16] = "regne";
                            colorString[17] = "nerge";
                            colorString[18] = "lcbka";
                            colorString[19] = "alkcb";
                            colorString[20] = "cbakl";
                            colorString[21] = "ihewt";
                            colorString[22] = "thewi";
                            colorString[23] = "ewthi";
                            colorString[24] = "relppu";
                            colorString[25] = "ulrpep";
                            colorString[26] = "leprpu";
                            colorString[27] = "ebul";
                            colorString[28] = "lbeu";
                            colorString[29] = "ulbe";
                            colorString[30] = "rbwno";
                            colorString[31] = "wobnr";
                            colorString[32] = "onwrb";
                            colorString[33] = "agonre";
                            colorString[34] = "negrao";
                            colorString[35] = "greaon";
                            word.setText(colorString[decider]);
                        }

                        int[] androidColors = getResources().getIntArray(R.array.androidcolors);
                        int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
                        word.setTextColor(randomAndroidColor);
                    }
                });

                redButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (word.getText() == colorString[1]) {
                            score++;
                        }
                        Random colStr = new Random();
                        if (score<=9) {
                            int decider = colStr.nextInt(9);
                            final String[] colorString = new String[9];
                            colorString[0] = "yellow";
                            colorString[1] = "red";
                            colorString[2] = "green";
                            colorString[3] = "black";
                            colorString[4] = "white";
                            colorString[5] = "purple";
                            colorString[6] = "blue";
                            colorString[7] = "brown";
                            colorString[8] = "orange";
                            word.setText(colorString[decider]);
                        }
                        if (score>9) {
                            int decider = colStr.nextInt(27) + 9;
                            final String[] colorString = new String[36];
                            colorString[0] = "yellow";
                            colorString[1] = "red";
                            colorString[2] = "green";
                            colorString[3] = "black";
                            colorString[4] = "white";
                            colorString[5] = "purple";
                            colorString[6] = "blue";
                            colorString[7] = "brown";
                            colorString[8] = "orange";
                            colorString[9] = "weyoll";
                            colorString[10] = "loyelw";
                            colorString[11] = "oelwyl";
                            colorString[12] = "erd";
                            colorString[13] = "der";
                            colorString[14] = "edr";
                            colorString[15] = "enrge";
                            colorString[16] = "regne";
                            colorString[17] = "nerge";
                            colorString[18] = "lcbka";
                            colorString[19] = "alkcb";
                            colorString[20] = "cbakl";
                            colorString[21] = "ihewt";
                            colorString[22] = "thewi";
                            colorString[23] = "ewthi";
                            colorString[24] = "relppu";
                            colorString[25] = "ulrpep";
                            colorString[26] = "leprpu";
                            colorString[27] = "ebul";
                            colorString[28] = "lbeu";
                            colorString[29] = "ulbe";
                            colorString[30] = "rbwno";
                            colorString[31] = "wobnr";
                            colorString[32] = "onwrb";
                            colorString[33] = "agonre";
                            colorString[34] = "negrao";
                            colorString[35] = "greaon";
                            word.setText(colorString[decider]);
                        }

                        int[] androidColors = getResources().getIntArray(R.array.androidcolors);
                        int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
                        word.setTextColor(randomAndroidColor);
                    }
                });

                greenButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (word.getText() == colorString[2]) {
                            score++;
                        }
                        Random colStr = new Random();
                        if (score<=9) {
                            int decider = colStr.nextInt(9);
                            final String[] colorString = new String[9];
                            colorString[0] = "yellow";
                            colorString[1] = "red";
                            colorString[2] = "green";
                            colorString[3] = "black";
                            colorString[4] = "white";
                            colorString[5] = "purple";
                            colorString[6] = "blue";
                            colorString[7] = "brown";
                            colorString[8] = "orange";
                            word.setText(colorString[decider]);
                        }
                        if (score>9) {
                            int decider = colStr.nextInt(27) + 9;
                            final String[] colorString = new String[36];
                            colorString[0] = "yellow";
                            colorString[1] = "red";
                            colorString[2] = "green";
                            colorString[3] = "black";
                            colorString[4] = "white";
                            colorString[5] = "purple";
                            colorString[6] = "blue";
                            colorString[7] = "brown";
                            colorString[8] = "orange";
                            colorString[9] = "weyoll";
                            colorString[10] = "loyelw";
                            colorString[11] = "oelwyl";
                            colorString[12] = "erd";
                            colorString[13] = "der";
                            colorString[14] = "edr";
                            colorString[15] = "enrge";
                            colorString[16] = "regne";
                            colorString[17] = "nerge";
                            colorString[18] = "lcbka";
                            colorString[19] = "alkcb";
                            colorString[20] = "cbakl";
                            colorString[21] = "ihewt";
                            colorString[22] = "thewi";
                            colorString[23] = "ewthi";
                            colorString[24] = "relppu";
                            colorString[25] = "ulrpep";
                            colorString[26] = "leprpu";
                            colorString[27] = "ebul";
                            colorString[28] = "lbeu";
                            colorString[29] = "ulbe";
                            colorString[30] = "rbwno";
                            colorString[31] = "wobnr";
                            colorString[32] = "onwrb";
                            colorString[33] = "agonre";
                            colorString[34] = "negrao";
                            colorString[35] = "greaon";
                            word.setText(colorString[decider]);
                        }

                        int[] androidColors = getResources().getIntArray(R.array.androidcolors);
                        int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
                        word.setTextColor(randomAndroidColor);
                    }
                });

                /*etc... for other buttons, same contents but different color name*/

I AM AWARE THAT I HAVE ONLY USED || OTHER ARRAY VALUES FOR YELLOW, THIS IS JUST AN EXAMPLE. I have also tried using individual if statements below the colorString[0] one to add scores when == to the other values, and else if. Neither worked, they just crashed the app. I've also tried different button, not that is should make a difference. I tried changing the order of where the if statement is, only to fail again. I've spent a while trying to resolve this, but have unfortunately not been able to resolve this.

Would appreciate it if someone could provide me with a fix, to ensure these other array values are accepted. If there is something I haven't made clear, all is shown in the code I have posted. Many thanks in advance.




Odd random number in range [1..99]

I want to fill an array with odd random numbers in a range [1..99].

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

const int N = 100;
int a[N];

void print(){
    for (int i=0; i<N; i++) 
        cout << a[i] << " ";
}

int main(){
    srand(time(NULL));
    int number;
    for (int i=0; i<N; i++) {
        number=(rand()%100)+1;
        if (number%2!=0)
            a[i]=number;
    }
    print();
}

When I use this code I receive:

0 7 0 0 29 0 0 93 0 0 29 0 27 0 0 13 35 0 0 0 0 0 51 0 0 0 97 99 15 73 79 0 73 0 21 39 0 7 25 41 1 99 31 0 0 1 0 81 69 73 37 95 0 0 0 41 21 75 97 31 0 0 0 0 0 0 31 21 0 11 33 65 0 69 0 0 9 63 27 0 13 0 63 27 0 7 0 0 99 0 77 0 59 5 0 99 0 69 0 0

What is wrong with that? Why there are a lot of "0"?




Having trouble with java syntax

I want to create a Random class constant and use nextDouble to get a single random number between 0 and 1. I'm having trouble with the syntax to declare the constant.

public static final double (?) I've tried looking at Oracle but that confused me a bit.




Prediction random number java.util.Random

I would like a tip on how to predict random numbers in java.util.Random based on the previous numbers! What is the algorithm that generates the seeds and how do calculations?




Java random number with length, restrictions, characters and letters

Hi I'm new to Java and I'm trying to generate a random number 11-digit random number. How do you do this in this format "[xxx]-xxx#AxAxx" where the x is digits 0-9 and the A is any upper case letter. The brackets, dashes, and hash must be in the correct position too. Also the restriction is the last two digits can't be 5 or 6 and the first digit can't be 0. What's the best way to do this? Do you have to use a string and a random class? Thanks.




two dimensional array random generator jQuery

All rows always have same numbers, why? They should take random number to populate it. Also, how can I repair it? Once I saw answer here but now I cannot find it.

var mapSizex = 5;
var mapSizey = 6;
var mapArray = [];

$(function() {
  console.log("ready!");
  $('#map-draw').html(drawMap());
});

function mapGenerator() {
  for (i = 0; i < mapSizex; i++) {
    for (x = 0; x < mapSizey; x++) {
      mapArray[i, x] = getRandom(1, 5);
    }
  }
}

function drawMap() {
  mapGenerator();
  var map = '';
  tileID = 0;
  for (i = 0; i < mapSizex; i++) {
    map = map + '<br style="clear: both;">';
    for (x = 0; x < mapSizey; x++) {
      map = map + '<div class="tile tileID' + tileID + '">' + mapArray[i, x] + '</div>';
      tileID++;
    }
  }
  return map;
}

function getRandom(min, max) {
  var x = Math.floor((Math.random() * max) + min);
  return x;
}
.tile {
  float: left;
  height: 20px;
  width: 20px;
  border: 1px solid black;
  text-align: center;
}
<script src="http://ift.tt/1oMJErh"></script>
<div id="main-container">
  <div id="map-container">
    <div id="map-draw"></div>
  </div>
</div>

To post it I need to add some more content but all included information's should be enough to find what I mean.




C - Frequency of Randomly Generated Numbers

If I put i < 100 or i < 1000 in the for loop, it will generate 100/1000 numbers, respectively. However, when I put 10000, nothing appears when I run it, why is this?

int i;
int random_number;

srand((unsigned)time(NULL));

for (i = 0; i < 10000; i++) {
    random_number = (int) (10.0 * rand() / (RAND_MAX + 1.0));
    printf("%d", random_number);        
}

I have been tasked to tabulate the percentage of 10,000 (0-9) random numbers. So any help at all with further code for this would also be greatly appreciated.
(I am new to C and StackOverflow so I am still learning how to use both - so I apologise in advance if I have used either of them wrong!)

Thank you!




Image is not displayed correctly when user clicks on button

Functionality:

In page A, user needs to answer a question with 4 options. When user clicks on any 1 option, the current page will navigate the user to Page B where, an image will be displayed depending on the option that the user has chosen.

Therefore, this is the general flow:

Page A: 1 randomly generated question and 4 associated options to the question will be displayed -> user clicks on one of the option -> page A will navigate to page B. In page B, an image will be displayed depending on the option that you have selected in Page A.

What I have done:

I have created 3 arrays:

FOR Randomly Generated Questions:

var QuestionOrder = ["What is A?", "What is B?", "What is C?"];

FOR 4 options to the question shown:

var ChoiceOrder = [["test1", "test2", "test3", "test4"], ["test5", "test6", "test7", "test8"], ["test9", "test10", "test11", "test12"]];

Image to be shown in Page B depending on option selected in Page A:

var DescriptionOrder = [["testA1.png", "testA2.png", "testA3.png", "testA4.png"], ["testB1.png", "testB2.png", "testB3.png", "testB4.png"], ["testC1.png", "testC2.png", "testC3.png", "testC4.png"]];

Therefore, when user clicks on "test1", it should display ->"testA1.png" or when user clicks on "test12", it should display ->"testC4.png" or when user clicks on "test8", it should display ->"testB4.png" etc...

Code:

Plunker : http://ift.tt/2e5xvvN

Issue:

I am currently able to display the image element from the array var DescriptionOrder after the user has selected from Page A.

However, the issue that I am currently facing is this:

The wrong behaviour:

when I clicked on "test1", it is not displaying ->"testA1.png" but displaying -"testB4.png" or when user clicks on "test12", it is not displaying ->"testC4.png" but displaying -"testA2.png" or when user clicks on "test8", it is not displaying ->"testB4.png" but displaying -"testC2.png"etc...

The correct behaviour:

Therefore, when user clicks on "test1", it should display ->"testA1.png" or when user clicks on "test12", it should display ->"testC4.png" or when user clicks on "test8", it should display ->"testB4.png" etc...

Meaning, it looks like the array var DescriptionOrder is randomised and not associated based on the inner indices of the array.

What have i done wrong?? I need some help pls.

Thanks.




How to Use "random" function in DrScheme R5RS

I want to use a "random" function in DrScheme R5Rs but it says it does not exist. But it is possible to use in "Advanced student", I need to use it in R5RS, what is the way to do it? Thank you in advance!




R plot random graph with same structure

I'm creating a random graph in R with the igraph-library.

library(igraph)
g <- erdos.renyi.game(12, 0.25)
par(mfrow=c(1,2))
plot(g)
plot(g)

This creates the following plot:

random graph

As you can see, it creates two different plots - even given the same nodes and edges. How can I make R plot the same plots, so I can highlight some edges/nodes while having the same order.

The goal is to create a random network with some degree of probability that two nodes are connected by an edge (above example is p=0.25 for n=12 nodes). Then this graph is plotted with the nodes on the same spot (even if the node size variies) everytime I plot it.

How do I do this? Note that I'm not limited to g <- erdos.renyi.game(12, 0.25) - it just did the job with the random network quite well.




Generate Random number in javaScript

I need alert box to state..

the random number generated is and gives the number 0 to 9




dimanche 30 octobre 2016

Classifying output of Monte Carlo simulation

I am wondering what are the class of the outputs of Monte Carlo Simulation?

Is the answer : IID, Stationary, and Arbitrarily Stationary?

or Number, function, and Graph?

Is there any example of random number generator that is capable to generate a sample of the class?

Thank you so much for your help!




How to randomize data from JSON list to Jquery

How are you?

I am working on a Quiz and am trying to shuffle my JSON data to randomly show the questions of a quiz.

I retrieve the JSON data, then show the question to the user, I tried searching but only found something similar to this but couldn't get it working. (Actually couldn't understand how to use it.)

    numberOfQuestions[Math.floor( Math.floor(Math.random()*numberOfQuestions.length))];

Can you help me?

Here is the fiddle

JS:

         $(document).ready(function() {

              var questionNumber = 0;
              var wordNumber = 0;
              var questionBank = new Array();
              var wordsBank = new Array();
              var stage = "#game1";
              var stage2 = new Object;
              var questionLock = false;
              var numberOfQuestions;
              var score = 0;

              var data = {
                "quizlist": [

                  {
                    "question": "How much is two plus two?",
                    "option1": "Four",
                    "option2": "Five",
                    "option3": "Two",
                  }, {
                    "question": "Selecione a sentença correta",
                    "option1": "I am a person",
                    "option2": "I is a person",
                    "option3": "I are a person",

                  }, {
                    "question": "Select the correct form in the interrogative",
                    "option1": "Are you a student?",
                    "option2": "Is you a student?",
                    "option3": "You are a student?",

                  }, {
                    "question": "How much is one minus one?",
                    "option1": "Zero",
                    "option2": "Two",
                    "option3": "Four",
                  }, {
                    "question": "He / She / It usam o verbo To Be ...",
                    "option1": "is",
                    "option2": "are",
                    "option3": "am",
                  }, {
                    "question": "Selecione a frase correta na afirmativa",
                    "option1": "We are here.",
                    "option2": "Are we here.",
                    "option3": "We are not here.",
                  }, {
                    "question": "Selecione a forma correta na negativa",
                    "option1": "He is not here.",
                    "option2": "He is not here?",
                    "option3": "He are not here.",
                  }, {
                    "question": "You / We / They usam o Verbo To Be ...",
                    "option1": "are",
                    "option2": "am",
                    "option3": "is",
                  }

                ]
              };
              numberOfQuestions = data.quizlist.length;
              for (i = 0; i < numberOfQuestions; i++) {
                questionBank[i] = [];
                questionBank[i].push(data.quizlist[i].question);
                questionBank[i].push(data.quizlist[i].option1);
                questionBank[i].push(data.quizlist[i].option2);
                questionBank[i].push(data.quizlist[i].option3);
              }



              displayQuestion();
              //gtjson



              //Display question and word, if correct
              function displayQuestion() {


                var rnd = Math.random() * 3;
                rnd = Math.ceil(rnd);
                var q1;
                var q2;
                var q3;

                if (rnd == 1) {
                  q1 = questionBank[questionNumber][1];
                  q2 = questionBank[questionNumber][2];
                  q3 = questionBank[questionNumber][3];
                }
                if (rnd == 2) {
                  q2 = questionBank[questionNumber][1];
                  q3 = questionBank[questionNumber][2];
                  q1 = questionBank[questionNumber][3];
                }
                if (rnd == 3) {
                  q3 = questionBank[questionNumber][1];
                  q1 = questionBank[questionNumber][2];
                  q2 = questionBank[questionNumber][3];
                }

                //show the options
                $(stage).append('<div class="questionText">' + questionBank[questionNumber][0] + '</div><div id="1" class="option">' + q1 + '</div><div id="2" class="option">' + q2 + '</div><div id="3" class="option">' + q3 + '</div>');

                $('.option').click(function() {
                  if (questionLock == false) {
                    questionLock = true;
                    //correct answer
                    if (this.id == rnd) {
                      $(stage).append('<div class="feedback1">CORRECT</div>');
                      score++;
                    }
                    //wrong answer  
                    if (this.id != rnd) {
                      $(stage).append('<div class="feedback2">WRONG</div>');
                    }
                    setTimeout(function() {
                      changeQuestion()
                    }, 1000);
                  }
                })
              } //display question






              function changeQuestion() {

                questionNumber++;

                if (stage == "#game1") {
                  stage2 = "#game1";
                  stage = "#game2";
                } else {
                  stage2 = "#game2";
                  stage = "#game1";
                }

                if (questionNumber < numberOfQuestions) {
                  displayQuestion();
                } else {
                  displayFinalSlide();
                }

                $(stage2).animate({
                  "right": "+=800px"
                }, "slow", function() {
                  $(stage2).css('right', '-800px');
                  $(stage2).empty();
                });
                $(stage).animate({
                  "right": "+=800px"
                }, "slow", function() {
                  questionLock = false;
                });
              } //change question
            });



            //doc ready

Thanks!




Are pseudo random number generators less likely to repeat?

So they say if you flip a coin 50 times and get heads all 50 times, you're still 50/50 the next flip and 1/4 for the next two. Do you think/know if this same principle applies to computer pseudo-random number generators? I theorize they're less likely to repeat the same number for long stretches.

I ran this a few times and the results are believable, but I'm wondering how many times I'd have to run it to get an anomaly output.

def genString(iterations):
   mystring = ''
   for _ in range(iterations):
       mystring += str(random.randint(0,9))
   return mystring


def repeatMax(mystring):
    tempchar = ''
    max = 0
    for char in mystring:
            if char == tempchar:
                    count += 1
                    if count > max:
                            max = count
            else:
                count = 0
            tempchar = char
    return max


for _ in range(10):
    stringer = genString()
    print repeatMax(stringer)

I got all 7's and a couple 6's. If I run this 1000 times, will it approximate a normal distribution or should I expect it to stay relatively predictable? I'm trying to understand the predictability of pseudo random number generation.




Random string generation I/O python

I'm creating a python script which should create a new file every time it generates a new string (everytime the script is executed it prints out the string to file), and also compares this random string with a string which is a text like: THIS IS A STRING, which is located on another already created file.

For example, the string THIS IS A STRING is located on file called file.dat, and the random generated string should be written to a file, in this case I call it newfile.txt.

However, I have this code:

import string
import random

file = open('file.dat', 'r')
file=file.read()
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
file = open("newfile.txt", "w")
file.write(id_generator())
file.close()

This code, simply reads the file.dat archive, prints it to console, then generates a random string and stores it on a file called newfile.txt, but it doesn't compares anything, so, to accomplish that I've modified the code like this:

import string
import random

file = open('bullshit.dat', 'r')
file=file.read()
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
with open("newfile.txt", "r") as f: stored = f.readline() 
if stored == id_generator(): 
    print('success!')

Now, my problem is, that this code just reads an already created file, which is newfile.txt, I need to create a new one like the code I had before, but comparing the strings.

I tried modifying the last three lines like this:

with open("newfile.txt", "w") as f: stored = f.readline() 
if stored == id_generator(): 
    print('success!')

But it throws me:

Traceback (most recent call last):
File "string2.py", line 20, in <module>
with open("newfile.txt", "w") as f: stored = f.readline() 
IOError: File not open for reading

How can I accomplish something like the first version, but comparing the strings as the second one?




Swift Random Color Generator

Is it possible to change the color a button with a label using a random generator?

For ex.. Label "A" is the title/color dictator and will notify "Button 1 and Button 2" what colors they will generate to be randomly.




Java ThreadLocalRandom efficiency

I am implementing a program that changes the outcome randomly, so I thought numbers could represent each outcome.

I am computing a random number using ThreadLocalRandom.getCurrent().nextInt(num); on every iteration, but I found out soon that it is extremely inefficient.

Is there another alternative to generate randomness?




How do I add a 'Play Again feature' to my Number Guessing Game?

I need some help on being able to add a play again feature. If the user guesses the right value, ask them if they want to play (using Y/N) and reset the random number.

Also, is there any way to modify my code so that the user can first set the parameters of the random number by setting a min. and max. number? Thanks!

Here's what I've got so far:

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

class Random_Number_Game {

  int maxNumber;
  int minNumber;
  int numberToBeGuessed = 0;
  int totalGuessesTaken = 0;

public Random_Number_Game(int min, int max) {
    maxNumber = max;
    minNumber = min;
    int userGuess;

    numberToBeGuessed = createRandomNumber();

    do {
        totalGuessesTaken++;
        userGuess = retrieveUserInput();
       } while (!checkUserInput(userGuess));
} // end GuessMyNumber method


 public int retrieveUserInput() {

    Scanner keyboard = new Scanner(System.in);
    String userinput;

    do {
        System.out.print("Guess a number between 0 and 100: ");
        userinput = keyboard.nextLine();
    } while (!isUserInputValid(userinput));

    return Integer.parseInt(userinput);
} // end retrieveUserInput method



public int createRandomNumber() {
    Random r = new Random();
    return r.nextInt(101);
}

public boolean checkUserInput(int guess) {

    if (guess == numberToBeGuessed) {

        System.out.println("Right! It took you " + totalGuessesTaken + " guesses.");
        return true;

    } else {

        if (guess > numberToBeGuessed) {
            System.out.println("Too High!");
        } else {
            System.out.println("Too Low!");
        }
    }
    return false;
}


public static boolean isUserInputValid(String testerString) {
    try {
        Integer.parseInt(testerString);
    } catch (NumberFormatException e) {
        System.out.println("That input is invalid. You entered '" + testerString + "'. Please enter a proper integer: ");
        return false;
    }
    return true;
}

public static void main(String args[]) {
    new Random_Number_Game(0, 101);
}

}




How to compare random generated string with a string on txt file - Python

I'm generating a random string of 28 characters, I need to compare this generated string with a another string which is on a file, this is my code at the moment:

import string
import random

file = open('file.dat', 'r')
file=file.read()
print file

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))
file = open("newfile.txt", "w")
file.write(id_generator())
file.close()

This code, opens file.dat prints it on console, then generates a random string, stores the string on file and exits, my problem is that I want to compare the file.dat content which is a string, and the random generated one. And I can't seem to clear my way onto a nice way to accomplish this.

I've read this answer but I'm cofused about it, because in this case, there is a random generated string, and another one which is on a file.

What could be the best approach to accomplish this?

I hope I've explained myself.

EDIT

The underlying idea, is to compare strings, let's say on file.dat I have "THIS IS A STRING", then compare the random generated one and see if any random generated character matches the position of characters in the phrase present on file.dat




How to find what random row from a random table was chosen

I'm trying to create a website where users can vote on different items from a game, like a tierlist. I want the item that a user votes on to be from a random table and a random row in that table.

Right now, I have the following code set up to find the random item:

$ran = mt_rand(1, 10);
switch ($ran) {
    case "1":$sql = "SELECT item, rating FROM ditems ORDER BY RAND() LIMIT 1";  
         $result = $conn->query($sql);  
         while($row = $result->fetch_assoc()) {
            echo $row["gun"];
         };
         break;
    case "2":$sql = "SELECT item, rating FROM citems ORDER BY RAND() LIMIT 1";  
         $result = $conn->query($sql);  
         while($row = $result->fetch_assoc()) {
            echo $row["item"];
         }; 
etc

The problem I run into is that I can't access what the chosen item is outside of the switch{} statement because the $row array is declared locally, but I have to be able to do that so that I can seet up a button to vote on the item.

What am I missing? Or is there a easier way to do this?




Random number generator in java

I am trying to make a random number generator that will generate either a 1 or a 2. However whenever I run the program only a 0 is printed. This is what I have right now:

Random rand = new Random();
int  n = rand.nextInt(2) + 1;
System.out.println(n);




drawing a slope in random circles python

So my program is designed to manipulate certain coordinates in order to create this image: ![image

So basically my program draw a bunch of random circles and I have to manipulate the line of equation to create the red sections. So far my image is the following:enter image description here

I can't seem to figure out how to add another line equation to create the other red section. Any help would be greatly appreciated!

# using the SimpleGraphics library
from SimpleGraphics import *

# tell SimpleGraphics to only draw when I use the update() function
setAutoUpdate(False)


# use the random library to generate random numbers
import random


# size of the circles drawn
diameter = 15

resize(600, 400)


##
# returns a vaid color based on the input coordinates
#
# @param x is an x-coordinate 
# @param y is a y-coordinate 
# @return a colour based on the input x,y values for the given flag
##
def define_colour(x,y):
  ##
  #add your code to this method and change the return value
  slopeOne = (200 - 300)/(0-150)
  b = 0 - (slopeOne * 200)
  #slopeTwo = (0-150)/(200 - 300)
  #b = 200 - (slopeOne * )



  lineEquationOne = (slopeOne * x) + b
  #lineEquationTwo = (slope * x) + b

  if y > lineEquationOne:
    return "white"
  else:
    return 'red'





######################################################################
#
# Do NOT change anything below this line
#
######################################################################

# repeat until window is closed
while not closed():
  for i in range(500):
    # generate random x and y values 
    x = random.randint(0, getWidth())
    y = random.randint(0, getHeight())

    # set colour for current circle
    setFill( define_colour(x,y) )

    # draw the current circle
    ellipse(x, y, diameter, diameter)

  update()




Copy random string 100 times on python - print to cli

I have this code, which generates a random string of 28 characters in python:

import string
import random

def id_generator(size=28, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

Then I call this method from command line like: id_generator()

Now to have this printed on cli, I've tried with this line, as a last one after return: print (id_generator()) but it doesnt print anything to cli, I have to execute the script inside python console with execfile

Also, how can I duplicate the random generated string 100 times?

Any ideas on this?




Probability of getting the particular summ of two numbers in C++

There are two cubes and different numbers from 1 to 6 on each plane surfaces of the cubes. After we throw up the cubes, we get two numbers on two of the plane surfaces. I need to create a code which would calculate the probability of getting the particular summ (which could be from 2 to 12) of those numbers on the plane surfaces. I also need to use the function "rand()". Does anyone have any ideas how to do this? Thanks in advance.




Image is not appended into img id container after user has clicked on button

Functionality:

User will need to answer 1 simple question with 4 options. Each option is appended with a different image. Hence, a new page with the appended image will be displayed depending on which option that the user has chosen.

Therefore, this is the general flow :

Page A-> displays a question with 4 options for the user to select. Depending on which option that the user selects. It will navigate to Page B and display the image that is associated with the option selected by the user.

What has been done:

I have created a page for the question and 4 options as well as a 2nd page that will show the appended image depending on the option that the user has selected.

This is the code that I have done:

var random_Question,
  random_BrandIndex,
  optionList,
  PrintSelectedOffer;

//Append array of images to list container in alphabetical Order
var x = 0,
  number = 0;
var printOptionFrame = "";

//Brand Offers
var Outlook_list = [];


//Set Array bank of Questions
var QuestionOrder = ["A?", "B?", "C?", "D?", "E?"];

//Set Array bank of Answers
var ChoiceOrder = [
  ["Shpinge", "Vacation", "Sav", "Donate"],
  ["Responsibles", " Foreign ", "Gourmet ", "Martial "],
  ["A ue Sea", "Rn Grass", "Dark F Trees", "WaterfallRainbow"],
  ["Cooking", "Traling", "Playing", "Shg"],
  ["Fabok", "Insram", "Snhat", "Seie?"]
];

//Print Array
var PrintOrder = [
  ["A01", "A02", "A03", "A04"],
  ["A03", "A05", "A04", "A06"],
  ["A02", "A03", "A06", "A04"],
  ["A04", "A05", "A03", "A01"],
  ["A03", "A04", "A02", "A06"]
];

function Start() {
  idleTime = 0;

  $("#Start").fadeOut();
  $("#QuestionPage").fadeIn({
    complete: function() {

      //Show Original Answer Point
      $("#Pointer_1").show();
      $("#Pointer_2").show();
      $("#Pointer_3").show();
      $("#Pointer_4").show();
      //Show Question and Answers
      showQuestion();
    }
  });
}

function showQuestion() {

  //Randomised Question Array List
  random_Question = Math.floor(Math.random() * QuestionOrder.length);
  //Push randomised question array into empty array reference
  Outlook_list.push(random_Question);
  console.log("Outlook_list:" + "[" + Outlook_list + "]");

  $("#GamePageOption_1").attr("class", "original_brightness");
  $("#GamePageOption_2").attr("class", "original_brightness");
  $("#GamePageOption_3").attr("class", "original_brightness");
  $("#GamePageOption_4").attr("class", "original_brightness");

  $("#Option_selected_1").hide();
  $("#Option_selected_2").hide();
  $("#Option_selected_3").hide();
  $("#Option_selected_4").hide();

  $("#Page_question").html(QuestionOrder[random_Question]);

  optionList = ChoiceOrder[random_Question];

  $("#GamePageOption_1").html(optionList[0]);
  $("#GamePageOption_2").html(optionList[1]);
  $("#GamePageOption_3").html(optionList[2]);
  $("#GamePageOption_4").html(optionList[3]);
}


function select_option(flag) {
  idleTime = 0;

  //Play with brightness of selected option

  if (flag == 1) {
    $("#Option_selected_1").show();
    $("#GamePageOption_2").attr("class", "decrease_brightness");
    $("#Pointer_2").attr("class", "decrease_brightness");
    $("#GamePageOption_3").attr("class", "decrease_brightness");
    $("#Pointer_3").attr("class", "decrease_brightness");
    $("#GamePageOption_4").attr("class", "decrease_brightness");
    $("#Pointer_4").attr("class", "decrease_brightness");
  } else if (flag == 2) {
    $("#Option_selected_2").show();
    $("#GamePageOption_1").attr("class", "decrease_brightness");
    $("#Pointer_1").attr("class", "decrease_brightness");
    $("#GamePageOption_3").attr("class", "decrease_brightness");
    $("#Pointer_3").attr("class", "decrease_brightness");
    $("#GamePageOption_4").attr("class", "decrease_brightness");
    $("#Pointer_4").attr("class", "decrease_brightness");
  } else if (flag == 3) {
    $("#Option_selected_3").show();
    $("#GamePageOption_1").attr("class", "decrease_brightness");
    $("#Pointer_1").attr("class", "decrease_brightness");
    $("#GamePageOption_2").attr("class", "decrease_brightness");
    $("#Pointer_2").attr("class", "decrease_brightness");
    $("#GamePageOption_4").attr("class", "decrease_brightness");
    $("#Pointer_4").attr("class", "decrease_brightness");
  } else if (flag == 4) {
    $("#Option_selected_4").show();
    $("#GamePageOption_1").attr("class", "decrease_brightness");
    $("#Pointer_1").attr("class", "decrease_brightness");
    $("#GamePageOption_2").attr("class", "decrease_brightness");
    $("#Pointer_2").attr("class", "decrease_brightness");
    $("#GamePageOption_3").attr("class", "decrease_brightness");
    $("#Pointer_3").attr("class", "decrease_brightness");
  }

  setTimeout(function() {

    $("#QuestionPage").fadeOut();
    $("#Description").fadeIn({
      complete: function() {

        //show outlook description
        printOptionFrame = PrintOrder[optionList];
        console.log("printOptionFrame: " + printOptionFrame);
        $("#DescriptionBlock").attr('src', printOptionFrame).show();
      }
    });
  }, 1000);
}
<div id="QuestionPage" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; z-index=2; top:0px; left:0px; margin:auto;">

  <!--MainStart Image-->
  <img id="Background" src="lib/image/Background.png" style="position:absolute; top:0px; left:0px; margin:auto;" />

  <!-- Question -->
  <div id="Page_question" style="position:absolute; font-family:AgendaSemiBold; z-index:3; top:515px; left:180px; margin:auto; color:#FFFFFF; font-size:30px; width:800px;"></div>

  <!-- Answer List -->
  <div id="GamePageOption_1" style="position:absolute; font-family:AgendaBold; z-index:3; top:854px; left:317px; margin:auto; color:#FFFFFF; font-size:25px; width:750px; text-align: justify;"></div>
  <div id="GamePageOption_2" style="position:absolute; font-family:AgendaBold;  z-index:3; top:986px; left:317px; margin:auto; color:#FFFFFF; font-size:25px; width:750px; text-align: justify;"></div>
  <div id="GamePageOption_3" style="position:absolute; font-family:AgendaBold;  z-index:3; top:1098px; left:317px; margin:auto; color:#FFFFFF; font-size:25px; width:750px; text-align: justify;"></div>
  <div id="GamePageOption_4" style="position:absolute; font-family:AgendaBold;  z-index:3; top:1214px; left:317px; margin:auto; color:#FFFFFF; font-size:25px; width:750px; text-align: justify;"></div>

  <!--Original Option Point -->
  <img id="Pointer_1" src="lib/image/OriginalOptionPoint.png" style="display:none; position:absolute; z-index:4; top:836px; left:180px; margin:auto;" />
  <img id="Pointer_2" src="lib/image/OriginalOptionPoint.png" style="display:none; position:absolute; z-index:4; top:962px; left:180px; margin:auto;" />
  <img id="Pointer_3" src="lib/image/OriginalOptionPoint.png" style="display:none; position:absolute; z-index:4; top:1077px; left:180px; margin:auto;" />
  <img id="Pointer_4" src="lib/image/OriginalOptionPoint.png" style="display:none; position:absolute; z-index:4; top:1193px; left:180px; margin:auto;" />

  <!-- Selected Option Point -->
  <img id="Option_selected_1" src="lib/image/SelectedOptionPoint.png" style="display:none; position:absolute; z-index:5; top:836px; left:180px; margin:auto;" />
  <img id="Option_selected_2" src="lib/image/SelectedOptionPoint.png" style="display:none; position:absolute; z-index:5; top:962px; left:180px; margin:auto;" />
  <img id="Option_selected_3" src="lib/image/SelectedOptionPoint.png" style="display:none; position:absolute; z-index:5; top:1077px; left:180px; margin:auto;" />
  <img id="Option_selected_4" src="lib/image/SelectedOptionPoint.png" style="display:none; position:absolute; z-index:5; top:1193px; left:180px; margin:auto;" />

  <!-- Selection of answer -->
  <img src="lib/image/transparent.png" class="transparentBg" style="position:absolute; z-index:6; top:854px; left:0px; margin:auto; color:#FFFFFF; font-size:25px; width:1080px; height:80px;" onclick="select_option(1);" />
  <img src="lib/image/transparent.png" class="transparentBg" style="position:absolute; z-index:6; top:986px; left:0px; margin:auto; color:#FFFFFF; font-size:25px; width:1080px; height:80px;" onclick="select_option(2);" />
  <img src="lib/image/transparent.png" class="transparentBg" style="position:absolute; z-index:6; top:1098px; left:0px; margin:auto; color:#FFFFFF; font-size:25px; width:1080px; height:80px;" onclick="select_option(3);" />
  <img src="lib/image/transparent.png" class="transparentBg" style="position:absolute; z-index:6; top:1214px; left:0px; margin:auto; color:#FFFFFF; font-size:25px; width:1080px; height:80px;" onclick="select_option(4);" />

  <button class="MainReset" onclick="Reset()"></button>

</div>

<div id="Description" align="center" style="position:absolute; width:1080px; height:1920px; background-repeat: no-repeat; display: none; z-index=7; top:0px; margin:auto;">

  <!--Video Div-->
  <!-- <div id="UOB_DescriptionVideo" style="position:absolute;"></div> -->

  <!--MainStart Image-->
  <img id="DescriptionBackground" src="lib/image/Description.png" style="position:absolute; top:0px; left:0px; margin:auto;" />

  <img id="DescriptionBlock" style="position:absolute; top:0px; left:0px; margin:auto;">
</div>

Issue:

When I clicked on the option, no element from the array of PrintOrder is displayed on Page B. As in the img id of DescriptionBlock is not displayed. Hence, I am unable to call the associated image after I have clicked on the option from Page A.

Hence, I would need some assistance and what have I done wrong? Please. Thank you.




placing distinct random values refering to another column Excel

I want to generate random String value that won't be repeated depending on the value in the another column. The dataset is fake and I need to complete segment name for every each customer. I put random names of segments this way:

=CHOOSE(RANDBETWEEN(1;6);$Y$2;$Y$3;$Y$4;$Y$5;$Y$6;$Y$7;)

of course it doesn't take into the account that one customer can be placed only in one segment (in one of RANDBETWEEN value). Do you have any solution how to put a distinct value for every customer? enter image description here




Is it a good/bad idea to keep ThreadLocal between parallel loops?

I'm trying to use ThreadLocal for parallel random generators. My test code is something like this:

class Program
{
    static void Main()
    {
        using (MyClass myClass = new MyClass())
        {
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("\nPass {0}: ", i + 1);
                myClass.Execute();
            } 
        }

        Console.WriteLine("\nPress any key...");
        Console.ReadKey();
    }
}

sealed class MyClass : IDisposable
{
    ThreadLocal<RandomGenerator> threadRNG = new ThreadLocal<RandomGenerator>(() => 
                                                    new RandomGenerator());

    public void Execute()
    {
        Action<int> action = (i) =>
        {
            bool repeat = threadRNG.IsValueCreated;
            List<int> ints = new List<int>();
            int length = threadRNG.Value.RNG.Next(10);
            for (int j = 0; j < length; j++)
                ints.Add(threadRNG.Value.RNG.Next(100));
            Console.WriteLine("Action {0}. ThreadId {1}{2}. Randoms({3}): {4}", 
                i + 1, threadRNG.Value.ThreadId, repeat ? " (repeat)" : "", 
                length, string.Join(", ", ints));
        };

        Parallel.For(0, 10, action);
    }

    public void Dispose()
    {
        threadRNG.Dispose();
    }
}

class RandomGenerator
{
    public int ThreadId { get { return Thread.CurrentThread.ManagedThreadId; } }
    Random rng;
    public Random RNG { get { return rng; } }
    public RandomGenerator()
    {
        rng = new Random(Guid.NewGuid().GetHashCode());
    }
}

Is it a good/bad idea to keep ThreadLocal between multiple executions of parallel loop? I'm afraid that there may accumulate unused instances of RandomGenerator. Especially when I have thousands of executions.




samedi 29 octobre 2016

Create random values of generic typein Java

I have the following:

public class RandomList {

    private List<Integer> list;

    public List<Integer> getList() {
        return list;
    }

    public RandomList (int n) {
        list = new ArrayList<Integer>();

        Random rand = new Random();
        rand.setSeed(System.currentTimeMillis());

        for (int i=0; i < n; i++)
        {
            Integer r = rand.nextInt();
            list.add(r);
        }
    }   
}

which gives me a list filled with random Integer values. I would like to generalize this, to also get a list of random Character values or perhaps lists of other types' random values.

So what I want is a generic type version, class RandomList<T>. I can replace everywhere "Integer" by "T", but am stuck at the line Integer r = rand.nextInt(); which would read different for different types.

I am thinking of doing the following:

  1. pass in the class of the generic type to RandomList
  2. using instanceof check the passed in class against the desired types (Integer, Character...) and depending on the check return the proper random value

Does this make sense? Is there another/better way to achieve what I want?




Get set of random numbers from input List having fixed sum using C#

I am looking for a C# algorithm that would give me a set of random integers from input List, such that the sum of obtained random integers is N.

For example: If the list is {1,2,3,4,5,6...100} and N is 20, then the algorithm should return a set of random numbers like {5,6,9} or {9,11} or {1,2,3,4,10} etc.

Note that the count of integers in result set need not be fixed. Also, the input list can have duplicate integers. Performance is one of my priority as the input list can be large (around 1000 integers) and I need to randomize about 2-3 times in a single web request. I am flexible with not sticking to List as datatype if there is a performance issue with Lists.

I have tried below method which is very rudimentary and performance inefficient:

  1. Use the Random class to get a random index from the input list
  2. Get the integer from input list present at index obtained in #1. Lets call this integer X.
  3. Sum = Sum + X.
  4. Remove X from input list so that it does not get selected next.
  5. If Sum is less than required total N, add X to outputList and go back to #1.
  6. If the Sum is more than required total N, reinitialize everything and restart the process.
  7. If the Sum is equal to required total N, return outputList.



generate random number between 10 to 1000000000 in C

I am using this code to create; but all the results are in range of 10-32.000.

can you tell me what I am doing wrong?

for(i=0;i<N;i++){                
    *(A+i)=rand() % (1000000000 - 10 + 1) + 10;
    printf("%lu\n",*(A+i));
}




Haskell Random Number Generator

I want to spawn an enemy at a random time in my game. To do this I wanted to check each frame if a random value [0..100] == 50

spawnEnemy :: World -> World
spawnEnemy (world@World { rndGen = r, enemies = e }) = world { enemies = if rand 0 100 = 50 then Enemy (rand (-200) 200, rand (-200) 200) 0 0 : e else e }
    where
        rand :: Float -> Float -> Float
        rand l h = fst $ randomR (l, h) r

(here rndGen :: stdGen and enemies :: [Enemy])

But rand never seems to return 50. What am I doing wrong here?




Java: Random card generator without arrays

I'm learning Java and got stuck on one of the "Loops" lesson exercises. Wherever I look online, this kind of question is solved using arrays; while I'm aware this is probably the more efficient way, it bugs me that I can't understand what is wrong with my solution. What would be a good solution here?

package practice05;

import java.util.Random;

public class Practice04
{
public static void main(String[] args)
{
    new Practice04();
}
public Practice04()
{
    String number = "";
    String suit = "";
    System.out.println(number(number) + " " + sign(suit));
}

private String number(String number)
{
    Random n = new Random();
    int num = n.nextInt(14);
    if (num > 10 || num < 2)
    {
        switch (num)
        {
            case 1: number = "Ace";
            case 11: number = "Ace";
            case 12: number = "Jack";
            case 13: number = "Queen";
            case 14: number = "King";
        }
    }
    else
    {
        number = Integer.toString(num);
    }
    return number;
}

private String sign(String suit)
{
    Random s = new Random();
    int sign = s.nextInt(4);
    switch (sign)
    {
        case 1: suit = "of clubs";
        case 2: suit = "of diamonds";
        case 3: suit = "of hearts";
        case 4: suit = "of spades";
    }
    return suit;
}
}




vendredi 28 octobre 2016

Random combination of strings using arrays

I am trying to figure out how to combine 2 random Strings entered by the user. This program is kind of like a Mad Libs game but instead it is for creating a poem. I first start by asking the user to enter the number of nouns willing to use, and then storing them into an array, and follow by asking the amount of adjectives, which also are stored in an array.

Precisely what is asked is as follows:

Generate your poem by choosing at random combinations of noun and adjectives. You are not allowed to pick a noun or an adjective again until you have used all sets of noun and adjectives that the user has provided, respectively.

Now I am asked to generate a poem by combining the entered nouns and adjectives, but the generator needs to be random. How would I do this? So far my program is as folows:

import java.util.Scanner; public class A3Question1 {

public static void main(String[] args) 
{
    Scanner keyboard = new Scanner(System.in);

    System.out.println("-----------------------------------------");
    System.out.println("               Poem game                 ");
    System.out.println("-----------------------------------------");
    System.out.println();
    String[] nouns, adjectives;
    boolean loop1 = false;

    while (!loop1)
    {

        System.out.print("How many nouns (min 3): ");
        int numNouns = keyboard.nextInt();

        if (numNouns < 3)
        {
            continue;
        }

        nouns = new String[numNouns];

        System.out.println("Enter " + numNouns + " nouns");
        boolean loop2 = false;

        while (!loop2)
        {
            nouns[numNouns - 1] = keyboard.next();
            numNouns--;

            if (numNouns == 0)
            {
                loop2 = true;
            }
        }
        boolean loop3 = false;

        System.out.println("How many adjectives (min 3): ");
        int numAdjectives = keyboard.nextInt();

        while (!loop3)
        {
            if (numAdjectives < 3)
            {
                System.out.print("How many adjectives (min 3): ");
                numAdjectives = keyboard.nextInt();
            }
            else
            {
                loop3 = true;
            }
        }

        adjectives = new String[numAdjectives];

        System.out.println("Enter " + numAdjectives + " adjectives");
        boolean loop4 = false;

        while (!loop4)
        {
            adjectives[numAdjectives - 1] = keyboard.next();
            numAdjectives--;

            if (numAdjectives == 0)
            {
                loop4 = true;
            }
        }

    }
    keyboard.close();
}

}




Generating a Random number from set array and returning it to main class

So I have an array of size 18, and I'm trying to generate a random number which represents the index location of one of the 18 numbers in the array and return that number from the array to the main method.

My code so far is this, and I've stuck for a while, so any help is appreciated.

public static int spinMethod() {
    int[] roll = new int[] {1000, 1500, 750, 600, 500, 100, 250, 750, 600, 1500, -1, 500, 1000, 1500, 750, -1, 500, 1500}; //creates array and assigns variables
    Random r = new Random(); //random number generator
    int x = 1 + r.nextInt(18);      
    return int[x];




Tensorflow function that returns an array of random integers different to a given int

I would like to implement a code in tensorflow, given two numbers a,b and a number "true", return an array of random integers, everyone different to the true.

In simple python using random.randint would be something like

def get_a_rand(a,b,true, S):
    for i in range(S.shape[0]):
        k = 1
        while (k == 1):
            r = (randint(a,b))
            if r!= true:                
                k = 12
                S[i] = r
            else:
                k = 1
return S

Where S for example:

S = np.zeros((4))

How can i define something like that using Tensorflow? Using this function maybe tf.random_uniform([],a ,b, dtype=tf.int32) ??




Writing a function in VBA to return a triangular random number

I am trying to write a series of VBA functions for excel that would return random number types to call on in subroutines. I am getting a similar error once I go into the more complicated formulas. For example: the asymmetric triangular random variable.

'the function

Function AsymetricTriangleInVBA (min As Double, mode As Double, max As Double) As Double
  Application.Volatile
  Randomize
  Dim Temp As Variant
  Temp = Rnd
  AsymetricTriangleInVBA = WorksheetFunction.if(Temp < ((mode - min) / (max - min)), min + (max - min) * WorksheetFunction.sqrt(((mode - min) / (max - min)) * Temp), min + (max - min) * (1 - WorksheetFunction.sqrt((1 - ((mode - min) / (max - min))) * (1 - Temp))))
End Function

'my test sub

Sub test()
    MsgBox AsymetricTriangleInVBA(5, 10, 15)
End Sub

The consistent error i am receiving is:

Run time error '438': Object does not support this property or method

Any thoughts?

Thanks




Taking data from a data.txt file in JSON format and displaying it randomly on the GUI

I have to import the data.txt file currently having 3 dictionaries (can have more as well) and to randomly select the name of an item and print it on the GUI. The code above is designed to do the required but it doesn't do anything. Can you please help me with this.

with open('data.txt') as data_file:
        data = json.load(data_file)
        data_file.close()
self.firstPrompt = tkinter.Label(self.top, width=7, \
                       text=random.sample(data['name'], 1), fg='blue', font=("Helvetica", 16))




How to randomly select between two numbers?

So lets say I want to randomly choose between the number 1 and number 3 (not in between, just those two numbers). How do I go about doing that? Do I just assign int a to 1, int b to 3, and then do random for int a,b?




How can I create a list with random parameters on certain text places? (Javascript)

To be honest I want to code a program that does that but if it isn't possible I would like to know if there is any other non-manual way. What I am basically saying is that I have a format like this one:

==========================================
Head: *******:*******
==========================================
Parameter 1: ********
Parameter 2: *******
Parameter 3: *******
Parameter 4: *******
Parameter 5: * [***, ***, ***]
==========================================
******** -> *********
==========================================

And I want it printed multiple times with stuff extracted at random from a database to input it in the place of the asterisks. The database limit is 500. I understand that it requires a for loop etc. but I am clueless as to how to make it get a random element from a list and how to input the said list within the code instead of writing each element one by one (The list is in .txt format).




Genreating Hashes using .NET Core

I need to Generate Random Unique hashes to be used in password reset links in .Net Core. In ASP.NET Identity, I found this to be helpful, I am wondering if RNGCryptoServiceProvider still assures the randomness of the hashes generated.

 using (RNGCryptoServiceProvider
                                rngCsp = new RNGCryptoServiceProvider())
            {
                var data = new byte[4];
                for (int i = 0; i < 10; i++)
                {
                    //filled with an array of random numbers
                    rngCsp.GetBytes(data);
                    //this is converted into a character from A to Z
                    var randomchar = Convert.ToChar(
                        //produce a random number 
                        //between 0 and 25
                                              BitConverter.ToUInt32(data, 0) % 26
                        //Convert.ToInt32('A')==65
                                              + 65
                                     );
                    token.Append(randomchar);
                }
            }

What is the best way to achieve that using .net core and using which classes?




Random number within range (range changes after each run)

I'm trying to make a guess my number program, with the computer guessing the number that I choose, I seem to have finally got it working except for the random number range, the high number works but the low number doesn't,

I guess I shouldn't be doing lowGuess=rand() but I have no idea what I should be doing instead, could somebody point me in the right direction please?

Also feel free to give me feedback on the rest of the code, this is my first attempt at writing something myself. (with a little reference material)

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

const int high = 100;
const int low = 1;
int lowGuess=1;
int highGuess=100;
int myNumber=0;
int guess=0;
int guesses=0;
bool correct = 0;

int askNumber();
int askResponse();
int guessNumber();

int main()
{

askNumber();

do 
{
    guessNumber();

    askResponse();
} while (correct == 0);
cout << "Yes!! I guesed your number in " << guesses << " guesses.";

return 0;
}


int askNumber()
{
cout << "\n\nEnter a number between " << low << " - " << high << ".\n\n";
cin >> myNumber;

if (myNumber < low || myNumber >high)
    {
    return askNumber();
    }
}

int guessNumber()
{
srand(static_cast<unsigned int>(time(0)));
lowGuess = rand();                              //im   doing something wrong here with lowGuess
guess = (lowGuess % highGuess) + 1;             //im trying to generate a random number between
cout << "\n\nMy guess is " << guess << endl;    //the value of lowGuess and highGuess
guesses += 1;                                   //highGuess is working as intended but lowGuess isn't

//printing values to see them working
cout << "low " << lowGuess << " high "<<highGuess << endl;  

return 0;
}

int askResponse()
{
int response;
cout << "\n\nIs my guess too high, too low, or correct?\n\n";
cout << "1. Too High.\n";
cout << "2. Too Low.\n";
cout << "3. Correct.\n\n";

    cin >> response;
if (response < 1 || response > 3)
{
    return askResponse();
}
else if (response == 1)
{
    cout << "\n\nToo high eh? I'll take another guess.\n\n";
    highGuess = guess;              //altering the upper limit of random number range
}
else if (response == 2)
{
    cout << "\n\nToo low eh? I'll take another guess.\n\n";
    lowGuess = guess;               //alteing the lower limit of random number range
}
else if (response == 3)
{
    correct = 1;
}

return 0;

} [/code]




Python - Radom Number Integer

How do you write 100 random numbers one number per line. The random numbers must be integers in the range [0,100].

for x in range(0, 100):
     print(random.randint(0, 100)

This is what I am doing, but it is not working.




Haskell Gloss: random starfield not random?

Using Haskell’s Gloss library, I’m trying to simulate a starfield. The visual aspect (drawing ‘stars’ with various speeds and sizes to the screen) is working. However, for some reason the stars aren’t being randomly distributed, resulting in a simulation which has a pattern. I also have this problem with an explosion simulation, but for simplicity’s sake, I’ll leave that one out for now. This is a simplified version of my code so far:

type Position       = (Float, Float)
type Velocity       = (Float, Float)
type Size           = Float
type Speed          = Float
type Drag           = Float
type Life           = Int

type Particle       = (Position, Velocity, Speed, Drag, Life, Size)

-- timeHandler is called every frame by the gloss ‘Play’ function. It's being passed
-- the delta time and the world it needs to update.
timeHandler dt world = world {rndGen = mkStdGen (timer world),
                              timer  = (timer world) + 1,
                              stars  = spawnParticle world (rndGen world) : updateParticles (stars world) dt world}

randomFloat :: StdGen -> Float -> Float -> Float
randomFloat rand min max = fst $ randomR (min, max) rand

spawnParticle :: World -> StdGen -> Particle
spawnParticle world gen = ((pos, (1 * speed, 0), speed, 1, 0, size), snd (split gen))
where pos   = (px', py')
      px'   = randomFloat gen (-600) (-500)
      py'   = randomFloat gen (-250) 250
      speed = size * (randomFloat gen 100 300) -- the smaller a particle, the slower 
      size  = randomFloat gen 0.1 1.3

updateParticles :: [Particle] -> Float -> World -> [Particle]
updateParticles []     _  _     = []
updateParticles (x:xs) dt world | fst(posPart x) > 500 = updateParticles xs dt world
                                | otherwise            = updatedPart : updateParticles xs dt world
    where pos'        = updateParticlePosition dt x world
          updatedPart = (pos', velPart x, speedPart x, 1, 0, sizePart x)

Note: velPart, speedPart etc. are functions to get a property out of a given particle. Again, drawing works fine, so I’ll leave that code out. updateParticlePosition simply adds the velocity to the current position of a star.

I think the problem has something to do with the fact that my random generators are not passed properly, but I’m too confused to come up with a solution… Any help is much appreciated!




How to select edge randomly from graph in R?

I have a regular graph and wanna delete randomly edge from graph. How to select edges randomly till I can delete?

library(igraph)
g = sample_k_regular(10,3)




VBMATH.Randomize(Double) equivalent in C

I'm shuffling a string called STR in VB using:

    For K = 1 To Len(Str)
        Sk = Sk + Asc(Mid$(Str, K, 1))
    Next K

    Rnd(-1)
    Randomize(Sk)

    For K = 1 To Len(Str)
        RndPos = 1 + Fix(Len(Str) * Rnd)
        ' SWAP Chars
        Tmp = Mid$(Str, K, 1)
        Mid$(Str, K, 1) = Mid$(Str, RndPos, 1)
        Mid$(Str, RndPos, 1) = Tmp
    Next K

I would like to unscramble it in C code on AIX, i can't however find the equivalent of Randomize(double) from VBMATH.

Is there an easy way around it ?

I know that i can seed C's rand() function with srand, but i'm stuck after that.. all the online resources are for C#.

Any help will be appreciated !

Cheers.




Generating Random SQL Queries from SQL Grammar

I am trying to automatically generate SQL queries that are only syntactically correct. I have seen the PostgreSQL grammar file, I am wondering is there a way to generate random SQL queries based on SQL grammar? There can be unlimited number of SQL queries generated but we can put a limit on the length of SQL query strings.

For example to get something like this in results:

SELECT X FROM X WHERE X BETWEEN X AND X ;




Writing to file random loss and gain of 0s

I am writing a python script to convert old DayLite contacts into CSV format to be imported into Outlook. I have a script that functions completely almost perfectly except for one small issue but due to being mass data fixing it in the file will take way to long.

The list of contacts is very long 1,100+ rows in the spreadsheet. When the text gets written into the CSV file everything is good except certain/random phone numbers lose their leading 0 and gain a '.0' at the end. However the majority of the phone numbers are left in the exact format.

This is my script code:

import xlrd
import xlwt
import csv
import numpy

##########################
# Getting XLS Data sheet #
##########################

oldFormatContacts = xlrd.open_workbook('DayliteContacts_Oct16.xls')
ofSheet = oldFormatContacts.sheet_by_index(0)

##################################
# Storing values in array medium #
##################################

rowVal = [''] * ofSheet.nrows

x = 1

for x in range(ofSheet.nrows):
    rowVal[x] = (ofSheet.row_values(x))

######################
# Getting CVS titles #
######################

csvTemp = xlrd.open_workbook('Outlook.xls')
csvSheet = csvTemp.sheet_by_index(0)
csv_title = csvSheet.row_values(0)

rowVal[0] = csv_title

##############################################################
# Append and padding data to contain commas for empty fields #
##############################################################

x = 0
q = '"'

for x in range(ofSheet.nrows):
    temporaryRow = rowVal[x]
    temporaryRow = str(temporaryRow).strip('[]')
    if x > 0:
        rowVal[x] = (','+str(q+temporaryRow.split(',')[0]+q)+',,'+str(q+temporaryRow.split(',')[1]+q)+',,'+str(q+temporaryRow.split(',')[2]+q)+',,,,,,,,,,,,,,,,,,,,,,,,,,'+str(q+temporaryRow.split(',')[4]+q)+','+str(q+temporaryRow.split(',')[6]+q)+',,,,,,,,,,,,,,,,,,,,,,,,,'+str(q+temporaryRow.split(',')[8])+q)

    j = 0
    for j in range(0,21):
        rowVal[x] += ','
    tempString = str(rowVal[x])
    tempString = tempString.replace("'","")
    #tempString = tempString.replace('"', '')
    #tempString = tempString.replace(" ", "")
    rowVal[x] = tempString

######################################
# Open and write values too new file #
######################################

csv_file = open('csvTestFile.csv', 'w')

rownum = 0

for rownum in range(ofSheet.nrows):
    csv_file.write(rowVal[rownum])
    csv_file.write("\n")

csv_file.close()

Sorry if my coding is incoherent I am a beginner to python scripts.

Unfortunately I cannot show or provide the contact details due to privacy reasons however I will give some examples in the exact format that it occurs.

So in the DayLite document a contact would be saved as "First name, Second name, Company, phone number 1, phone number 2, email" for example: "Joe, Black, Stack Overflow, 07472329584," but when written into the CSV file it will be "Joe","Black","Stack Overflow","7472329584.0".

This is odd because for each occurrence of that problem there will be 10 or so fine numbers that get saved exactly the same e.g. In DayLite: "+446738193583" when written in CSV: "+446738193583".

It seems to me to be a very weird error and this is why I have come here for help! If anyone has any ideas I'd be more than happy to hear them. Cheers guys.




Node.js module for random number analysis

Is there any node.js module available to find-out if the given sequence of numbers appears to be random or not?

I have googled and able to find-out modules only to generate random numbers.




jeudi 27 octobre 2016

What is an efficient method to force uniqueness using rand();

If I used (with appropriate #includes)

int main()
 {
   srand(time(0));
   int arr[1000];
   for(int i = 0; i < 1000; i++)
      {
        arr[i] = rand() % 100000;
      }
   return 0;
 }

To generate random 5-digit ID numbers (disregard iomanip stuff here), would those ID numbers be guranteed by rand() to be unique? I've been running another loop to check all the values of the array vs the recently generated ID number but it takes forever to run, considering the nested 1000 iteration loops. By the way is there a simple way to do that check?




How to store and re-use text input values and variable values that use Math.random()?

Okay, so I'm trying to create a quiz application for revision purposes that asks a random question from a list of questions, takes a text input as the users answer to the question, and then compares it to the actual answer to the question. The code I have used is:

var keyList = Object.keys(htmlModule);
var ranPropName = keyList[ Math.floor(Math.random()*keyList.length) ];
var pageStart = function() {
    document.getElementById("question").innerHTML = htmlModule[ranPropName][0];
    document.getElementById("submit").onclick = answerValidation;
};
window.onload = pageStart;

var answerValidation = function(correctAnswer, userAnswer) {
    correctAnswer = htmlModule[ranPropName][1];
    userAnswer = document.getElementById("submit").value;;

    if(userAnswer === correctAnswer) {
    document.getElementById("rightWrong").style.backgroundColor = "green";
    } else {
    document.getElementById("rightWrong").style.backgroundColor = "red";
    }

};

The variable "htmlModule" refers to the object in which the questions and their answers are stored. Each question and answer pair is stored inside an array that is the value of its property, the property simply being a key used to reference each pair e.g. htmlQ1, htmlQ2 etc.

The main problem I seem to be having is that my 'if' statement comparing the actual answer and the user answer won't evaluate to 'true'. I know this because the background colour of the div element "rightWrong" only ever turns red, even when I've definitely typed in a correct answer at which point it should turn green. My assumption is that either the text input isn't being stored for some reason, or the value of the variable 'ranPropName' that uses Math.random() is changing due to the use of Math.method(), but I'm stuck as to how to remedy either potential problem. Thanks in advance for any replies.




Generating random numbers with weighted distribution in Matlab?

I know how to generate random numbers in a certain range in Matlab. What i am trying to do now is generate random numbers in a range where there is more chance of getting certain ones.

For example: how could i use Matlab to generate random numbers between 0 and 2, where 50% of them will be less than 0.5?

To get numbers between 0 and 2 I would use (2-0)*rand+0. How can i do this but get a certain percentage of the numbers generated to be less than 0.5? Is there a way to do this using the rand function?




C++ : curious return value from a rand() in Dice.h

I know there is a lot of question relative to rand() but none solves my problem.

I have a Dice.h implemented has follow :

#pragma once
#ifndef DEF_DICE
#define DEF_DICE

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

class Dice
{
public:

//Constructors
Dice();
Dice(int nbFaces);

//Destructor
~Dice();

//Return the result of a roll
int roll();

protected:

//The number of faces of this dice
int m_faces;
};

#endif // !DEF_DICE

In Dice.cpp I have this :

#include "stdafx.h"
#include "Dice.h"

Dice::Dice() : m_faces(6)
{

}

Dice::Dice(int nbFaces) : Dice()
{
    m_faces = nbFaces;
}

Dice::~Dice()
{
}

int Dice::roll()
{
    int roll(rand()*m_faces + 1);
    return roll;
}

And my main looks like this :

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include "Dice.h"

using namespace std;

int main()
{
    srand(time(0));

    Dice d6;
    cout << d6.roll() << endl;

    int test(rand() % 6 + 1);
    cout << test << endl;


    return 0;
}

Nothing hard, isn't it ? Just a dice, made with 6 faces through default constructor...

But why the heck d6.roll() returns something like 140456 (always different but always about hundred of thousands) ??? The value of test is good (between 1 and 6)...

I tried with srand(time(0)) in the constructor but it's the same problem.




Plotting number distribution in Matlab

I create random integers based on the given parameter and would like to plot these randomly generated numbers using hist and subplot. When I use disp(A) I get fine results, but the plotting doesn't work.

  x=-4:.2:4;

for i = 1:n
   A=round(-100+100*rand());
   disp(A)
    c=hist(A,-4:.2:4);
  subplot(n,n,i)
  bar(x,c(:,i))
end




How to generate new random circles based on distance from head circle in JavaScript?

I have drawn a circle on a random position within a range on a canvas in JavaScript.

I want to generate 2 more circles on a random position on a specific distance (200) from the center of the 1st circle.

There is a way to generate new coordinates until the distance is equal to 200, but there should be a better solution, right?

How can I do the following?

enter image description here

Code:

var x = getRandomInt(200, 800)
var y = getRandomInt(200, 400)
var r = 60
drawCircle (x, y, r)

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min
}

function drawCircle(x, y, r) {  
    context.beginPath()
    context.arc(x, y, r, 0, 2 * Math.PI, false)
    context.fillStyle = "#fc3358"
    context.fill()
    context.closePath()
}




How to output a random color from a set of selected colors in Java? (Android)

So I want a string to be given a random color any time the user inputs an answer. My issue is that I'm not sure how to make that random color of a string be a color of a specific range. For example, if I wanted the string to be randomly become blue, red, green, pink, white, or brown. Only these colors, none other.

So far I have managed a completely random color out of all possible RBG variations using the following code:

Random rand = new Random();
            int r = rand.nextInt(254)+1;
            int g = rand.nextInt(254)+1;
            int b = rand.nextInt(254)+1;

            int randomColor = Color.rgb(r,g,b);
            word.setTextColor(randomColor);

Though as previously mentioned, this is not what I aim to achieve. Instead of this, I want set colors that can be randomly applied to the string. These are colors that I would pick, then have randomly set as the string color. This sets a completely random color out of a range I do not intend to have. I could end up with 5 variations of blue for example.

If anyone could put forward a solution, I'd appreciate it. Thank you.




Java's Random class behaviour clarification

I have a class 'A' that holds an instance of Random, and which simulates rolling a die, e.g. 6 sides, with a result of 1 - 6 being generated on each 'roll'.

I have another class 'B' that may hold a reference to an object of type A, and should delegate to its 'roll' method.

Another person needs to write a unit test to assess that the method in class B is delegating to the 'roll' method in class A correctly. In order to do this I simply need to invoke the method X times and check that the score updates.

Currently in the unit test I have a loop that goes round up to 1000 times and if the score hasn't been updated then I assume it is beyond the realms of possibility that the same number could have been rolled consecutively 1000 times! I have however picked the number 1000 out of thin air. I wanted to pick a more accurate number, based on the actual behaviour of Java's Random class.

From reading the API it says it is states it is "a linear congruential pseudorandom number generator..". What I'm trying to ascertain is based on it using a 48-bit, is there a number of times for which it is impossible for the same value to be repeated. E.g. in my scenario where the numbers 1 - 6 could be generated, is it say impossible to get the same number, e.g. 6, more than 20 times in a row? I'm looking for that information if anyone knows it.




mercredi 26 octobre 2016

How to generate random numbers between 2 values, inclusive?

I need help figuring out how to generate a set amount of random numbers between two user-inputted values, inclusively. Just so you know, I have searched for this but am not finding what I have just stated. Here is my code:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    int userBeg, userEnd, outPut;

    cout << "Enter a start value: ";
    cin >> userBeg;
    cout << "Enter an end value: ";
    cin >> userEnd;

    srand(time(NULL)); //generates random seed val

    for (int i = 0; i < 5; i++) {
      //prints number between user input, inclusive
    outPut = rand()%((userEnd - userBeg) + 1); 
    cout << outPut << "  ";
    }//end for

    return 0;
}//end main 

I'm confused with the output I get for the following ranges: 1-100 yield output numbers which fall in-between, but not including, the boundaries such as 50, 97, 24, 59, 22. But, 10-20 yield numbers such as 1, 14, 6, 12, 13. Here, the output is outside of the boundaries as well as in-between them. What am I doing wrong?

Thank you in advance for your help!




Generating random integer between negative and positive range in MATLAB

I'm trying to generate a random integer in the range of -2 and 5 using round and rand functions. I'm able to generate a random integer however it always returns a negative value and a zero.

round(rand(1)*-5)




How do I get the output to produce random numbers?

This is what I have so far

    import java.util.Arrays;

public class Randoms {

    public static void main(String[] args) {
        int[] array = new int [50];
        for (int index = 0; index < array.length; index++) {
            int j = (int) Math.random() * 101 + 1;

            System.out.println(j);
        }

    }

}

My output just produces a bunch of 1s. I want numbers from 0-100? Any help would be appreciated. I am fairly new to Java so sorry if this is a really dumb mistake. Thanks in advance.




Use the same Random Generated Number Several Times

I'm writing a code where the user inputs a sentence, inputting one word at a time. When they type 'exit', the code returns "Your original sentence was sentence. Word number (generate random number) is (the word that corresponds to that number)".

For example, the sentence is "This is a cool code", it'll return "Your original sentence was This is a cool code. Word number 3 is a.

Right now, my code gets two different random numbers and words and says 'list index out of range' when the sentence has more than 4 words. How should I fix this and get it to work properly?

def sentenceSplit():
    print ('Think of a sentence')
    print ('Type the sentence one word at a time pressing enter after each word')
    print ("When you have finished the sentence enter 'exit'")
    print ('')
sentence = []
while True:
    word = input('')
    print ('Accepted', word)
    if word == 'exit':
                print ('')
                print ('Your original sentence was')
                outputString = " ".join(sentence)
                print (outputString)
                wordCount = int(len(outputString))
                pleaseWork =  (random.randint(0,wordCount))
                print('Word number ',pleaseWork,' is ', (sentence[pleaseWork]))

                break
    sentence.append(word)




%random% variable not returning a random number

I'm using this code:

set /a alg=!random!*!activecount!/32768+1

For the most part, it works. HOWEVER, the !random! variable isn't generating a completely random number. instead, it's constantly counting up at a slow pace. Now, assuming the variable !activecount! is equal to 2, it would constantly generate either 1 or 2, without changing, for a VERY long time. Why isn't the random variable randomizing? I tried echoing !random! after the fact, and it generates a random number then. What gives?




Draw with random numbers and limit the # of winners

I need to perform an activity, that is a draw for a duration of three days. But budget I have to limit the # of winners, for example of the 10000 visitors I can only reward 300. I was thinking create 300 random numbers, store and record the visit of users, then validate whether the visitor # is equal to any of those numbers in a PHP script and give the prize. Was it the right way? Thank you very much in advance, waiting for any comments, Good day!




C - How do I use the

I've recently started my degree. One module is C.

I have been given various random number generator exercises to do but I don't understand the instructions given about how to use/implement the <stdlib.h> library and the rand() and srand() functions.

It also talks about int rand(void); and void srand(unsigned int seed);? What are these?

Within the instructions documents, there is also this string of code (which I do not know where to put or what it does for that matter):

random_number = (int) (1O.O*rand()/(RAND_MAX+1.O));

The first exercise is this:

  1. Mean Test - Calculate the mean of 1000 random numbers. the result should be close to 4.5.

Any help would be greatly appreciated! Thanks in advance!