lundi 29 février 2016

If statement to check if variable landed on 2 numbers out of 10

I tried this code, but I'm getting an error. What is an alternative to this?

int chance = rand.Next(1, 11);

if (chance == 1 || 10)
{
    string win = "lose";
}

This is in C#




Looking for a demonstration of the need for Matsumoto's DCMT algorithm in parallel PRNG

In “Dynamic Creation of Pseudorandom Number Generators” Matsumoto and Nishimura cautioned against careless initialization of MT PRNGs for the purposes of parallel simulations which assume the number streams from the different generators are independent of each other:

The usual scheme for PRNG in parallel machines is to use one and the same PRNG for every process, with different intial seeds. However, this procedure may yield bad collision, in particular if the generator is based on a linear recurrence, because in this case the sum of two pseudorandom sequences satisfies the same linear recurrence, and may appear in the third sequence. The danger becomes non-negligible if the number of parallel streams becomes large compared to the size of the state space.

How big does the number of streams have to get for this to be a serious problem? In the case of the standard MT, MT19937, the state space is rather large... I could definitely see there being a linear relationship modulo 219937−1 among 20,000 sequences, but how about a birthday-paradox-style relationship among 400 sequences?

It appears that this is actually a serious problem, because parallel PRNG implementations do include DCMT, but it would be nice to have some examples of failure, and some sense for when this becomes a problem.




Random letter on Button Click?

I have a problem:
I was coding in Android Studio and to get used to it I wanted to make a simple app , that when a button is pressed, it showed a random letter on screen, with the button everything is fine, but I can't code the random letter to appear since I cant use

function 

and Android Studio doesen't even accept

var

could someone give me the code I need for the random letter to appear? What I have is

Btn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
   //here i'd need to enter the function
}




MinGW boost random_device compile error

I need some random numbers for a simulation and are experimenting with the C++ 11 random library using MinGW Distro from nuwen.net.

As have been discussed in several other threads, e.g. why do I get same sequence for everyrun with std::random_device with mingw gcc4.8.1, random_device do not generate a random seed, i.e. the code below, compiled with GCC, generates the same sequence of numbers for every run.

// test4.cpp
// MinGW Distro - nuwen.net
// Compile with g++ -Wall -std=c++14 test4.cpp -o test4

#include <iostream>
#include <random>

using namespace std;

int main(){
    random_device rd;
    mt19937 mt(rd());
    uniform_int_distribution<int> dist(0,99);
    for (int i = 0; i< 16; ++i){
        cout<<dist(mt)<<" ";
        }
        cout <<endl;
}

Run 1: 56 72 34 91 0 59 87 51 95 97 16 66 31 52 70 78

Run 2: 56 72 34 91 0 59 87 51 95 97 16 66 31 52 70 78

To solve this problem it has been suggested to use the boost library, and the code would then look something like below, adopted from How do I use boost::random_device to generate a cryptographically secure 64 bit integer? and from A way change the seed of boost::random in every different program run,

// test5.cpp
// MinGW Distro - nuwen.net
// Compile with g++ -Wall -std=c++14 test5.cpp -o test5

#include <boost/random.hpp>
#include <boost/random/random_device.hpp>
#include <iostream>
#include <random>

using namespace std;

int main(){
    boost::random_device rd;
    mt19937 mt(rd());
    uniform_int_distribution<int> dist(0,99);
    for (int i = 0; i< 16; ++i){
        cout<<dist(mt)<<" ";
        }
        cout <<endl;
}

But this code wont compile, gives the error “undefined reference to ‘boost::random::random_device::random_device()”. Note that both random.hpp and radndom_device.hpp are available in the include directory. Can anyone suggest what is wrong with the code, or with the compiling?




php - Randomization - srand offset

I want to randomize number using given seed and offset. In other words, I look for the correct way do do the following:

function get_random($seed, $offset) {
  srand($seed);
  for ($i = 0; $i < $offset; $i++) {
    rand();
  }
  return rand();
}




How to sort a list of weighted objects in O(n(logn)^2) if the scale used to weigh each object has a 1/3 chance of making an error?

The scale may return the wrong answer with probability at most 1/3. Every time we measure the weight of a stone we have probability 1/3 of getting the wrong answer independently from measure of the weight in previous measures. The scale is used for comparisons. The probability that the sorting is wrong has to be less than 0.01. The malfunction is random.

I've thought about this problem for a while. I think it has to be a randomized algorithm and we use repetition to get a high probability of it succeeding. I think we can prove that the algorithm is correct using Chernoff bounds.




Use ran1 FORTRAN 77 subroutine in FORTRAN 90

I am trying to use ran1 from Numerical Recipes in my FORTRAN 90 code. I think a common way is to compile the old subroutine separately, then use the object file. But here I want to know what change is necessary to use it directly in my code.

FUNCTION ran1(idum)
INTEGER idum,IA,IM,IQ,IR,NTAB,NDIV
REAL ran1,AM,EPS,RNMX
PARAMETER (IA=16807,IM=2147483647,AM=1./IM,IQ=127773,IR=2836,
! NTAB=32,NDIV=1+(IM-1)/NTAB,EPS=1.2e-7,RNMX=1.-EPS)
! “Minimal” random number generator of Park and Miller with Bays-Durham shuffle and
! added safeguards. Returns a uniform random deviate between 0.0 and 1.0 (exclusive of
! the endpoint values). Call with idum a negative integer to initialize; thereafter, do not
! alter idum between successive deviates in a sequence. RNMX should approximate the largest
! floating value that is less than 1.
INTEGER j,k,iv(NTAB),iy
SAVE iv,iy
DATA iv /NTAB*0/, iy /0/
iy = 0
if (idum.le.0.or.iy.eq.0) then !Initialize.
idum=max(-idum,1)
! Be sure to prevent idum = 0.
do 11 j=NTAB+8,1,-1
! Load the shuffle table (after 8 warm-ups).
k=idum/IQ
idum=IA*(idum-k*IQ)-IR*k
if (idum.lt.0) idum=idum+IM
if (j.le.NTAB) iv(j)=idum! Compute idum=mod(IA*idum,IM) without overflows by
enddo 11
iy=iv(1)
endif
k=idum/IQ
idum=IA*(idum-k*IQ)-IR*k
! Compute idum=mod(IA*idum,IM) without overflows by
if (idum.lt.0) idum=idum+IM      ! Schrage’s method.
j=1+iy/NDIV
iy=iv(j)                ! Output previously stored value and refill the shuffle table.

iv(j)=idum
ran1=min(AM*iy,RNMX)    ! Because users don’t expect endpoint values.
return
END 




C++ random class repeat values when run [duplicate]

How do I change this so it gives a different set of values each time it is run?

#include <random>
#include <iostream>

using namespace std;

int main()
{
    random_device rd;
    mt19937 gen(rd()); 

    for(int i=0; i<10; i++)
    {
        std::cout << "Random Num " << i << " = " << gen() << "\n";
    }
}

Right now it gives the same result each time:

Random Num 0 = 2412496532
Random Num 1 = 3119216746
Random Num 2 = 1495923606
Random Num 3 = 3931352601
Random Num 4 = 26313293
Random Num 5 = 2552602825
Random Num 6 = 3745457912
Random Num 7 = 2213446826
Random Num 8 = 4119067789
Random Num 9 = 4188234190




Generating Random Date

I'm a novice Java student. I have only been studying programming for a few months at school, and so I am currently pretty bad at it, and often feel stuck doing my assignments.

Anyway, I have a question regarding an assignment. I have been looking around and not quite finding the answers I need, so I was hoping to find some help on here. It would be much appreciated. My assignment goes like this: "Write a program that creates a Date object and a Random object. Use the Random object to set the elapsed time of the Date object in a loop to 10 long values between 0 and 100000000000 and display the random longs and the corresponding date and time."

We were just introduced to the classes java.util.Random and java.util.Date to work with this assignment, and are expected to use them to create the needed Date and Random objects.

The only things I really know how to do for this assignment are how to start the code:

import java.util.Date
import java.util.Random

public class RanDate {
public static void main(String[] args) {

And how to create the loop:

for (int i = 0; i <= 10; i++) {

I'm sorry if my question was too vague, or if I didn't ask something properly. This is my first time asking for help on this site. Thank you in advance for your help.




Fill Each Square With A Random Color

I am trying to fill the whole screen with squares, each one filled with a different color. I am able to generate the entire screen full of squares, but I cannot get them to be a random color. Here is what I have so far:

import java.util.Random;

public class RGBRandom
{
  public static void main(String[] args)
{
StdDraw.setScale(0, 100);

for (int x = 0; x <= 100; x++)
{     
  for (int y = 0; y <= 100; y++)
  {
    int r = (int)Math.random()*256;

    int g = (int)Math.random()*256;

    int b = (int)Math.random()*256;

    StdDraw.setPenColor(r, g, b);
    StdDraw.filledSquare(x, y, 0.5);
  }
} 
}
}




Is this an elegant solution?

The problem is not complicated. Log randomly a name from an array of names.

My solution comes as this.

var names = [ 'nick', 'rock', 'danieel' ];
function randPicker(names) {
    var randNum = Math.floor((Math.random() * 10));
    var name = randNum <= (names.length - 1) ? console.log(names[randNum]) : randPicker(arguments[0]); 
};

It seems to me that this code is not that beautiful, because im quite sure that there are better ways that perform much faster. Is that true?




Reference that outlines benefits of determinism?

I was recently working on a simulator that uses pseudorandom numbers to introduce variance into the system. The seed was based on the current timestamp (and therefore changed with every run).

After checking in a new command-line flag to allow specification of a fixed RNG seed, a colleague asked me "Why does this matter?"

I didn't know where to start ... the advantages seem obvious:

  • Ensures reproducibility between runs
  • Reduces noise between A/B experiments
  • Eases debugging

Instead of giving a lecture, I'd like to point to some existing article that elaborates on these points. Does anyone know a good article or text?




pass a random generated variable to setInterval

I have animated a dynamic created element with setInterval. When the element is clicked I want it to change to a random direction (left, right, up or down).

I think the problem is that I can´t pass the randomly created direction into the setInterval function.

The html here....

<div id="klicker"></div>

The JavaScript here.....

var box = document.getElementById("klicker");
var x = 1;
var startp = 200;
box.onclick = function() {
    var newdiv = document.createElement('div');
    document.body.appendChild(newdiv);
    newdiv.style.width = 200 + 'px';
    newdiv.style.height = 200 + 'px';
    newdiv.style.backgroundColor = 'grey';
    newdiv.style.position = 'absolute';
    newdiv.style.left = startp + "px";
    newdiv.style.top = startp + "px";
    newdiv.setAttribute('id', 'runner')
    var run = document.getElementById('runner');
    var dire = 'right';
    run.onclick = function() {
        var mov = function() {
            randoms();
        };
        function randoms() {
            alert('ddddd');
            var rnd = (Math.random() * 4) + 1; //ranom number 1-4
            var rnd_down = Math.floor(rnd); //make it en integer
            /*--- make each number a uniqe direction---*/
            if (rnd_down == 1) {
                dire = 'right';
            } else if (rnd_down == 2) {
                dire = 'left';
            } else if (rnd_down == 3) {
                dire = 'up';
            } else {
                dire = 'down';
            }
        };

        var moveit = setInterval(function() {
            movefunc();
        }, 50);

        function movefunc() {
            /*----each direction will make the div travel in diffrent directions--*/
            if (dire = 'right') {
                x = x + 1;
                newdiv.style.left = x + 'px';
            } else if (dire = 'left') {
                x = x - 1;
                newdiv.style.left = x + 'px';
            } else if (dire = 'up') {
                x = x - 1;
                newdiv.style.top = x + 'px';
            } else {
                x = x + 1;
                newdiv.style.top = x + 'px';
            }
        };
    };
}




Randomly sized rectangles on JavaScript canvas

I'm trying to draw randomly sized rectangles on my canvas. This is the code I have but it doesn't show anything when I run it.

 // JavaScript Document
window.addEventListener('load', drawLine);

function drawLine() {
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d'); 
    {
        context.beginPath();
        context.lineWidth = "100";
        context.strokeStyle = 'black';
        context.rect(910, 400, Math.floor((Math.random() * 150) + 150), Math.floor((Math.random() * 150) + 150));
        context.stroke();
        context.closePath();
    }
}




Random generates number 1 more than 90% of times in parallel

Consider the following program:

public class Program
{
     private static Random _rnd = new Random();
     private static readonly int ITERATIONS = 5000000;
     private static readonly int RANDOM_MAX = 101;

     public static void Main(string[] args)
     {
          ConcurrentDictionary<int,int> dic = new ConcurrentDictionary<int,int>();

          Parallel.For(1, ITERATIONS, _ => dic.AddOrUpdate(_rnd.Next(1, RANDOM_MAX), 1, (k, v) => v + 1));

          foreach(var kv in dic)
             Console.WriteLine("{0} -> {1:0.00}%", kv.Key, ((double)kv.Value / ITERATIONS) * 100);
     }
}

This will print the following output:

(Note that the output will vary on each execution)

> 1 -> 97,38%
> 2 -> 0,03%
> 3 -> 0,03%
> 4 -> 0,03%
...
> 99 -> 0,03%
> 100 -> 0,03%

Why is the number 1 generated with such frequency?




RTP: Why are timestamps and sequence numbers started at random value?

In the RTP rfc, it is stated that the sequence numbers and the timestamps start at a random value. There is no explanation for that, and what I found by google'ing is the following: "This is more or less unavoidable if different media types are generated by independent applications, whether these applications reside on the same host or not". I do not understand that explanation. For identification you use the SSRC. I don't see how there could arise any problems if the sequence numbers and timestamps started at 0. Can anyone provide me with an answer?




Randomness of random number algorithms

there are conformity tests to tell whether a particular RNG method, programmable or mechanical is close to so called true random numbers http://ift.tt/1nb8pQy

it is based on the hypothesis that, true random numbers should not have any patterns and regularities. I guess in a short they are trying to ensure "equal distribution" in a large set of data but an homogeneous or equal distribution is another sort of regularity ( A pattern ), wouldnt that be a violation of original randomness theory?

I have made a stock chart (trading) using a random number function (javascript), it draws a chart very similar to natural stock market charts, I am wondering what implications would have when using this technique?

i am not worried about "true randomness" (if there is anything as such) but the conformity tests used to approve those algos maybe a problem, the chart is range bound, it has short trends, noises and everytime something new design when i refresh.

my code is like this:

initialize share price lets say 100.00, then run a loop 10k times, and call random function ( returns between 0 to 1 ) if the value is less than 0.5, i add 0.1 to original price or deduct 0.1, i have also tried randomizing 0.1




How would you sort a list of weight objects in O(n(logn)^2) time if the scale you use to weigh the object has a 1/3 change of malfunctioning?

I've thought about this problem for a while. I think it has to be a randomized algorithm and we use repetition to get a high probability of it succeeding. I think we can prove that the algorithm is correct using Chernoff bounds.




dimanche 28 février 2016

Mysql - how to random select 1 row in a large repetitive set such that each row had an `equal` chance of selection

I im trying to figure out a simple thing:

how to random select 1 row in a large repetitive set such that each row had an equal chance of selection?

For example, a table of products with each product having multiple entries, I just want to select 1 random. But the 'chance' of that one should not be more than others due to its repetition.

One solution is to get unique list (with GROUP BY) and get RANDOM from this subquery. But for a large dataset, thats not an optimal solution, whcihc is what I need help here.

Thanks.




I don't know why my function Flip() in JavaScript isn't returning anything. I want it to return if it is heads or tails

JavaScript - I don't see anything obvious that is wrong

function Flip() {
    var Probability = Math.floor(Math.random());
    if (Probability > 0.5) {
        document.getElementById("message").innerHTML("Heads!");
    }
    if (Probability < 0.5) {
        document.getElementById("message").innerHTML("Tails!");
    }    

HTML - Nothing should be wrong in the HTML (besides selectors)

<body>
    <button onClick="Flip()" id="submit">FLIP THE COIN</button>
    <p id="message"></p>
</body>




Posting random-ish tweet with php and codebird

Ok I'm using php and codebird to generate tweets once an entry has been added to my database and here is the sample of whats working well.

 $params = array(
    'status' => "Some text " . $name[0] ." some text " . $body
 );
 $reply = $cb->statuses_update($params);

This works with ever database entry with no issues.

So now I want to create a few different standard messages and pick one at random. I've been able to partially achieve this with array_rand() with the following:

$tweets = array(
    "Some text " . $name[0] ." Some text " . $body,
    "Different text " . $name[0] ." different text " . $body,
    "text " . $name[0] ." text " . $body,
    "new text ". $name[0] ." new text " . $body
);

$key = array_rand($tweets, 1);
$params = array(
    'status' => $tweets[$key]
);

This seems to be working most the time but it seems that 15% of the time a database entry that should trigger a new tweet doesn't. I've seen every one of my tweet options published as a tweet so it would seem its a random problem with using array_rand(). Thanks in advance




need multiple random images - every call to php from html begins the randomization again, causing duplicates

html calling for a random image:

<img src="/test/art/rotate.php?i=0">
<img src="/test/art/rotate.php?i=1">
<img src="/test/art/rotate.php?i=2">

php file i'm accessing:

<?php

// rotate images randomly but w/o dups on same page - format:

// <img src='rotate.php?i=0'> - rotate image #0 - use 'i=1'

// for second, etc

// (c) 2004 David Pankhurst - use freely, but please leave in my credit
$images = array_unique($images);
$images=array( // list of files to rotate - add as needed


  "img5.jpg",

  "img6.jpg",

  "img7.jpg",

  "img8.jpg",

  "img9.jpg",

  "img10.jpg",

  "img11.jpg",

  "img12.jpg",   

  "img13.jpg",

  "img14.jpg",

  "img15.jpg",  

  "img16.jpg",   );


$total=count($images);

$secondsFixed=3600; // seconds to keep list the same

$seedValue=(int)(time()/$secondsFixed);

srand($seedValue);

for ($i=0;$i<$total;++$i) // shuffle list 'randomly'

{

  $r=rand(0,$total-1);

  $temp =$images[$i];

  $images[$i]=$images[$r];

  $images[$r]=$temp;

}

$index=(int)($_GET['i']); // image index passed in

$i=$index%$total; // make sure index always in bounds

$file=$images[$i];

header("Location: $file"); // and pass file reference back

?>

I get images to display, but there are duplicates. I think this is because every call to the php file is a new call, the already loaded images aren't remembered as already loaded. How do I prevent showing duplicates?




Park Miller algorithm (python 3)

So I'm trying to make a python code that generates random numbers using the park-miller algorithm. I know that the general idea should be:

seed = (16807*seed) % (2147483947)

but I am not sure how I would actually implement this into python. How would I specify returning a number from say 0-9?




Python - object has no attribute 'randint'

I want to import the random module to use randint and get a random number from 1 to 10. I have this so far:

import random  
number = random.randint(1,10)  
print number  

I've also tried importing randint specifically, but that doesn't work either. With the code above, I get object has no attribute 'randint.'

I've come across plenty of people getting this error. The solution has always been to find the file you've named random.py and change its name because the script is loading that instead of the real module. I understand that, but I can't find that file; I've searched high and low, and the only file I can find named random.py is the real module in the Python library list.




How to remove duplicates from array using for loop

In this code I have found duplicates from an array and I want to remove them. The output then will be unique generated numbers. I am required to use math.random and modulo. Anyone have any clues?I tried to store them in an array but then the original array has 0's and 0 is part of my domain for the random number generation (from 0 to 52).

public class Decks {

 public static void main(String[] args) {

generate();

}

 public static void generate() {
int deckOfCard[] = new int[52];

for (int counts = 0; counts < 52; counts++) {

    deckOfCard[counts] = (int) (Math.random() * 51);

}

for (int i = 0; i < deckOfCard.length - 1; i++) {

    for (int j = i + 1; j < deckOfCard.length; j++) {

        if ((deckOfCard[i] == (deckOfCard[j])) && (i != j)) {

            System.out.println("DUPLICATE " + deckOfCard[i]);

        }
    }
}

for (int count = 0; count < deckOfCard.length; count++) {

    System.out.print("\t" + deckOfCard[count]);

}
}




Convert random to int visual studio 2015

why is this not working? It is in visual studo 2015, windows forms application C#

namespace guessing
{
    public partial class Form1 : Form
    {
        Random rnd = new Random();
        int rndm = rnd.Next(1, 13);

there is an error under rnd, which says:

"A field initializer cannot reference the non-static field, method, or property 'Form1.rnd' "




Unique random numbers using Math.Random and Modulus

Help, I am to Use Math.random()and the remainder operator to generate 52 distinct numbers from 0 to 51. These numbers will represent a deck of card and let’s call it deckOfCard. (Now you have a one-dimensional array of size 52.) For this step, you should write a method called generateCardwhich returns nothing but accepts one argument which is the array variable that represents the deck of card(pass by value). For the output, I am trying to get UNIQUE random numbers.

public class Decks {

public static void main(String[] args) {

    generate();

}

public static void generate() {
    int deckOfCard[] = new int[52];

    for (int counts = 0; counts < 52; counts++) {

        deckOfCard[counts] = (int) (Math.random() * 51);

    }

    for (int count = 0; count < deckOfCard.length; count++) {

        System.out.print("\t" + deckOfCard[count]);

    }

}
}




How to generate a random double between 0 and a variable in c++

Is there a way of generating a random double between 0 and a variable. The variable is of type double and changes each time the code is run so the range in which the number can be chosen from can vary, but it will always be less than 1. I tried to generate a number and cast it to a double but that didn't work.




Xcode Cocoa application how can I Nsstring @"", something

So I have a problem... Here is my code.

NSString *targetPath =@"/Users/miguelcosta/Desktop/Image.png";

So in this NSString I want to do something like this...

NSString *targetPath =@"/Users/miguelcosta/Desktop/Image", RandomNumber + @"png";

How can I do that?

I hope that you understand... Thanks for your help!




Counting/random int in while loop

I want this while loop to change numbers with every iteration (both the count and random int.) but when I run the program, the loop just goes on with the same numbers on the count and random int.:

# if 4 sides 
die1 = random.randint(1,4)
die2 = random.randint(1,4)
count = 1 

while sides == 4 and die1 != die2:
    print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
    count == count + 1

print ("You got snake eyes! Finally! On try number", count,".")




Variables being ran generated are displaying int or displaying cards suits (Black Jack program)

When running the program the output is obviously the to string method written to display the cards value and suit. When running the program it outputs the joption message "Would you like to play (Yes or No)" when you select yes it outputs 0 for both values and null for its suit.

// Card.java, BlackJack.java
// Driver class

package blackjack;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class BlackJack {

      public static int userTotals = 0;
      public static int computerTotals = 0;
      public static Random myRan = new Random();

    public static void main(String[] args) 
    {
       int userAnswer;
       userAnswer = JOptionPane.showConfirmDialog(null, "Would you like to play?");

       while (userAnswer == JOptionPane.YES_OPTION)
       {
           drawUserCard();
           drawComputerCard();
           System.out.println("\n");
           userAnswer = JOptionPane.showConfirmDialog(null, "Would you like to play?");
       }

       if (userTotals > computerTotals  && userTotals <= 21)
       {
           JOptionPane.showMessageDialog(null, "User won this round.");
       }
       else if(computerTotals > userTotals && computerTotals <= 21)
       {
           JOptionPane.showMessageDialog(null, "Computer won this round.");
       }
       else if(userTotals == computerTotals && userTotals <= 21 && computerTotals <= 21)
       {
           JOptionPane.showMessageDialog(null, "It's a tie!");
       }
       else{
           JOptionPane.showMessageDialog(null, "No winner.");
       }

    }

    public static void drawUserCard()
    {
        int cardVal = myRan.nextInt(10) + 1;
        Card userCard = new Card("club", cardVal);
        userTotals += userCard.getCardValue();
        System.out.println("User: " + userCard);
        System.out.println("User Totals: " + userTotals);         


    }

    public static void drawComputerCard()
    {
        int cardVal = myRan.nextInt(10) + 1;
        Card computerCard = new Card("spades", cardVal);
        computerTotals += computerCard.getCardValue();
        System.out.println("Computer: " + computerCard);
        System.out.println("Computer Totals: " + computerTotals);       
    }

}


// Card.java, BlackJack.java

package blackjack;

public class Card
{
    private String suit;   //Clubs, Diamonds, Hearts, Spade
    private int cardValue; // 1 - 11; 

    public Card (String aSuit, int aCardValue)
    {
        aSuit = suit;
        aCardValue = cardValue;
    }

// Getters and setters

    public String getSuit(){
        return suit;
    }

    public int getCardValue(){
        return cardValue;
    }

    public void setSuit(String aSuit){
        suit = aSuit;
    }

    public void setCardValue(int aCardValue){
        cardValue = aCardValue;
    }

    public String toString(){
        String displayCardContent = "The card drawn is " + cardValue + " of " + suit + ".";
        return displayCardContent;
    }
}




Does random objects successively created within a very short peroid of time have the same seed value?

I am wondering, in languages like java and c#, default random objects have time-based seed value and if these objects are created within a very short period of time, like creating inside double or triple looping, won't they have same seed and produce the same results? Is this behavior platform-dependent? Can the random objects of multiple thread acts like that?




Why does rand() % 50 get a random number between 0 and 50?

This code:

cout << rand() % 50 << endl;

generates a random number between 0 and 50. Why is this?




generate random number not working

Hi great ppl of stackoverflow.

i am trying to generate random numbers using jquery. However, it didnt generate when i refresh the broswer.

my html as follows:

<td colspan="3" id="number1" class="numberStyle"><span>1</span></td>
<td colspan="3" id="number2" class="numberStyle"><span>2</span></td>

my script as follows:

 $(document).ready(function(){
var num1;
var num2;

num1=Math.floor((Math.random()*3)+1);
document.getElementById("number1").innerhtml = num1;

num2=Math.floor((Math.random()*3)+1);
document.getElementById("number2").innerhtml = num2;

});

Kindly advise. thanks a lot




samedi 27 février 2016

Having lots of trouble in creating a random draft for my website

I need to create a drafting feature that draws 2 names from a list with x values for my website, with the possibility to restrict some of them from being able to be drafted together i've been stuck for over a month and it's getting infuriating. some help? i'm kind of new but never faced problems that i couldnt find answer for here nor google...




Random number generator to array, with no duplicates java

So I am trying to make a program that produces an array of 20 random numbers, that does not have duplicates (to the end user). Here is my code so far

import java.util.*;
public class randomprog
{
public static void main(String args[])     
{
    Random rand = new Random();
    int[] list = new int[20];
    boolean generating=true;
    int counting=0;
    while(generating)
    {
        int testNum= rand.nextInt(30)+1;
        if (Arrays.asList(list).contains(testNum))
        {}
        else
        {
            list[counting]=testNum;
            counting++;
            System.out.println(testNum);
        }
        if(counting>=20)
        {
            generating=false;
        }
    }
}}

So as you can see I have already tried using Arrays.asList(list).contains(mynumber) however I still recieve duplicates in my output like 29 4 4 1 20 30 20 23 30 11 6 7 27 14 16 8 4 19 7 15

Any suggestions?




Generate an independent and identically distributed (i.i.d.) random gaussian matrix

What is the best/accurate way to create an i.i.d. random Gaussian matrix using Python?

What is pseudo-random? And would that suffice?




random.randint on lists in python

im very new to programming , and i've been cracking my head on this : i want to create a list called dasos , and fill it with 15 zeros , then i want to change the 0 to 1 in 5 random spots of the list , so it has 10 zeros and 5 ones ,here is what i tried

import random, time

dasos = []

for i in range(1, 16):
  dasos.append(0)

for k in range(1, 6):
  dasos[random.randint(0, 15)] = 1

some times i would get anywhere from 0 to 5 ones but i want exactly 5 ones , if i add a

print(dasos) 

to see my list i get :

IndexError: list assignment index out of range

thanks in advance




Small Basic - More "natural" terrain generation for simple Minecraft clone I've found online

This is the main focus of the question:

For BlockX = 0 To 900 Step 30 'Try to carve out Hills
 GraphicsWindow.BrushColor = "SkyBlue"
 depth = Math.GetRandomNumber(5)
 GraphicsWindow.FillRectangle(BlockX,BlockY,30,depth*30)
EndFor

And the whole program:

GraphicsWindow.Clear()
GraphicsWindow.CanResize = 0
GraphicsWindow.BackgroundColor = "SkyBlue"


gw = GraphicsWindow.Width
gh = GraphicsWindow.Height
gw = 900
gh = 600

For BlockX = 0 To 900 Step 30
For BlockY = 420 to 270 Step -30
    b = Math.GetRandomNumber(2)    
    If b = 1 Then 'Stone
      GraphicsWindow.DrawImage("C:\AllVersions\Versions\v0.4\SBCraft\assets\rock.png",BlockX,BlockY) 
    EndIf
If b = 2 Then 'Dirt
      GraphicsWindow.DrawImage("C:\AllVersions\Versions\v0.4\SBCraft\assets\dirt.png",BlockX,BlockY)
    EndIf
  EndFor 
EndFor

For BlockX = 0 To 900 Step 30 'Grass Layer
  BlockY = 240
  GraphicsWindow.DrawImage("C:\AllVersions\Versions\v0.4\SBCraft\assets\grass.png",BlockX,BlockY)
EndFor

For BlockX = 0 To 900 Step 30 'Try to carve out Hills
  GraphicsWindow.BrushColor = "SkyBlue"
  depth = Math.GetRandomNumber(5)
  GraphicsWindow.FillRectangle(BlockX,BlockY,30,depth*30)
EndFor   

Explanation: I found a very simple Minecraft clone online, and I'm trying to expand to it by adding a terrain generator. The terrain generator supports 3 blocks dirt, grass, and stone. For the bottom 6 layers, dirt and stone randomly generate, and a layer of grass on top. The main focus of this question is the last For statement. For each column, a random number is selected. The random number selected is how many blocks are deleted in each column. But this makes very jagged and unnatural terrain. Is there some weird trigonometric thing I can do to make hills / natural terrain, or another way?




Does rand() function with the same seed gives the same random numbers on diferent PC's? [duplicate]

I would like to know if I will get the same random numbers on all computers using the same srand() seed.

If not, how can I achieve that.




Randomly italicize words in a bunch of texts on javascript button click

I know it's a weird thing to do but I'd like to create a javascript button that, when clicked on, italicizes randomly a bunch of texts. "Italicize randomly" means that only certain words, say 1 out of 20, should be in italics, but each time different ones (regardless of their function or nature -- verb, noun, subjet, preposition etc).

I was thinking of calling an array and then get "str.italics()", but that would mean that I'll have to methodically copy into the code all texts' lexique, right ? I'm sure there's a prettier way to do that.

Thanks.




C# Random class strange errors

namespace RandomBug

{ class Program { static Random rnd = new Random(0); static void Main(string[] args) {
for (int i = 0; i < 1000000; i++) Program.rnd.Next(100);
}

}

}

This code gives me all kind of strange inner errors like: Null Access, Array out of range, etc. This not happen if the Random is not static. I'm using VS 2015. I found this problem after I saw bad random results on C# Unity.




can random C++ 2011 standard functions be called from a C routine?

I need to generate a random integer from a range and have found very interesting what is discussed here in the answer by @Walter. However, it is C++11 standard and I need to use C, is there a way of making the call from C? I reproduce his answer here:

#include <random>

std::random_device rd;     // only used once to initialise (seed) engine
std::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased

auto random_integer = uni(rng);




vendredi 26 février 2016

show random number of elements with JavaScript

I have a quick question, I have a random function in my code, and I would like that random function to randomize 9 numbers, and depending in the number that returns, that would display the number of happy faces on my html.

My first question is how do I connect the function with my happy faces, and the second is, should I have all nine happy faces on my html, or should I just have one, and generate the others (depending on the random number) dynamically. right now I have a display: none on the css, I just commented out so you guys could see it.

I added some of the code here

'use strict';

$(document).ready(init);

var globalNum;

function init(){
        $('.number').click(clickNum);
        console.log('hello from jQuery!');
}

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


console.log(getRandomInt(1,9));

function clickNum(){
        var num = $(this).text();
        console.log(num)
        // addNumToDisplay(num);

}

// function displayNum(num){
//      globalNum = 
//      var currentNumber = $('.number').text(num);
//      console.log(currentNumber);
// }
* {
        /*outline: 2px solid red;*/
}

p {
        padding: 50%;
        font-size: 32px;
        font-weight: bold;
        text-align: center;
        background: #dbdfe5;
}

body {
        padding-top: 60px;
        padding-bottom: 40px;
}

.col-sm-8 {
        width: 80%;
        height: 200px;
}

.jumbotron {
        width: 800px;
        margin: 0 auto;
        height: auto;
}

.fa-smile-o {
        background-color: yellow;
        border-radius: 50%;
        height: .9em;
    width: .9em;
    /*display: none;*/
}

.btn-group {
        position: relative;
        left: 40%;
}

.numbers {
        margin-top: 15px;
        width: 900px;
}

.number {
        font-size: 40px;
        letter-spacing: 10px;
}

#right {
        position: relative;
        height: 80px;
        width: 120px;
        font-size: 30px;
        background-color: lime;
        color: white;
}

.rightButton {
        margin-left: 50px;
        position: absolute;
}

#result {
        font-size: 30px;
        margin-left: 40px;
        padding: 30px;
        background-color: white;
        border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <title>Game 5</title>
        <link rel="stylesheet" href="http://ift.tt/1jAc5cP" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <link href="http://ift.tt/1PinXyn" rel="stylesheet" integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous">
        <link rel="stylesheet" href="style.css">
</head>
<body>
        <div class="container">
                <div class="jumbotron firstBlock">
                        <i class="fa fa-smile-o fa-4x"></i>
                        <i class="fa fa-smile-o fa-4x"></i>
                        <i class="fa fa-smile-o fa-4x"></i>
                        <i class="fa fa-smile-o fa-4x"></i>
                        <i class="fa fa-smile-o fa-4x"></i>
                        <i class="fa fa-smile-o fa-4x"></i>
                        <i class="fa fa-smile-o fa-4x"></i>
                        <i class="fa fa-smile-o fa-4x"></i>
                </div>
                <div class="btn-group" role="group" aria-label="...">
                  <button type="button" class="btn btn-primary">Restart</button>
                  <button type="button" class="btn btn-warning">Reroll</button>
                  <button type="button" class="btn btn-success">Check</button>
                </div>
                <div class="jumbotron numbers">
                        <button class="number">1</button>
                        <button class="number">2</button>
                        <button class="number">3</button>
                        <button class="number">4</button>
                        <button class="number">5</button>
                        <button class="number">6</button>
                        <button class="number">7</button>
                        <button class="number">8</button>
                        <button class="number">9</button>
                        <span class="right">
                                <span id="result">5</span>
                                <span class="rightButton">
                                <button id="right">Right!</button>
                                </span>
                        </span>
                </div>
        </div>
<script src="http://ift.tt/1L6zqzP"></script><script src="http://ift.tt/1jAc4pg" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>  
<script src="main.js"></script>     
</body>
</html>



How to store random values in an array of structs

Ok, so what I am needing to do is simulate 2 die rolls 100 times and store each rolls in an array of structs, then process the sum of the two rolls and record the occurences.

Seems easy enough here what i got:

        #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <math.h>
    #include <iostream>
    #include <iomanip>
    #include <windows.h>

    using namespace std;

    struct dice{
        int dice1;
        int dice2;

    };

    int main( void ){


        int i = 0;
        int r = 0;
        int number [14] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0};


        struct dice rolls[ 100 ];

        for(i=0; i < 100; i++){
            rolls[ i ].dice1 = rand() % 6 + 1;
            rolls[ i ].dice2 = rand() % 6 + 1;
            if(rolls[i].dice1 + rolls[i].dice2 == 2){
                number[2]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 3){
                number[3]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 4){
                number[4]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 5){
                number[5]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 6){
                number[6]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 7){
                number[7]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 8){
                number[8]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 9){
                number[9]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 10){
                number[10]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 11){
                number[11]++;
            }else if(rolls[i].dice1 + rolls[i].dice2 == 12){
                number[12]++;
            }

        }


        cout<< setw(21) <<"Dice Result: "<< setw(29) << "Number of Occurence:"<<endl;
        for(i = 0; i < 14; i++){
            cout<< setw(20)<< i << setw(30) <<number[i]<<endl;
            Sleep(100);
        }

        return 0;
    }

What the hell am i missing it seems like its all there but i keep getting a non-random number of occurences? Any help of insight would be appreciated!




numpy.random.exponential(scale=1.0) returns numbers greater than 1

Unless I've gone completely insane, the documentation for numpy.random.exponential()

http://ift.tt/1OBOz73

suggests that setting the scale parameter to 1.0 should guarantee that function calls return a number between 0.0 and 1.0, since it is only defined for x > 0.

I've graphed it on wolfram alpha to verify I'm not going insane and it does range from 0 to 1.

http://ift.tt/1TcMkj5

I also tried both numpy.random.exponential() since the default argument is 1.0 and numpy.random.standard_exponential(), but both sometimes give me values greater than 1.

I feel like I've made some silly mistake in my understanding but cannot find it. Any help would be greatly appreciated.

Example code that I ran:

import numpy as np
print np.random.exponential(scale=1.0)

Example returned value:

1.56783951494




Photoshop random action execution script

I am asking if someone could write an example of a Photoshop script that randomly executes an array of named actions. Thank you.




Change image by id

I'm totally new in JavaScript. I need to change image randomly on click. Here is my code. What's wrong? I'm trying to make a dice game where you roll a dice and a image value pops. I only get the number change on screen when i click on image, but the image changes from 1.jpg to 6.jpg and thats all.

<!DOCTYPE html>
<hml>
<body>


<img id="myImage" onclick="changeImage()"  src="1.jpg" width="100" height="100">

<p id="pl" ></p>

</body>

<script>
function myFunction() {
    var x = Math.floor((Math.random() * 6) + 1);
    document.getElementById("pl").innerHTML = x;
}

</script>

<script>
function changeImage() {
    var image = document.getElementById('myImage');
    var pl;

    pl = myFunction();
    if (pl == 1) {
        image.src = "1.jpg";
    } else if (pl == 2) {
        image.src = "2.jpg";
    } else if (pl == 3) {
        image.src = "3.jpg";
    } else if (pl == 4) {
        image.src = "4.jpg";
    } else if (pl == 5) {
        image.src = "5.jpg";
    } else {
        image.src = "6.jpg";
        }
}
</script>


</html>




How to evaluate an array of non-repetitive numbers?

I am trying to create an array of numbers that are not repeated. The order of priority is from top to bottom, left to right, where I'm trying to get a range of x to y. But need dont be repeat values in ranges

  Dim arrayCarton(9, 3) As Integer

    Private Sub generar_carton()
        Randomize()
        filas = 3
        columnas = 9
        Dim RandomNumber As Integer
        For j = 0 To columnas - 1
            For i = 0 To filas - 1
                Dim label As Label = CType(Panel2.Controls("Carton" & i & j), Label)
                If j = 0 Then
                    RandomNumber = CInt(Math.Floor(((9 * (j + 1)) - 1) * Rnd())) + 1                   
                End If
                If j < 8 And j > 0 Then
                    RandomNumber = CInt(Math.Floor(((j * 10 + 9) - j * 10) * Rnd())) + j * 10

                End If
                If j = 8 Then
                    RandomNumber = CInt(Math.Floor(((9 * 10) - j * 10) * Rnd())) + j * 10 + 1
                End If
                arrayCarton(j, i) = RandomNumber
                label.Text = arrayCarton(j, i)
            Next
        Next
    End Sub

One can see that some numbers are repeated, output:

enter image description here




"cat /dev/random" versus "tail -f /dev/random"

Statement

cat /dev/random

keeps producing output, as expected, but

tail -f /dev/random

hangs (at least on OSX and SUSE). Why the latter statement hangs?




Random sample from a very long sequence, in python

I have a long python generator that I want to "thin out" by randomly selecting a subset of values. Unfortunately, random.sample() will not work with arbitrary sequences. Apparently, it needs something that supports the len() operation (and perhaps non-sequential access to the sequence, but that's not clear). And I don't want to build an enormous list just so I can thin it out.

As a matter of fact, it is possible to sample from a sequence uniformly without knowing its length-- there's a nice algorithm in Programming perl that does just that. But does anyone know of a standard python module that provides this functionality?

Demo of the problem (Python 3)

>>> import itertools, random
>>> random.sample(iter("abcd"), 2)
...
TypeError: Population must be a sequence or set.  For dicts, use list(d).

On Python 2, the error is more transparent:

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    random.sample(iter("abcd"), 2)
  File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 321, in sample
    n = len(population)
TypeError: object of type 'iterator' has no len()

If there's no alternative to random.sample(), I'd try my luck with wrapping the generator into an object that provides a __len__ method (I can find out the length in advance). So I'll accept an answer that shows how to do that cleanly.




Random Number Resets

My random number generates on page load, but seems to reset when the user clicks the "Guess" button. I still have a lot of building to go with this, but at the end I want the user to be able to make multiple guesses to guess the random number. I want it to generate when the page first comes up and stay the same until correctly guessed. I'm not sure what I'm doing wrong and just starting this program. If you answer, please also explain, as I'm trying to learn what I'm doing. Thank you!

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>PHP Homework 2</title>
        <link rel="stylesheet" href="styles/styles.css">
    </head>

    <body>
        <section id="main">
            <h1>Play the Guessing Game!</h1>
            <section id="left">
                <h2>Take a Guess!</h2>
                <form action="mine.php" method="post">
                    <div id="guessBox">
                        <label id="guessLB">Your Guess:</label>
                        <input id="guessTB" class="num" type="number" name="guessTB" max="1000" min="1">
                        </input>
                    </div>
                    <input type="submit" id="guessButton" name="guessBTN" value="Guess" />
                </form>
            </section>
            <section id="right">
                <h2>Game Stats</h2>
                <?php 

                    if(isset($_POST['guessTB'])) 
                    {
                        $randomNum = $_POST['guessTB'];
                    } 
                    else 
                    {
                        $randomNum = rand(1,100);
                    }                       

                    echo "<p>Random Number: $randomNum</p>";
                ?>      
            </section>
        </section>          
    </body>
</html>

UPDATE: My HTML has remained the same, and I'm posting my new PHP code. But I used a session and wrote some more. However, I've come across two problems:

1) If I refresh the page, I get an error that says that the first instance of $randomNum below the session_start(); is unidentified.

2) It seems that it remembers my very last guess in the game. If I close out the page and reopen it, I immediately get one of the messages that my guess was too high or too low, even before making a guess. Any advice is appreciated!

<?php
                    session_start();

                    $randomNum = $_SESSION['randomNum'];
                    $guess = $_POST['guessTB'];

                    if(!isset($_SESSION['randomNum']))
                    {
                        $_SESSION['randomNum'] = rand(1,1000);
                    }
                    else
                    {   
                        if($guess < $randomNum)
                        {
                            echo "<p>Your Guess is Too Low! Try Again!</p>";
                        }

                        else if($guess > $randomNum)
                        {
                            echo "<p>Your Guess is Too High! Try Again!</p>";
                        }

                        else
                        {
                            echo "<p>You Won!</p>";
                            $_SESSION = array();
                            session_destroy();
                        }
                    }           

                    echo "<p>Guess: $guess</p>";
                    echo "<p>Random Number: $randomNum</p>";
                ?>  




How to group like numbers using c++

So I have written a program to simulate the sum of 10,000 dice rolls and output the results. Now I need to group together all the duplicate numbers and see how many times each one was rolled.

for (int totalrolls = 0; totalrolls < 10000; totalrolls + 1) {
    int dice1 = rand() % 6 + 1;//1st roll
    int dice2 = rand() % 6 + 1;//2nd roll
    int sumtotal = dice1 + dice2;//Sum of the two dice 
    cout << "Sum of dice rolls " << sumtotal << endl;
}

Here is the code I have written for the first part. maths is not really my strong suit so I would appreciate any method that can help me solve this problem.




How to change the domain from random generated emails in Faker Library using Robot Framework

I am using Faker Library to generate emails from some automation tests like a Register process. Can anyone tell me what file should I edit with the new email domain? Right now, all generated emails have @hotmail.com and I want that changed in something like mydomain.com.

I've manage to install the library, to import it in RIDE and to make a register process using random generated data, but like I said it will be nice if I could change the domain for random generated emails.

Thank you!




Java random color to blocks

So I am programming the game breakout in Java and I already got an array with bricks, but I want to give the brick (or rows of bricks) random colors. I have the possibility of 4 different colors; red, green, blue, yellow. But with my code shown below, I only get the different colors when I re-open my window and game. Can someone help me to give random colors to the blocks?

public void prepareBlocks() {
    int spacing = Breakout.BLOCKSPACING_Y;

    Random rand = new Random();
    int  n = rand.nextInt(4) + 1;
    Color colour = new Color(n);

    if (n==1){
        colour = Color.red;
    } if (n==2){
        colour = Color.yellow;
    } if (n==3){
        colour = Color.green;
    } if (n==4){
        colour = Color.blue;
    }

    lines[0] = new Line(0, colour);
    lines[1] = new Line(BLOCKHEIGHT+spacing, colour);
    lines[2] = new Line(BLOCKHEIGHT*2+2*spacing, colour);
    lines[3] = new Line(BLOCKHEIGHT*3+3*spacing, colour);
    lines[4] = new Line(BLOCKHEIGHT*4+4*spacing, colour);
    lines[5] = new Line(BLOCKHEIGHT*5+5*spacing, colour);

    for(int i = 0; i<lines.length; i++) {
        blockCount += lines[i].numberblocks;
        lines[i].fill();
    }
}




Testing Random Number Generators(RNG)

There are numerous tests of RNGs. Consider that we tested RNG with lots of different seeds and the output is as follows: with certain seeds the RNG passes the test, with other seeds RNG doesn't pass. By passing I mean we 1.fix significance level, 2. find critical value, 3.If the test output is bigger than critical value we reject. Or we may do something like that with p-values. We can fix the seed and for fixed seed take random number sequences from RNG, and we see for some sequences RNG passes the test, for others doesn't pass. So the MAIN question is how check whether RNG good or not, IF some of sequences pass the test, some sequences of THE SAME RNG don't pass? Should I plot the distribution of p-values of test outputs, which we know that is uniformly distributed ?

Thank you very much in advance.




(C#) How to fill a 2D array with 2 different numbers evenly, but randomly?

For a randomized tic-tac-toe game simulator, I need to utilize a 2D array to simulate a round between 2 players. To fill the array, I've been using a simple randomizer to generate a random number between 0 and 1.

    //create 2D array
  const int ROWS = 3;
  const int COLS = 3;
  int[,] tictactoeArray = new int[ROWS, COLS];
   //create random variable
  Random rand = new Random();

   //method to fill array with random values between 0 and 1.
  private void RandomizeArray(ref int[,] iArray)
  {
      for (int row = 0; row < ROWS; row++)
      {
          for (int col = 0; col < COLS; col++)
          {
              tictactoeArray[row, col] = rand.Next(2);
          }
      }
  }

But when I use a random number generator like this, I occasionally end up with an impossible combination of values in relation to tic-tac-toe. As in the value 1 will occur 6 or more times, and make the game unfair for the other "player". I've done extensive searching, but haven't found a way to (more or less) evenly distribute the 2 values. Any suggestions?




Code to generate A-Z generates H, 72,

I am using the following code:

srand(time(NULL));
int r = rand() % 25 + 65;
char c = (char) r;
fprintf(stdout, "%c", c);
char d = (char) r;
fprintf(stdout, "%d", d);
char e = (char) r;
fprintf(stdout, "%e", e);
NSLog(@"%c");
NSLog(@"%d");
NSLog(@"%e");
_firstRandomLetter.text = [NSString stringWithFormat:@"%c", c];
_secondRandomLetter.text = [NSString stringWithFormat:@"%d", d];
_thirdRandomLetter.text = [NSString stringWithFormat:@"%e", e];

...to try and generate 3 letters from A to Z and display them. However, I get bizarre things such as 72 and ... as results. Everything displays fine.




Implicit declaration of functions srand, rand and system

Trying to solve an exercise where I have to print a random temperature value between 35°C & -10°C every 5 seconds followed by the date and time. Everything looks to be working as intended, however when I enter the code in a test script I get following errors.

implicit declaration of functions errors This is my code:

#include<stdio.h>
#include<unistd.h>
#include<time.h>
#define temp_max 35
#define temp_min -10
#define FREQUENCY 5

int main(void)
{
srand(time(NULL));
while(1)
{
int number = rand() % (temp_max*100 - temp_min*100) + temp_min*100;
double temperature = (double) number;
temperature /= 100;
printf("Temperature=%1.2f @ ",temperature);
fflush(stdout); 
system("date");
sleep(FREQUENCY);
}
return 0;
}

These are my results:

These are my results

This is what the test script checks for:

This is what the test script checks for

As I am unable to see my own mistakes, any help would be greatly appreciated.




Not being able to use Math.random properly

I've been working on a little bacteria simulator where the directions the bacteria take is "random", but it's creating a pattern where all bacteria go down the screen, why is this? what am I doing wrong?

My code:

var sandbox = "#main";
spawn(1);
for (var i = 0; i < 10; i++) {
  $(sandbox).animate({
    "height": $(sandbox).height()
  }, 500, function() {
    step();
  });
}

function spawn(amount) {
  var WIDTH = $(sandbox).width();
  var HEIGHT = $(sandbox).height();

  for (var i = 0; i < amount; i++) {
    addLiving(Math.round(Math.random() * 9999999), Math.round(Math.random() * WIDTH), Math.round(Math.random() * HEIGHT), 15);
  }
}

function addLiving(ID, LEFT, TOP, FOOD) {
  $(sandbox).append('<div id="id' + ID + '" class="livingBeing" style="position:absolute;top:' + TOP + 'px;left:' + LEFT + 'px;background-color:#000;width:1px;height:1px" food="' + FOOD + '"></div>');
}

function step() {
  $(".livingBeing").each(function() {
    move(this);
    eat(this);
    split(this);
    if (Math.round(parseInt($(this).attr("food"), 10)) > 0) {
      $(this).attr("food", Math.round(parseInt($(this).attr("food"), 10) - 1));
    } else {
      $(this).remove();
    }
  });
}

function move(living) {
  var way = Math.round(Math.random() * 3) + 1;
  console.log(way);
  if (way === 1) {
    $(living).css({
      'top': "+=1px"
    });
  }
  if (way === 2) {
    $(living).css({
      'top': "-=1px"
    });
  }
  if (way === 3) {
    $(living).css({
      'left': "-=1px"
    });
  }
  if (way === 4) {
    $(living).css({
      'left': "+=1px"
    });
  }

  if ($(living).position().top > $(sandbox).height()) {
    $(living).css({
      'top': "-=1px"
    });
  }
  if ($(living).position().top < $(sandbox).height()) {
    $(living).css({
      'top': "+=1px"
    });
  }
  if ($(living).position().left > $(sandbox).height()) {
    $(living).css({
      'left': "-=1px"
    });
  }
  if ($(living).position().left < $(sandbox).height()) {
    $(living).css({
      'left': "+=1px"
    });
  }
}

function eat(living) {
  //if livingBeing1 is now at the same spot as livingbeing2 then livingBeing2 dies and
  //livingBeing1 gets livingBeing2's food
  $(".livingBeing").each(function() {
    if ($(this).position().top === $(living).position().top && $(this).position().left === $(living).position().left && $(this).id !== $(living).id) {
      $(living).attr("food", parseInt($(living).attr("food"), 10) + parseInt($(this).attr("food"), 10));
      $(this).remove();
    }
  });
}

function split(living) {
  //if food greater than/equal (Math.random()*10)+2; then split
  if (parseInt($(living).attr("food"), 10) >= (Math.random() * 20) + 10) {
    addLiving(Math.round(Math.random() * 9999999), $(living).position().left + 1, $(living).position().top + 1, Math.floor(parseInt($(living).attr("food"), 10) / 2));
    $(living).attr("food", Math.floor(parseInt($(living).attr("food"), 10) / 2));
  }
}
#main {
  position: fixed;
  width: 100px;
  height: 100px;
  border: 1px solid #C3C3C3;
}
<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript" src="http://ift.tt/J5OMPW"></script>
  <title>testing</title>
</head>

<body>
  <div id="main"></div>
</body>

</html>



How to get a specific number of random elements from a collection in Smalltalk?

How can I elegantly get a specific number (>1) of distinct, random elements from a collection?




#VALUE Error for the function random number and normal random number

Based on the Rand Excel formula I tried to generate one normal number in the following 12 cells.

I used following same formula in 12 different cells =NORM.INV(RAND(),0,1) Is this correct ? if yes what is different between normal number and random number if there is ant ?

Now I have implemented new method to generate normal random number. This method is based on the following 3 steps algorithm :

1 - Generate two uniform numbers on the [-1,1] interval that you will call U1 and U2.

2 - calculate S = U1 ^2 + U2^2

3 - If S < 1 the normal number is given by U1 * square root (-2 ln (S)/S) otherwise go back to step 1 until S < 1.

Function BoxMuller(U1 As Double, U2 As Double) As Double
Dim S As Double

Do
    U1 = WorksheetFunction.NormInv(U1, 0, 1)
    U2 = WorksheetFunction.NormInv(U2, 0, 1)
    S = U1 * U1 + U2 * U2

    If S < 1 Then
        BoxMuller = U1 * Sqr(-2 * Log(S) / S)
        Exit Function
    End If

Loop Until S < 1
End Function

But the above function sometimes return #VALUE Error When I use following formula =BoxMuller(RAND(),RAND()) . Where am I wrong ?




Calling a function in a project C++

I am tasked with a project of calling a function from another file instead of coding everything in the same script. I must generate 2 random integers from my main script then pass it to my side function compute it and display the result out on my main script.

Suppose value p = 5, q = 3, the side function will compute the sum: 33333 + 3333 + 333 + 33 + 3 = sum

Suppose value p = 3, q = 6, the side function will compute the sum: 666 + 66 + 6 = sum

I am required to generate 20 sets of such values randomly using c++11 random engine. I am able to get the gist of how the codes are suppose to be like but i am constantly confused about how to pass the function value, retain the function value and compute the final value.

Below is my error

    ||=== Build: Debug in lab5task1 (compiler: GNU GCC Compiler) ===|
    C:\Users\lteo007\Documents\lab5task1\lab5task1.cpp||In function 'int main()':|
    C:\Users\lteo007\Documents\lab5task1\lab5task1.cpp|29|error: expected primary-expression before 'int'|
    C:\Users\lteo007\Documents\lab5task1\lab5task1.cpp|29|error: expected primary-expression before 'int'|
    ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Below are my codes:

main code

#include <iostream>
#include <random>
#include <ctime>

using namespace std;

int generate_integer(int, int );
int add_integers(int, int );



int main()
{
    mt19937 rand_generator;

    rand_generator.seed(time(0)); //random seeding using current time

    uniform_int_distribution<int> rand_distribution(1,9);



    for(int i=0; i<20; i++)
    {
        int rand_num1, rand_num2;
        rand_num1 = rand_distribution(rand_generator);
        rand_num2 = rand_distribution(rand_generator);
        cout << "1st parameter" << rand_num1 << "        "  ;
        cout << "2nd parameter" << rand_num2 << "        "  ;
        cout << "sum" << add_integers(rand_num1,rand_num2)<< endl;
    }
    return 0;
}

and here is the side function

#include <iostream>
using namespace std;

int generate_integer(int m, int n);

int add_integer()
{
    int sum = 0;
    int p,q;

    for(int i = p; i > 0; i--)
        {
            sum = generate_integer(i,q) + sum;
            cout << sum << endl;
        }
    return sum;

}

int generate_integer(int m, int n)
{
    for(int i = 0; i < m; i++)
        {
            cout << n;
        }
}




jeudi 25 février 2016

What is wrong with my binary search technique?

I'm in my first Java class in college, and have attempted to do my first assignment involving using the binary search technique. I've created an array to generate 10 random numbers between 1-100, sorted them with a standard for loop (supposed to use the "enhanced for loop"). The last thing to complete successfully besides making my for loop enhanced is to "enter one value, search array using binary search technique to determine if value is present or not and output that. Maybe you guys can help me what I'm doing wrong as I'm getting some errors? Thanks!

import java.util.*;

class lab4point2 //lab4.2 part 1
{
public static void main(String args[])
{

int[] array = new int[10]; //array of 10 numbers created.

Random rand = new Random(); //random class created called rand.

for (int cnt = 0; cnt < array.length; cnt++) //for loop to generate
{array[cnt] = rand.nextInt(100) + 1;}     // the 10 numbers randomly 1-100

Arrays.sort(array); //sorted

System.out.println(Arrays.toString(array));// prints the 10 numbers to screen

System.out.print("Enter a value to see if it is present. ");

Scanner scanner = new Scanner(System.in);
int value = scanner.nextint();

boolean binarySearch(array, 0, 99, value);
{    int size = 100;
     int low = 0;
     int high = size - 1;

    while(high >= low) {
        int middle = (low + high) / 2;
         if(data[middle] == value) {
             System.out.print("Value is present ");
             return true;
         }
         if(data[middle] < value) {
             low = middle + 1;
         }
         if(data[middle] > value) {
             high = middle - 1;
         }
    }
    System.out.print("Value is not present. ");
    return false;
}


}


}




Why does each child process generate the same "random" number when using rand() in c?

I am trying to spawn n child processes, then let each child process request a random number of resources. However, each child currently requests an identical number of resources, though that number changes each time I run the program.

/* Create the appropriate number of processes */
int pid;
for(int i = 0; i < numberOfProcesses; i++){
    pid = fork();
    if(pid < 0){
        fprintf(stderr, "Fork Failed");
        exit(1);
    }
    else if(pid == 0){
        time_t t;
        srand((unsigned) time(&t));

        printf("Child (%d): %d.", i+1, getpid());

        /* Generate a random number [0, MAX_RESOURCES] of resources to request */

        int requestNum = rand() % (MAX_RESOURCES + 1);
        printf(" Requesting %d resources\n", requestNum);

        exit(0);
    }
    else{ wait(NULL); }
}




Swift random number matching game

I created own number button 0~9 and enter button and Randomnumber shows, it should change in 2.0 I got this. but my problem is, I need to input number that should be same as random number just showed up.

 @IBAction func btnNum(sender: AnyObject) {

I input all number button in here

}

 @IBAction func btnEnter(sender: AnyObject) {

This is func for enter button

}

And I need to make if I input something that should same with random number that shown on the top.

I create if my input and random is not equal, it is over. however, if I didn't put input but random number still changing.

  1. Random number should change in 2 sec

  2. I need to input number in 2 sec and compare those two

  3. If not equal it is wrong

  4. Also, if I didn't input anything in 2 sec it is still wrong

Every single number should end with press enter




C# Generate random string new instance returning same random string [duplicate]

This question already has an answer here:

I have a function to create a random string :

    public string RndStrings(int Groot)
    {
        Random randa = new Random();

        //The string that will contain all letters that are allowed to be generated.
        string totally = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM_";
        //Make a string that will be returned;
        string Ro = "";
        //Add a random character from the string "Allowed" to the string "R".
        for (int i = 0; i < Groot; i++) Ro += totally[randa.Next(0, totally.Length)];
        //Return the random string.
        return Ro;
    }

When used like this without using a Thread.Sleep in between the results returned are the SAME.

        var random_pwd = new ClientTools();
        string random_string_pwd = random_pwd.RndStrings(15);
        var random_salt = new ClientTools();
        string random_string_salt = random_salt.RndStrings(15);

With a Thread.Sleep in between, they are different as I want. How is this possible because I create two new instances of ClientTools which contains the RndStrings function.

Thanks.




Can you edit padding parameters for RSACryptoServiceProvider?

I'm writing an RSA encryption code on vb.net using the RSACryptoServiceProvider class. You get the option to use pkcs v1.5 or OAEP padding but i can't understand if it's parameters can be shown or are accessible to edit. I've seen the RSAOAEPKeyExchangeFormatter Class and RSAPKCS1KeyExchangeFormatter classes but i don't know how to use them. Is it possible to edit the parameter for the padded bytes and import padding bytes from your own random byte generator? Is there a sample code which does that, that i could view and understand the procedure? In general can the padding parameters on RSACryptoServiceProvider class be changed?




Java: Require library to generate histological cut

I like to generate images like the following:

image001 image002 image003

The generated images dont have to be as good as the images above. Important is the background (something like in the first image is ok) and the cell nucleus (the dark points).

Unfortunately i did not find a library which has good support to generate such things. Maybe someone knows a java library which could help to generate such images?

Thank you very much

Best regards

Kevin




Guessing Game in C++ random() with do while loop...not running or comparing high or low

Code not running and does not show high or low. Guessing game including random() starting with do while loop. It continues to ask user to guess infinitely.

int main()
{ 
//Variables
int _guess, tries, number;
char reply;

do
{
    //Constants
    int const MIN_NUMBER = 1, MAX_NUMBER = 100;

    //Get the system time.
    unsigned number = time(0);

    //Seed the random number generator.
    srand(number);

    number = (rand() % (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER;




Don't know how to generating random dots inside my shapes

Inside turtle graphics, I drew a rectangle and a circle side by side. How can I put 10 random dots in each of my shapes? Here is a picture of what it needs to look like:enter image description here

Here are some of the rules I need to fulfill to complete this: enter image description here

Here is the code and algorithm that was given to be used as a template:

-This is for 10 random dots in the rectangle:

import random
x = random.randint(-100, 100)
y = random.randint(-50, 50)

Repeat 10 times:
   x = random x value inside the square
   y = random y value inside the square
   Call drawPoint from UsefulTurtleFunctions
End Repeat

-This is for 10 random dots in the circle:

import random
x = random.randint(-20, 30)
y = random.randint(50, 100)

count_dots_in_circle = 0
While count_dots_in_circle < 10 Do
   x = random x value inside the square enclosing the circle
   y = random y value inside the square enclosing the circle
   If (x,y) is inside the circle Then
      Add one to count_dots_in_circle
      Call drawPoint from UsefulTurtleFunctions to show (x,y) point
   End If

Also this will calculate distance in some way:

def distanceBetween(x1, y1, x2, y2):
   d = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
   return d

Finally, here is the code I have:

import turtle
import math
import randint 

# draw a rectangle at a specific location
def drawRectangle(x = -75, y = 0, width = 100, height = 100): 
    turtle.penup() # Pull the pen up
    turtle.goto(x + width / 2, y + height / 2)
    turtle.pendown() # Pull the pen down
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)    


# Draw a circle at a specific location
def drawCircle(x = 50, y = 0, radius = 50): 
    turtle.penup() # Pull the pen up
    turtle.goto(x, -50)
    turtle.pendown() # Pull the pen down
    turtle.begin_fill() # Begin to fill color in a shape
    turtle.circle(radius) 




How do I find out whether a point is between two lines

I have a random distribution of points and I would like to find out which of those points are in between the two lines (note lines are parallel), any help would be greatly appreciated.

enter image description here




PYTHON randomize questions from a list and enumerate

I'd like to make

you.questions=['Finish this poem "Roses are red Violets are ..."','What is your favorite food?','Stones or Beatles?','favorite pet?','favorite color?','favorite food?']
for q in xrange(3)
    question = ''
    while question not in questions:

(this is where I'm stuck)

into

  1. What is your favorite food?
  2. favorite pet?
  3. Stones or Beatles?

the end result will be 7 questions from a pool of 25. Thanks in advance.




Java Math.random won't refresh on while loop (of course)

So, I am trying to make a text based RPG. A good starter project, as I am new to all of this. I want to make a critical hit, and math.random seems like the best way to go. Only one problem; when it loops, it doesn't refresh the random. I can assume that that's because it calls it once, and once it's called in, that's it. That's it's value. I want to know of an alternative so it refreshes every time the while loop starts over. I know there are some other bugs in my code; but that's not what I'm focusing on right now. Here's the entire method:`enter code here: public void battleStart(Enemy enemy, Player player){

    while(enemy.health != 0){
    String battle = null;



    int criticalHt = (int)(Math.random() * 10) + 0;

    boolean T = true;
    while(T = true){

    battle = Game.console.next();

    enemy.attackplayer(player);

    if(battle.toLowerCase().contains("skip")){

        System.out.println(criticalHt);

        if(criticalHt == 1){

        player.hitPoints -= enemy.dmg*2;

        System.out.println(Game.toTitleCase(enemy.firstName) + " " + Game.toTitleCase(enemy.lastName) + " has used " + Game.toTitleCase(enemy.attackName) + " for a critical level of " + enemy.dmg*2 + "!.\n Your health is now " + player.hitPoints + ".");

        }

        else{

        player.hitPoints -= enemy.dmg;

        System.out.println(Game.toTitleCase(enemy.firstName) + " " + Game.toTitleCase(enemy.lastName) + " has used " + Game.toTitleCase(enemy.attackName) + ".\n Your health is now " + player.hitPoints + ".");


        System.out.println("Your turn to attack! Use an attack, or type \"skip\" to let your enemy strike.");
        };
                if(battle.contains("skp")){


                };




                }
        /* End while */ }
        }




Generate random number and place it inside image URL

I want to generate a random number and place it inside an image URL. I found this JS code on the web but it doesn't work:

<script type="text/javascript" language="JavaScript">
number=Math.random()*10000000000000000;
</script>

<img src="http://ift.tt/1QHEvkx"/>

Can someone see whats wrong with the code? Thanks in advance.




How can you randomly import a file into pygame?

I'm making a quiz in pygame and would like the program to choose randomly from 2/3 ready made questions for the next one. All questions are on different files, so i am currently just importing the one i want next when a button is pressed.




how to start random activate on button press?

I know this question has already been answered but i can't get it to work.

I want to open a random activity on a button press in android studio.

I am new to programming so i will appreciate if you could be specific as possible because some stuff that are obvious to you are not obvious to me.

thanks




How can I place objects randomly in a cell for a 2D array based game? Java

Here I'm asked to do a method for the game which randomly places monsters in a map.. Im not really sure to start and how can I place an object (ex.Boss) in cell (0,0) using nested for loops for the 2D array Or randomly place the weak foes. How to translate this idea into a code?

public void generateMap(ArrayList weakFoes, ArrayList strongFoes): //It should generate the whole map grid randomly. It should be filled with:

• 1 Boss: A random boss should be positioned in the top left of the map i.e. cell (0,0).

• 15 Weak Foes: The weak foes should be randomly positioned on the map. The weak foes should be chosen randomly from the input weakFoes.

Any help is appreciated.. Thank youu




Stata - Random Effects Model

In Stata, I have run a random effects regressions. What are the next steps? I have checked that the random effects model is appropriate. Should I test for serial correlation? Is there anything else that I should test for?

If so what codes do I use to run these tests?




How to generate random numbers using only specific digits, e.g [1234] [4213] [3124]

In VB.NET I am trying to figure out how exactly to generate numbers of a fixed length using specific digits.

I have seen these questions but they do not cover what I am looking for:
Generating random integers in a specific range
Produce a random number in a range using C#
How to generate random number with the specific length in python
Generating an array of random strings
Generation 9 digits random number including leading zero

I am trying to generate 4 digit numbers using only 1, 2, 3, and 4.
It would be like this:

1234  
2134  
3124  
2143  
2431  
2413  

etc...
Can someone explain to me how this can be achieved?




Update multiple labels with values from a dictionary?

I'm trying to make an app that will select an index at random, something like 0-1000 and then print the key, value, and link of the selected number to three seperate labels on the iPhone simulator.

So from my example, I want to randomly select "0" or "1" and if for instance "1" was chosen; then the key, value, and link information would each be printed to three separate labels on the simulator. The following is what I've been working on in playgrounds. Is there a better way to go about this?

var spDictionary: [String: [String:String]] = [

    "0": ["key": "AMZN", "value": "AMAZON", "link": "yahoo"],
    "1": ["key": "AAPL", "value": "APPLE", "link": "yahoo2"],

]

And for the random aspect I think it would be something like this but I'm not sure? Sorry for the newbie question.

let randomIndex: Int = Int(arc4random_uniform(UInt32(spDictionary.count)))`




Performance issue with random double generation using Mersenne twister

I have the following code:

//#include all necessary things
class RandomGenerator {
public:
   double GetRandomDbl() {
     random_device rd;
     mt19937 eng(rd());
     std::uniform_real_distribution<double> dDistribution(0,1);
     return dDistribution(eng);
     }
 };

And then I have:

int _tmain(int argc, _TCHAR* argv[])
{
RandomGenerator Rand;    //on the heap for now

for (int i = 0; i < 1000000; i++) {
double pF = Rand.GetRandomDbl();
}
}

This code alone, takes an astounding 25-28 seconds to execute on 4GB RAM. I recall reading something about instantiating a new object every time I use the Mersenne twister, but if that's the issue how should I improve this? Surely this can be made faster.




Is z3 model the same for a same program?

I would like to know if, for two exact same problems (same variables names, same assertions, same statements order, etc.), z3 will always return the same model, or if will change from time to time. If the z3 model can change under these constraints, is there any workaround yet so I can always get the same result ?

I've already read this but was looking for more actual answers : Z3 randomness of generated model values Z3 timing variation

Thanks in advance !




Bash select random string from list

I have a list of strings that I want to select one of them at random each time I launch the script.

For example

SDF_BCH_CB="file1.sdf"
SDF_BCH_CW="file2.sdf"
SDF_BCH_RCB="file3.sdf"
SDF_BCH_RCW="file4.sdf"
SDF_TT="file5.sdf"

Then I want to be randomly select from the above list to assign the following two variables.

SDFFILE_MIN=$SDF_BCH_CW
SDFFILE_MAX=$SDF_TT

How can I do this ?

Thanks




The size of an array created from np.random.normal

I am using the numpy's random.normal routine to create a Gaussian with a given mean and standard deviation.

array_a = an array of len(100)

gaussian = np.random.normal(loc=array_a,scale=0.1,size=len(2*array_a))

So I expect the gaussian to have a mean=array_a and stddev=0.1 and the size of the gaussian array to be 2 times array_a. However the above returns me an array with the same size as that of array_a !

How do I get the len(gaussian) to be 2 times len(array_a) with the given mean and standard deviation?




mercredi 24 février 2016

Generate random numbers without using the last n values in Python

I have a Python function that generates a random number between 0 and 100:

def get_next_number():
    value = randint(0,100)

Every time I call this function, I need it to return a random number but that number cannot be one of the last n random numbers it returned (lets say 5 for this example).

Here are some examples:

55, 1, 67, 12, 88, 91, 100, 54 (This is fine as there are no duplicates in the last 5 numbers returned)

77, 42, 2, 3, 88, 2... (When the function gets a random number of 2, I need it to try again since 2 was already returned 3 numbers prior)

89, 23, 29, 81, 99, 100, 6, 8, 23... (This one is fine because 23 occurred more than 5 times before)

Is there something built into the random function to accomplish this?




Javascript - How do I make a button generate a random integer from 1-12, and have the button constantly produce that same number

So using Javascript, I am trying to make a button generate a random number from 1-12, and have that button generate that same number until I refresh the page. For example, if I click a button and it randomly generates 7, I want that button to continually produce a value of 7. When I reload the page and click the button, I want it to generate another random number from 1-12, and hold that value.

All I got is:

$("#buttonGreen").click(function() {
  $("#scoreNum").html((Math.floor(Math.random() * 12) + 1));
});

but this will generate a different random number between 1-12 every time I click it.




Issue filling up and outputting a 3D array

I am trying to create a 3-Dimensional array which gets filled up with pseudo-random numbers ranging from 0 to 9 (inclusive). This is my first time working with arrays containing more than 2 dimensions, so I am a bit lost.

At first the only number being inputted into the array was a 1, but after changing some code around, every number but the last one is a 1, and the last digit is pseudo-random. To make matters worse with the new situation I am in, when I hit enter, I get a weird error message.weird error message

Besides these two errors (error filling up array, and debug error), I also cannot figure out how in the world to print it out in 3 groups of 3 x 3 numbers, although right now, that is a lower issue on my agenda (although hints for that would be appreciated).

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

using namespace std;

int main(){

    srand(time(NULL));


    const int arrayRow = 3, arrayColumns = 3, arrayDepth = 3;

    int fun[arrayRow][arrayColumns][arrayDepth];

    for (int r = 0; r < 4; r++){
        for (int c = 0; c < 4; c++){
            for (int d = 0; d < 4; d++){
                int value = rand() % 10;
                fun[r][c][d] = value;
                cout << fun[arrayRow][arrayColumns][arrayDepth];
            }
        }
    }
    cout << "Complete." << endl;
    system("pause");
}




Generate random human understandable ID for users in rails

I want to generate a unique (human recognisable) id for each user that changes when they comment on different posts in my app. (so doesn't need to be stored in db as is constantly changing). The ID only needs to be used within the scope of a thread.

What I mean by this is identical to what YikYak does. In YikYak, anonymity is essential, so in each thread, users are assigned a randomly generated avatar which is the only way they and other people recognise which posts are posted from the same user.

I'm building an app where I too need anonymity, but I need users to be able to recognise when other people are commenting more than once.

What is the best thing to generate? A string of 2 random words like "Brocolli umbrella"? Or is there a way to randomly generate a simple avatar?

Any advice much appreciated




Randomizing (shuffling) JSON Object in JavaScript

I initially used the information from prior questions to figure out how to randomize data using information I found in a Stack Overflow Q&A. (How to randomize (shuffle) a JavaScript array?) In my original attempt, I did separate randomizations for girls' names and boys' names.

npcGirls = ["Amanda", "Deja", "Grace", "Hailey","Jada", "Kylie", "Maria", "Shanice", "Victoria"];
shuffle(npcGirls);

npcBoys = ["Aiden", "Benjamin", "Daniel", "Isaiah", "Jamal", "Maurice", "Steven", "Tyrone", "Zach"];
shuffle(npcGirls);

Randomization was completeed using the Fisher-Yates algorithm submitted by gnarf.

function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}

As I've thought about it and read more, I realize that I really need to use a JSON instead of a simple array. JSON is new to me. I've figured out how to set it up:

var npc = [
{"npcName":"Amanda", "npcSex":"girl", "npcRisk":"1"},
{"npcName":"Deja", "npcSex":"girl", "npcRisk":"2"},
{"npcName":"Grace", "npcSex":"girl", "npcRisk":"3"},
{"npcName":"Hailey", "npcSex":"girl", "npcRisk":"4"},
{"npcName":"Jada", "npcSex":"girl", "npcRisk":"5"},
{"npcName":"Kylie", "npcSex":"girl", "npcRisk":"6"},
{"npcName":"Maria", "npcSex":"girl", "npcRisk":"7"},
{"npcName":"Shanice", "npcSex":"girl", "npcRisk":"8"},
{"npcName":"Victoria", "npcSex":"girl", "npcRisk":"9"},
{"npcName":"Aiden", "npcSex":"boy", "npcRisk":"1"},
{"npcName":"Benjamin", "npcSex":"boy", "npcRisk":"2"},
{"npcName":"Daniel", "npcSex":"boy", "npcRisk":"3"},
{"npcName":"Isaiah", "npcSex":"boy", "npcRisk":"4"},
{"npcName":"Jamal", "npcSex":"boy", "npcRisk":"5"},
{"npcName":"Maurice", "npcSex":"boy", "npcRisk":"6"},
{"npcName":"Steven", "npcSex":"boy", "npcRisk":"7"},
{"npcName":"Tyrone", "npcSex":"boy", "npcRisk":"8"},
{"npcName":"Zach", "npcSex":"boy", "npcRisk":"9"}];

I haven't figured out how to call the function correctly or how to do separate randomizations for girls and boys. So, for example, the end of the randomization should replace girls' names with other girls' names but keep npcRisk in the same order. Guidance would be appreciated.




(C#) How to fill a 2D array with 2 different numbers evenly, but randomly?

For a randomized tic-tac-toe game simulator, I need to utilize a 2D array to simulate a round between 2 players. To fill the array, I've been using a simple randomizer to generate a random number between 0 and 1.

    //create 2D array
  const int ROWS = 3;
  const int COLS = 3;
  int[,] tictactoeArray = new int[ROWS, COLS];
   //create random variable
  Random rand = new Random();

   //method to fill array with random values between 0 and 1.
  private void RandomizeArray(ref int[,] iArray)
  {
      for (int row = 0; row < ROWS; row++)
      {
          for (int col = 0; col < COLS; col++)
          {
              tictactoeArray[row, col] = rand.Next(2);
          }
      }
  }

But when I use a random number generator like this, I occasionally end up with an impossible combination of values in relation to tic-tac-toe. As in the value 1 will occur 6 or more times, and make the game unfair for the other "player". I've done extensive searching, but haven't found a way to (more or less) evenly distribute the 2 values. Any suggestions?




Code to generate A-Z generates H, 72,

I am using the following code:

srand(time(NULL));
int r = rand() % 25 + 65;
char c = (char) r;
fprintf(stdout, "%c", c);
char d = (char) r;
fprintf(stdout, "%d", d);
char e = (char) r;
fprintf(stdout, "%e", e);
NSLog(@"%c");
NSLog(@"%d");
NSLog(@"%e");
_firstRandomLetter.text = [NSString stringWithFormat:@"%c", c];
_secondRandomLetter.text = [NSString stringWithFormat:@"%d", d];
_thirdRandomLetter.text = [NSString stringWithFormat:@"%e", e];

...to try and generate 3 letters from A to Z and display them. However, I get bizarre things such as 72 and ... as results. Everything displays fine.




Implicit declaration of functions srand, rand and system

Trying to solve an exercise where I have to print a random temperature value between 35°C & -10°C every 5 seconds followed by the date and time. Everything looks to be working as intended, however when I enter the code in a test script I get following errors.

implicit declaration of functions errors This is my code:

#include<stdio.h>
#include<unistd.h>
#include<time.h>
#define temp_max 35
#define temp_min -10
#define FREQUENCY 5

int main(void)
{
srand(time(NULL));
while(1)
{
int number = rand() % (temp_max*100 - temp_min*100) + temp_min*100;
double temperature = (double) number;
temperature /= 100;
printf("Temperature=%1.2f @ ",temperature);
fflush(stdout); 
system("date");
sleep(FREQUENCY);
}
return 0;
}

These are my results:

These are my results

This is what the test script checks for:

This is what the test script checks for

As I am unable to see my own mistakes, any help would be greatly appreciated.




Using take(n) more than once on Random sequence

I would like to take groups of strings from a Randomized sequence. I found that Randoms.takeFromValues provides a sequence that is most suitable for this. But it does not quiet work as expected. I am sure there is something I am not doing right. Here is a test code, It fails at second assertion as the size of list2 is 2 instead of 3.

@Test
public void totallylazy_random_sequence_test() {
    List<String> strings = list("string-1","string-2","string-3","string-4","string-5","string-6");
    Sequence<String> selector = Randoms.takeFromValues(strings);
    List<String> list1 = selector.take(3).toList();
    List<String> list2 = selector.take(3).toList();
    assertThat(list1.size(), is(3));
    assertThat(list2.size(), is(3));
}




Random select array with remove items (jQuery)

I'm trying to find a way to get values from an array of random way without repeating them, I found the following solution:

var letters = ["A", "B", "C"];
var getRandom = (function(array) {
  var notGivenItems = array.map(function(el) {
    return el;
  });
  var getIndex = function() {
    return Math.floor(Math.random() * notGivenItems.length);
  };

  return function() {
    if (notGivenItems.length === 0) {
      return;
    }

    return notGivenItems.splice(getIndex(), 1)[0];
  };
})(letters);

console.log(getRandom());
console.log(getRandom());
console.log(getRandom());
console.log(getRandom());

If I print the console.log() 4 times, at last, the array appears as undefined, and that's precisely what I need. However, I need (function () {... don't be fired automatically, because the value that comes via AJAX. So, should be something like:

var letters = ["A", "B", "C"];

function selec() {

  var getRandom = (function(array) {
    var notGivenItems = array.map(function(el) {
      return el;
    });
    var getIndex = function() {
      return Math.floor(Math.random() * notGivenItems.length);
    };

    return function() {
      if (notGivenItems.length === 0) {
        return;
      }

      return notGivenItems.splice(getIndex(), 1)[0];
    };
  })(letters);

  return getRandom();
}

console.log(selec());

But then, the function continues printing values continuously, without return undefined. Can one please help me out?




How do I generate random dots inside my turtle circle and rectangle?

Inside turtle graphics, I drew a rectangle and a circle. How can I put 10 random dots in each of my shapes? This is the code I have:

import turtle
import math
import random 

# draw a rectangle at a specific location
def drawRectangle(x = -75, y = 0, width = 100, height = 100): 
    turtle.penup() # Pull the pen up
    turtle.goto(x + width / 2, y + height / 2)
    turtle.pendown() # Pull the pen down
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)
    turtle.right(90)
    turtle.forward(height)
    turtle.right(90)
    turtle.forward(width)    


# Draw a circle at a specific location
def drawCircle(x = 50, y = 0, radius = 50): 
    turtle.penup() # Pull the pen up
    turtle.goto(x, -50)
    turtle.pendown() # Pull the pen down
    turtle.begin_fill() # Begin to fill color in a shape
    turtle.circle(radius) 




Random Number Resets

My random number generates on page load, but seems to reset when the user clicks the "Guess" button. I'm not sure what I'm doing wrong and just starting this program. If you answer, please also explain, as I'm trying to learn what I'm doing. Thank you!

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>PHP Homework 2</title>
        <link rel="stylesheet" href="styles/styles.css">
    </head>

    <body>
        <section id="main">
            <h1>Play the Guessing Game!</h1>
            <section id="left">
                <h2>Take a Guess!</h2>
                <form action="mine.php" method="post">
                    <div id="guessBox">
                        <label id="guessLB">Your Guess:</label>
                        <input id="guessTB" class="num" type="number" name="guessTB" max="1000" min="1">
                        </input>
                    </div>
                    <input type="submit" id="guessButton" name="guessBTN" value="Guess" />
                </form>
            </section>
            <section id="right">
                <h2>Game Stats</h2>
                <?php 

                    if(isset($_POST['guessTB'])) 
                    {
                        $randomNum = $_POST['guessTB'];
                    } 
                    else 
                    {
                        $randomNum = rand(1,100);
                    }                       

                    echo "<p>Random Number: $randomNum</p>";
                ?>      
            </section>
        </section>          
    </body>
</html>