mercredi 31 décembre 2014

arc4random on Xcode for C

I want to do a multiplications quiz using random numbers from 2 variables. I tried to use this:



int answ

int rand1= (arc4random()%10)+1;

int rand2= (arc4random()%20)+1;

printf("\n¿What is %d * %d?: ", rand1, rand2);

scanf("%d", &answ);

if (answ==rand1*rand2)
printf("\nCorrect answer!");
else
printf("\Incorrect answer, the result was %d", rand1*rand2);


My problem is that both random numbers does not change when the next question is asked. I also tried adding srand(time(NULL)) and the same.. (I already have the library stdlib.h added)


What´s missing?





Random falling object using timer

I am trying to build a game (circus of plates) , where I need to create random shapes falling and the player should catch them to increase the score . basically, I don't have a problem with randomly create objects, I just need them to fall.


I used objects pool design pattern to create a pool containing the created object, with a method borrowShape() to get one object form the pool.


In code bellow, I tried to use time schedule to sequentially falling object on after another.



public class view extends JFrame {
private static final long serialVersionUID = 1L;
public int x1 ;
public int y1 ;
public int x2 ;
public int y2 ;
public int Xframe ;
public int Yframe ;
// Keyboard c ;
private Image bfimage ;
private Graphics bfg ;
Image clown1 ;
Image clown2 ;
private Queue<Shapes> queue_1 = new LinkedList<Shapes>();
private Queue<Shapes> queue_2 = new LinkedList<Shapes>();
private Queue<Shapes> queue_3 = new LinkedList<Shapes>();
private Queue<Shapes> queue_4 = new LinkedList<Shapes>();
private LinkedList<Shapes> onScreen = new LinkedList<Shapes>();
Shapes shape_1 = new BlueMushroom();
Shapes shape_2 = new RedMushroom();
Shapes shape_3 = new GreenMushroom();
Shapes shape_4 = new RedMushroom();

ShapesPool pool;
FirstState frstate;
public view () throws InterruptedException{
ImageIcon i1 = new ImageIcon("clown111.gif");
clown1= i1.getImage() ;
ImageIcon i2 = new ImageIcon("clown22.gif");
clown2= i2.getImage() ;
// create pool
onScreen.add(new BlueMushroom());



Xframe= 1370 ;
Yframe = 700 ;
setTitle("game");
setSize(Xframe , Yframe);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
x1 = 0 ;
y1 = Yframe - 240 ;
x2 = 650 ;
y2 = Yframe - 240 ;
controller k = new controller(this , x1 , y1 , x2 , y2 , Xframe , Yframe) ;
this.addKeyListener(k);
Timer time = new Timer();
pool = ShapesPool.getInstance();
frstate = new FirstState();
Shapes shape = new BlueMushroom();
for(int i = 0 ; i < 5 ; i++){
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_1.add(shape);
}
for(int i = 0 ; i < 7 ; i++){
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_2.add(shape);
}
for(int i = 0 ; i < 9 ; i++){
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_3.add(shape);
}
for(int i = 0 ; i < 11 ; i++){
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_4.add(shape);
}

time.schedule(new RunShape(),2*1000, 2*1000);
time.wait();

}

int ypos1=0;
int ypos2=0;
int ypos3=0;
int ypos4=0;

Random rand = new Random();
public int randomX(){
return rand.nextInt(1700);
}

class RunShape extends TimerTask{
@Override
public void run(){
System.out.println("run");
Shapes shape = new BlueMushroom();
if(!queue_1.isEmpty()){
System.out.println("awl saaf ");

shape_1 = queue_1.poll();
addObject(shape_1);
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_1.add(shape);
}
if(!queue_2.isEmpty()){

shape_2 = queue_2.poll();
addObject(shape_2);
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_2.add(shape);
}
if(!queue_3.isEmpty()){

shape_3 = queue_3.poll();
addObject(shape_3);
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_3.add(shape);
}
if(!queue_4.isEmpty()){

shape_4 = queue_4.poll();
addObject(shape_4);
shape = pool.borrowShape();
shape.setCurrentX(randomX());
shape.setCurrentY(10);
shape.setState(frstate);
queue_4.add(shape);
}
Timer time = new Timer();
time.schedule(new TimerTask(){
public void run(){
while(ypos1 <= 1600){
ypos1++;
shape_1.setCurrentY(ypos1);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ypos2++;
shape_2.setCurrentY(ypos2);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ypos3++;
shape_3.setCurrentY(ypos3);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ypos4++;
shape_4.setCurrentY(ypos4);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
if(ypos1 == 1600 ){ ypos1 = 0;
shape_1.setCurrentY(ypos1);
}
if(ypos2 == 1600 ){ ypos2 = 0;
shape_2.setCurrentY(ypos2);
}
if(ypos3 == 1600 ){ ypos3 = 0;
shape_3.setCurrentY(ypos3);
}
if(ypos4 == 1600 ){ ypos4 = 0;
shape_4.setCurrentY(ypos4);
}

}
},1*1000 ,1*1000);
try {
time.wait(1*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


public void addObject(Shapes shape){
onScreen.add(shape);
repaint();
}
public void paint(Graphics g) {
bfimage = createImage(getWidth(), getHeight()) ;
bfg = bfimage.getGraphics() ;
paintcomponent(bfg) ;
g.drawImage(bfimage, 0, 0, this) ;

}

public void paintcomponent(Graphics g){
g.drawImage(clown1, x1, y1, this) ;
g.drawImage(clown2, x2, y2, this) ;
g.drawImage(shape_1.getMushroom(), shape_1.getCurrentX(), shape_1.getCurrentY(), this);
g.drawImage(shape_2.getMushroom(), shape_2.getCurrentX(), shape_2.getCurrentY(), this);
g.drawImage(shape_3.getMushroom(), shape_3.getCurrentX(), shape_3.getCurrentY(), this);
g.drawImage(shape_4.getMushroom(), shape_4.getCurrentX(), shape_4.getCurrentY(), this);
for(Shapes shape : onScreen){
g.drawImage(shape.getMushroom(), shape.getCurrentX(), shape.getCurrentY(), this);
}

repaint() ;
}

}




Random numbers without duplicates

Simulating a lottery of 6 numbers chosen from 40, I want to create a list of numbers in Haskell using the system random generator but eliminate duplicates, which often arise.


If I have the following:



import System.Random

main :: IO ()
main = do
rs <- forM [1..6] $ \_x -> randomRIO (1, 40) :: (IO Int)
print rs


this is halfway. But how do I filter out duplicates? It seems to me I need a while loop of some sort to construct a list filtering elements that are already in the list until the list is the required size. If I can generate an infinite list of random numbers and filter it inside the IO monad I am sure that would work, but I do not know how to approach this. It seems while loops are generally deprecated in Haskell, so I am uncertain of the true Haskeller's way here. Is this a legitimate use case for a while loop, and if so, how does one do that?





How can I generate random numbers based on a pattern from a given list of numbers?

I'm trying to generate x random numbers based on lists I will provide (containing the same amount of numbers I want generated). So Far I have this code:



import random
list = []

while len(list) < 10:
x = random.randint(1, 100)
if x not in list:
list.append(x)

list.sort()
print (list)


The question is, how do I input the lists I have so Python can read some pattern (in lack of a better word) and generate numbers? Tried Google it, found nothing so far. Thanks.





how to generate ten random number [on hold]

this is my imageview list



public ImageView[] IMGS = { iv1, iv2, iv3, iv4, iv5, iv6,iv7,iv8,iv9,iv10,iv11,iv12,iv13,iv14,iv15,iv16,iv17,iv18,iv19,iv20 };

iv1 = (ImageView) findViewById(R.id.imageView1);
iv2 = (ImageView) findViewById(R.id.imageView2);
iv3 = (ImageView) findViewById(R.id.imageView3);
iv4 = (ImageView) findViewById(R.id.imageView4);
iv5 = (ImageView) findViewById(R.id.imageView5);
iv6 = (ImageView) findViewById(R.id.imageView6);
iv7 = (ImageView) findViewById(R.id.imageView7);
iv8 = (ImageView) findViewById(R.id.imageView8);
iv9 = (ImageView) findViewById(R.id.imageView9);
iv10 = (ImageView) findViewById(R.id.imageView10);
iv11 = (ImageView) findViewById(R.id.imageView11);
iv12 = (ImageView) findViewById(R.id.imageView12);
iv13 = (ImageView) findViewById(R.id.imageView13);
iv14 = (ImageView) findViewById(R.id.imageView14);
iv15 = (ImageView) findViewById(R.id.imageView15);
iv16 = (ImageView) findViewById(R.id.imageView16);
iv17 = (ImageView) findViewById(R.id.imageView17);
iv18 = (ImageView) findViewById(R.id.imageView18);
iv19 = (ImageView) findViewById(R.id.imageView19);
iv20 = (ImageView) findViewById(R.id.imageView20);


I need to randomly generate ten different indexes with this piece of code. How do I set the visiblity? thanks in advance





NIST randomness tests in R

i've recently known about NIST 15 tests and random numbers. Since NIST packages tests are written in C,i just want to know if there are NIST 15 tests packages written in R?? or where can i convert C packages into R ??





mardi 30 décembre 2014

Random number not updating in SetInterval function

I've tried a few different approaches to this found on SO but just cant seem to get it to work.


I'm trying to update the randomly selected item in an array, in a setInterval function, but the random number is not changing.


It is randomly chosen on first load, but then it doesn't update after the fact, each time the function runs again.


This is all using the lazylinepainter plugin: https://github.com/camoconnell/lazy-line-painter



var pathArray = [pathOne,pathTwo,pathThree,pathFour,pathFive,pathSix],
colors = ['#e51616','#0000FF','#FFFF00','#00FF00'],
drawBox = $('#drawing-box'),
svg = $('#drawing-box svg'),
svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path");

function randomFrom(array) {
return array[Math.floor(Math.random() * array.length)];
}

randomColor = randomFrom(colors);

var i = Math.floor(Math.random() * (5 - 0 + 1));
console.log(i);

function Draw(){

var drawLoop = setTimeout(function (){
$('#drawing-box svg path').animate({'opacity':0},300);
setTimeout(function(){
$('#drawing-box svg path').remove();
drawBox.lazylinepainter('paint');
console.log(pathArray[i]);
},350);
},5500);

var drawFunc = drawBox.lazylinepainter({
"svgData": pathArray[i],
"strokeColor": randomColor,
"strokeWidth": 5,
"responsive": true,
"onComplete": drawLoop
});

drawFunc.lazylinepainter('paint')
};

setInterval(function(){
Draw();
},6000);


Here it is on jsFiddle —————


Rerun the fiddle over and over to see the different paths chosen at random (since its not updating otherwise).


Hopefully that snippet is clear, was still trying a few different things in there.


The ultimate goal is to have that line draw a randomly chosen item from the pathArray (pathOne, pathTwo, pathThree, etc. etc.) with each interval.





c++1y way to generate random floating point number

I need in random floating point numbers. I want to test implementations of an elementary functions in my JIT-compiler for a custom floating point type. So I do the following:



  • I testing the function (say, exp) for fixed points (say, zero -> one, one -> Euler constant, ln2 -> two)

  • Then I generate full-range floating-point numbers (adjacent to domain of the elementary function) and testing my function on them.


How to generate desired numbers? What I do at the moment is the following:



#include <iostream>
#include <iomanip>
#include <random>
#include <chrono>
#include <limits>

#include <cmath>
#include <cstdlib>

int
main()
{
using G = long double;
G const one = G(1);
std::mt19937_64 random_(static_cast< typename std::mt19937_64::result_type >(std::chrono::high_resolution_clock::now().time_since_epoch().count()));
std::uniform_real_distribution< G > zero_to_one_; // uniform [0;1) ditribution
std::uniform_int_distribution< int > uniform_int_(std::numeric_limits< G >::min_exponent - 1, std::numeric_limits< G >::max_exponent - 1);
std::cout.precision(std::numeric_limits< G >::digits10);
for (std::size_t i = 0; i < 100; ++i) {
std::cout << std::scalbn(one + zero_to_one_(random_), uniform_int_(random_)) << std::endl;
}
return EXIT_SUCCESS;
}




Avoid division by zero in C when taking log with respect to a random number

I am currently using C to generate a Gaussian noise. In one step, I need to take the log of a uniformly distributed number u1 = (double) rand() / RAND_MAX. Because u1 may be zero, there is a risk in doing log(u1). So, I need to check. Should I use



do {
u1 = ((double) rand() / RAND_MAX);
} while (u1 == 0.);


Or, should I use



do {
u1 = ((double) rand() / RAND_MAX);
} while (u1 < epsilon);


where epsilon is a small number? If the latter is preferred, how should I choose the value of epsilon? (In Fortran there is TINY, but I do not know what to do in C).


Thanks!


Attached is the complete code:



#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdlib.h>

double gaussian_noise(double mean, double std)
{
static int have_spare = 0;
static double u1, u2, z1, z2;
if(have_spare)
{
have_spare = 0;
z2 = sqrt(-2. * log(u1)) * sin(2. * M_PI * u2);
return mean + std * z2;
}
have_spare = 1;
do {
u1 = ((double) rand() / RAND_MAX);
} while (u1 == 0.);
u2 = ((double) rand() / RAND_MAX);
z1 = sqrt(-2. * log(u1)) * cos(2. * M_PI * u2);
return mean + std * z1;
}

void main()
{
const double mean = 0., std = 1.;
double noise;
int i;
for(i=0; i<100000; i++)
{
noise = gaussian_noise(mean, std);
printf("%lf\t", noise);
}
}




Random real in [0..1[ using Mersenne Twister

I'm trying to make a model of a zombie apocalipse in c++ using simple structs and a when I'm randomizing the population, I need some fields of the struct to have a value in the interval [0..1[. As I'm interested in a more statistically correct analysis, I choose to use the mt19937 engine to generate my "data". When playing around with this PRNG I couldn't find a way to generate a number in said range. Here's the code that I came up with:



int
main ( int argc, char** argv )
{

mt19937_64 newr ( time ( NULL ) );
std::cout << newr.max ( ) << endl;
std::cout << newr.min ( );
double rn;
for(;;){
rn = newr()/newr.max ();
std::cout << rn << std::endl;
}
}


But the only outputs that I get for the loop are zeros (0). A small print of the output is down:



18446744073709551615
0
0
0
0
0
0
0
0
0
0
0


Any ideas?





Generate random numbers with rand() except number zero

I would like to generate random numbers between 1 and 25 with the method rand()

But I only know how to generate random numbers this way, which includes the number zero by default:



int r = rand() % 26 /* random int between 0 and 25 */


Anyone? Thank you.





How to get rid of letters randomly generated after being used?

I'm currently writing a program that requires me to generate random letters from the alphabet and assign them to other letters. (It's an encryption program). The problem is, once I've generated the first few letters, some are generated again.


For example, I want to let a = c (randomly generated letter) But now that c is used, I don't want the other 25 letters to be equal to c. So I don't want b = c I don't know how to go about this as it seems easy enough but I can't manage to do it.


Here is that bit of my code.



for (int i = 0; i<26; i++)
{
Random r = new Random();
cipherArray[i] =(char)(cipherText.charAt(r.nextInt(cipherText.length())));
}
return cipherArray;


Any help is appreciated, thank you.





List all 4-digit integers in Java [on hold]

I need a program that stores all 4 digit numbers as Stings which has the following attributes:



  • 4 digits long

  • every number appears only once

  • there isn't 0 (only 1-9)


Actually I need something like this:



String[] s = {"1234","1235","1236,"1237","1238","1239","1245","1246",..,"9875","9876"}




how to compute pdf/cdf of a non-standard beta distribution (i.e., support not in [01]) in R?

I know the dbeta/pbeta command, but this is only for standard beta distributions where the upper limit of the support is 1 and the lower limit is 0. How to generalize these functions?


Thanks.





Change (0, 1] to (0, 1) without branching

I have a random number generator that outputs values from (0, 1], but I need to give the output to a function that returns infinity at 0 or 1. How can I post-process the generated number to be in (0, 1) without any branches, as this is intended to execute on a GPU?


I suppose one way is to add a tiny constant and then take the value mod 1. In other words, generate from (ɛ, 1 + ɛ], which gets turned into [ɛ, 1). Is there a better way? What should the ɛ be?





Generate random string for member of struct

I would like to know how I can generate a random string for a member of a struct and assign this value to the member of the struct.


My struct is defined this way:



struct student{
int key;
char name[25];
}


I already generated random numbers of the member "key" of struct.

Part of the code of the method:



struct student s;
int r = rand() % 5000;
s.key=r;


Note: With srand(time(NULL)); defined in main().


How I do it for s.name?





Generate random number for atribute in struct

I have a struct called drug, and i want to generate random numbers for the atributes minimal_quantity and quantity. But every time i run the code, i get the same numbers on these two atributes, for all drugs that are generated.


My struct is defined this way:



struct drug{
int code;
char name[25];
int minimal_quantity;
int quantity;};


And the method for generating drugs is this:



load_drugs_file(){
int i;

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

if ((fp=fopen("drugs.dat","a+"))==NULL){
printf("Error: impossible to open the file. \n");
exit(1);
}

struct drug m;
srand(time(NULL));
int r1 = rand() % 500; /* random int between 0 and 499 */
int r2 = rand() % 1000; /* random int between 0 and 999 */

m.code=i;
strcpy(m.name,"A");
m.minimal_quantity=r1;
m.quantity=r2;

fwrite(&m,sizeof(m),1,fp);

fclose(fp);
}}


Any suggestions?





Generate random numbers from 0 to 7 with every number appearing 2 times in java ADT

I need to generate random numbers from 0 to 7 with every number appearing 2 times. The end result should have every number appearing 2 times, in random order. An example would be: MyArray = [3, 6, 0, 5, 2, 2, 6, 7, 5, 4, 7, 1, 3, 1, 0, 4]. This is what I tried to do. The code works alone but not in an ADT environnement (in an adapter class that is visited 16 times, but only 14 when I use this code).



ArrayList<Integer> nombres = new ArrayList<Integer>();
private int getRandomNumber() {

Random rand = new Random();
int temp;

while(true){
temp = rand.nextInt(8);

if (nombres.size()==0) {
nombres.add(temp);
return temp;
}

if (nombres.contains(temp)){
if (nombres.indexOf(temp) == nombres.lastIndexOf(temp)){
nombres.add(temp);
return temp;
}
}

if (!nombres.contains(temp)){
nombres.add(temp);
return temp;
}



}

}


Any other, easier solutions? (I have tried to put everything in a single if, same result).





Should I use `rand % N` or `rand() / (RAND_MAX / N + 1)`?

I was reading the C FAQ and found out in a question that it recommends me to use rand() / (RAND_MAX / N + 1) instead of the more popular way which is rand() % N.


The reasoning for that is that when N is a low number rand() % N will only use a few bits from rand().


I tested the different approaches with N being 2 on both Windows and Linux but could not notice a difference.



#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 2

int main(void)
{
srand(0);
printf("rand() %% N:\n");
for (int i = 0; i < 40; ++i) {
printf("%d ", rand() % N);
}
putchar('\n');

srand(0);
printf("rand() / (RAND_MAX / N + 1):\n");
for (int i = 0; i < 40; ++i) {
printf("%d ", rand() / (RAND_MAX / N + 1));
}
putchar('\n');

return 0;
}


The output is this (on my gnu/linux machine):



rand() % N:
1 0 1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 0 1 0
rand() / (RAND_MAX / N + 1):
1 0 1 1 1 0 0 1 0 1 0 1 0 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 1 0 1 1 1 0 1 1 0 1 0 1


Both alternatives seem perfectly random to me. It even seems like the second approach is worse than rand % N.


Should I use rand() % N or rand() / (RAND_MAX / N + 1)?





Python code for random number generator not printing as expected

Sorry if this is a silly question I've researched it and found similar code that works and applied the same layout, but for some reason when I run mine it doesn't print num or the true or false result, just a blank line. I'm using Python 2, what am I missing? the rand_divis_3 function should just simply generate a random number and print True or False depending on whether it is divisible by 3. Help much appreciated, I'm new to python



import random
def rand_divis_3():
num = random.randint(0,100)
print num
if num % 3 == 0:
print True
else:
print False




Generate 3 bit random binary number every clock cycle on 80C51 microcontroller

Can some one please post the C code to program an 80C51 micro controller to generate a random three bit binary number at every lock cycle?


I am in second semester of electrical engineering and thus don't have much knowledge about microcontorllers. i tried using 3 flip flops at different frequencies to generate the number but there were timing problems.





Randomizing strings without duplication

I have string with 5 different sayings and I'm trying to make them random without any duplication and repeat the saying once they all have been picked.


so far i have


final String[] mySays = { " x ", " y ", " z" , " a ", " b",}


@Override public void onClick(View v) { //change number to however number there is of "saying" int aNumber = (int) (Math.random() * 5); textOne.setText(mySays[aNumber]);


what can i add to this?


any help is greatly appreciated.





Why the randomize() function not working?

I and my friend are trying to make a "Hangman" game using C++ for our school project. But on compilation, the messages show that the standard functions randomize() and random were not declared in this scope. What is wrong in the code?



#include <iostream>
#include <cstdlib>
#include <cstring>
#include<cstdio>
using namespace std;
const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;

int letterFill (char, char[], char[]);
void initUnknown (char[], char[]);

int main ()
{
char unknown [MAXLENGTH];
char letter;
int wrong_guesses=0;
char word[MAXLENGTH];
char words[][MAXLENGTH] =
{
"batman begins",
"superman returns",
"2012",
"tarzan",
"goal",
"300",
"space jam",
"transformers",
"megamind",
"spiderman"
};
randomize();
int n=random(10);
strcpy(word,words[n]);
initUnknown(word, unknown);

cout << "\n\nWelcome to hangman...Guess a Movie Name";
cout << "\n\nEach letter is represented by a star.";
cout << "\n\nYou have to type only one letter in one try";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

while (wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Whoops! That letter isn't in there!" << endl;
wrong_guesses++;
}
else
{
cout << endl << "You found a letter! Isn't that exciting!" << endl;
}

cout << "You have " << MAX_TRIES - wrong_guesses;
cout << " guesses left." << endl;
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "Yeah! You got it!";
break;
}

}
if(wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
cin.get();
return 0;
}
int letterFill (char guess, char secretword[], char guessword[])
{
int i;
int matches=0;
for (i = 0; secretword[i]!='\0'; i++)
{
if (guess == guessword[i])
return 0;
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void initUnknown (char word[], char unknown[])
{
int i;
int length = strlen(word);
for (i = 0; i < length; i++)
unknown[i]='*';
unknown[i]='\0';
}




lundi 29 décembre 2014

Weighted sampling without replacement in PHP

If D denote the population of all items and |D|=n the total quantity of items, I want to take a random sample S of m=|S| elements, being m <= n. Each item in D has a weight attached, that represents its probability of appears in S.


Mi question is: What is the best algorithm (more efficent / easy to implement) keeping in mind n / 1k < n < 10k and all items will be in memory?





Random in a Int[]

I want to the player receive a random item in the Int[]



public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {


Player player = (Player) sender;

if(commandLabel.equalsIgnoreCase("surprise")){
Random random = new Random();

PlayerInventory inventory = player.getInventory();
int ItensIds[] = {274, 313, 314, 315, 316};
ItemStack item = new ItemStack(Material.AIR);



for(int Ids : ItensIds){

int randomNumber = random.nextInt(300);
do{
randomNumber = random.nextInt(300);
item.setTypeId(Ids);
inventory.addItem(item);
} while(randomNumber == Ids);

break;
}

}


Im trying to figure how it works but ends crashing the server or not working at all.


Im really new at this code stuff, please understand if I did something really wrong.





how to get random ten values after generate random number


public ImageView[] IMGS = { iv1, iv3, iv3, iv4, iv5, iv6,iv7,iv8,iv9,iv10,iv11,iv12,iv13,iv14,iv15,iv16,iv17,iv18,iv19,iv20 };

for(int i=0;i<20;i++){
IMGS[i].setVisibility(View.GONE);


}



for(int i=1;i<=10;i++) {`


Random random = new Random(); rndIndex = random.nextInt(IMGS.length);



IMGS[rndIndex].setVisibility(View.VISIBLE);


}


how to ten random value in imageViews and get dialog after ten value show or click





How to make cards work in python

This is my code so far:



import sys
import os
import random
Question():
os.system('cls')
SQ=input('Do you want to play blackjack y/n')
if(SQ == y or SQ == Y):
StartGame()
if(SQ == n or SQ == N):
sys.exit()
if(SQ != n and SQ != N and SQ != y and SQ != Y):
print('You did answer the question with a y or a n which correspond to yes and no accordingly')
Question()
Question()

StartGame():
slot1=False
slot2=False
slot3=False
slot4=False
slot5=False
slot6=False
slot7=False
slot8=False
slot9=False
slot10=False
slot11=False
slot12=False
slot13=False
slot14=False
slot15=False
slot16=False
slot17=False
slot18=False
slot19=False
slot20=False
slot21=False
slot22=False
slot22=False
slot23=False
Slot24=False
slot25=False
slot26=False
slot27=False
Slot28=False
slot29=False
slot30=False
slot31=False
slot32=False
slot33=False
slot34=False
slot35=False
slot36=False
slot37=False
slot38=False
slot39=False
slot40=False
slot41=False
slot42=False
slot43=False
slot44=False
slot45=False
slot46=False
slot47=False
slot48=False
slot49=False
slot50=False
slot51=False
slot52=False

aceHEART = randrange(1, 52)
aceHEART


I don't understand the correct way to make the slots and a random number generator together to make a random shuffle. How can i make it so it does not try to put more than one card in one slot. I also do not know how to manage these cards in a more efficient way. I am making a blackjack game in python and i do not know the correct way to approach this. Please help me in the best way you can.





PHP semi-random word generator

The following code is working. But I'd like to improve it. Basically, this page displays a random str per each categories and reloads a page when a user pushes a button. Can it be different so I could manage the data easier(I want to update the words library frequently). I also wonder if this is short enough for quick loading. Thank you so much for your help in advance.



<!-- begin -->
<html>
<head>
</head>

<body>


<?php
#hash = random url generated from 128 chars


$words = array('apple', 'orange', 'banana');
$rword = rand(0,2);

$syms = array('chair', 'sofa', 'table', 'coffee table');
$rsym = rand(0,3);

$value1 = $words[$rword];
$final1 = strtoupper($value1);

$value2 = $syms[$rsym];
$final2 = strtoupper($value2);

?>


<h2>Fruit</h2><p><?php echo $final1 = strtolower($value1); ?></p>
<h2>Furniture</h2><p><?php echo $final2 = strtolower($value2); ?></p>


<FORM METHOD="LINK" ACTION="random.php">
<INPUT TYPE="submit" VALUE="generate again">
</FORM>



</body>
</html>

<!-- end -->




How to select random numbers from a given list in matlab / octave

How to select random numbers from a given list of data


I can create a list of 5 random numbers between 50 and 100 using the code below but how can I have it randomly select numbers from a dataset of values example dataset=[10;20;25;111;14];



amtofNumbers=5; %amount of numbers
a = 50;
b = 100;
r = (b-a).*rand(amtofNumbers,1) + a


I'm using octave 3.8.1 which works with matlab .





dimanche 28 décembre 2014

postgresql random() bug?

select random() * 999 + 111 from generate_series(1,10)



690,046183290426
983,732229881454
1091,53674799064
659,380498787854
398,545482470188
775,65887248842
1044,79942638567
173,288027528208
584,690435883589
522,077123570256


Two values are over 999!


This one works fine: select random() * 9 + 1 from generate_series(1,10)


PostgreSQL 9.3.5 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2, 64-bit


Is that a bug?


Thanks Joe





C why is their a probability of higher numbers using rand() [duplicate]


Weird question I guess. Its out of curiosity.


Using rand() function, if we set the parameters between 1-10, i then ran a test a few times on a my machines UNIX operating system, more specifically Ubuntu. My results always showed higher numbers (greater then 5) being more likely returned. It didn't seem at all as if it was random.


I also read up on the module which states that using the modules operation, we form some kind of bias.



Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).


Why is that? Also it said lower numbers become more likely, however i get more higher numbers





Random Generator Code?

I'm trying to get this code to produce an array comprised of unique random musical notes. It will, based on parameters given make a note and assign an accidental sign to it, with a possibility of either displaying as its flat of sharp counterpart. For example, If the random generator said the note "A" will be flat, there's a chance it will show up as either Ab or G#.


Now, I haven't handled the half-step notes (e.g. Cb is turned into B#, etc.), but that's mainly because the first part isn't working. The problem I have now is the code I'm using doesn't seem to work consistently. It will correctly translate the notes at some times and mess them up on others. There's no systematic pattern of error, either, at least, not from I've tried to decipher.


I'm using XNA for this to display the notes on the screen, but the real problem is with the data. I'm using a Note class I made.


Here's the code I'm using:


First the Note class:



public class Note
{
public enum Notes
{
A,
B,
C,
D,
E,
F,
G
}
public Notes noteLetter { get; private set; }
public Notes translatedLetter { get; private set; }
public bool isFlat { get; private set; }
public bool showSharp { get; private set; }

private const int NOTE_COUNT = 7;

/// <summary>
/// Creates a Note
/// </summary>
/// <param name="note">The basic note</param>
/// <param name="flat">Is the note flat?</param>
/// <param name="sharp">Will be shown as it's sharp counterpart?</param>
public Note(Notes note, bool flat, bool sharp)
{
noteLetter = note;
isFlat = flat;
showSharp = sharp;

if (isFlat && showSharp)
{
int hashCode = noteLetter.GetHashCode();
translatedLetter = (Notes)((hashCode + NOTE_COUNT - 1) % NOTE_COUNT);
}
else
{
translatedLetter = noteLetter;
showSharp = isFlat;
}

}
}


Then the Game1.cs file:



public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;

KeyboardState KeyBState, prevKeybState;

Texture2D sprite;

Rectangle noteSource;
Rectangle accSource;

const int ACCIDENTAL_START_X = 840;

const int BORDER_OFFSET = 12;

Vector2 notePosition;

SpriteFont font;

/// <summary>
/// The array of notes, row/column format
/// </summary>
Note[,] box;

const int ROW_SIZE = 3, COLUMN_SIZE = 4;

public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";

box = new Note[ROW_SIZE, COLUMN_SIZE];
noteSource = new Rectangle(0, 0, 120, 120);
accSource = new Rectangle(ACCIDENTAL_START_X, 0, 50, 50);

notePosition = Vector2.Zero;
}


protected override void Initialize()
{
// TODO: Add your initialization logic here
MakeTable();

base.Initialize();
}


protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
sprite = Content.Load<Texture2D>("Note Pieces2");
font = Content.Load<SpriteFont>("font");
// TODO: use this.Content to load your game content here
}


protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}


protected override void Update(GameTime gameTime)
{
// Allows the game to exit
KeyBState = Keyboard.GetState();

if (KeyBState.IsKeyDown(Keys.Escape))
this.Exit();

if (KeyBState.IsKeyDown(Keys.Space) && prevKeybState.IsKeyUp(Keys.Space))
MakeTable();

// TODO: Add your update logic here
prevKeybState = KeyBState;
base.Update(gameTime);
}


protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);

// TODO: Add your drawing code here
spriteBatch.Begin();
for (int r = 0; r < ROW_SIZE; r++)
{
for (int c = 0; c < COLUMN_SIZE; c++)
{
Note temp = box[r, c];
notePosition.Y = r * noteSource.Width + (r * BORDER_OFFSET);
notePosition.X = c * noteSource.Height + (c * BORDER_OFFSET);
noteSource.X = temp.translatedLetter.GetHashCode() * noteSource.Width;

spriteBatch.Draw(sprite, notePosition, noteSource, Color.White);

notePosition.X += noteSource.Width / 2;
notePosition.Y += 7;

spriteBatch.DrawString(font,
temp.noteLetter.ToString() +
(temp.isFlat ? "b " : " ") +
temp.translatedLetter +
(temp.showSharp ? "#" : ""), notePosition, Color.Black);

notePosition.X -= noteSource.Width / 2;
notePosition.Y -= 7;

if (temp.isFlat)
{
notePosition.X += 63;
notePosition.Y += 63;

accSource.X = ACCIDENTAL_START_X;
accSource.Y = 0;
if (temp.showSharp)
{
accSource.X += (temp.translatedLetter.GetHashCode() % 2) * (accSource.Width * 2);
accSource.Y += ((int)(temp.translatedLetter.GetHashCode() / 2)) * accSource.Height;
spriteBatch.Draw(sprite, notePosition, accSource, Color.White);
}
/*
else
{
accSource.X += (temp.translatedLetter.GetHashCode() % 2) * (accSource.Width * 2) + accSource.Width;
accSource.Y += ((int)(temp.translatedLetter.GetHashCode() / 2)) * accSource.Height;
spriteBatch.Draw(sprite, notePosition, accSource, Color.White);
}
*/
}

}
}
spriteBatch.End();
base.Draw(gameTime);
}

/// <summary>
/// Makes a new random table of notes
/// </summary>
private void MakeTable()
{
//make everything null
for (int r = 0; r < ROW_SIZE; r++)
{
for (int c = 0; c < COLUMN_SIZE; c++)
{
box[r, c] = null;
}
}

//then start
Random rand = new Random();
for (int i = 0; i < 12; i++)
{
bool isUnique;
bool noteEntered;

do
{
Note newNote = new Note((Note.Notes)rand.Next(0, 7),
rand.Next(0, 2) == 0 ? true : false,
rand.Next(0, 2) == 0 ? true : false);

isUnique = true;
noteEntered = false;
//Check to see if there exists a note like this
for (int r = 0; r < ROW_SIZE; r++)
{
for (int c = 0; c < COLUMN_SIZE; c++)
{
Note temp = box[r, c];
if (noteEntered || !isUnique)
continue;
else if (temp != null &&
temp.noteLetter == newNote.noteLetter &&
temp.isFlat == newNote.isFlat)
{
isUnique = false;
}
else if (temp == null)
{
box[r, c] = newNote;
noteEntered = true;
}

}
}
} while (!isUnique);
}
}
}


The main code running everything is the MakeTable() method, but I put in everything just in case there's a problem somewhere else. To the best of my knowledge, other than graphics libraries, I'm not using any libraries related to the XNA Framework that would cause this to go wrong. I'm using a rebuild of XNA made by CodePlex. I know they're still working on some things, but this shouldn't be an issue. Can someone help me with this?





How to make a computer move in a single player tic tac toe game [VB]

I'm trying to make a single player tic tac toe game. I already have 2 player working using some codes I found online but I'm not having any luck inputting the codes for single player with what I have already. I have a start menu that asks if you want to play 1 or 2 players then it goes to the game form to start the game (where all the main code is) Also I am new to vb and don't know all the terminology yet so if you can help out please be detailed and leave comments in the code.


What I'd like to do is make the computer move on a random choice for the first move then based on what is already played it will make the choice off of that. I think I can get that part on my own I just need help figuring out how to incorporate the random number generator into the code I already have.


One last thing I would like to know, is this vb.net or vb6? I don't really know the difference since this is my first Visual Basic project.


This is where I assume the code would go but if I am wrong let me know and I can post the entire code:



Public Class Form1
Dim flag As Boolean = False
Private mute As Integer = 0

Private Sub Buttons(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click

If flag = False Then
' DirectCast(sender, Button).Image = (My.Resources.Mario)
DirectCast(sender, Button).Text = "X"
flag = True
My.Computer.Audio.Play(My.Resources.fireball, AudioPlayMode.Background)
playerTurn.Text = " Turn: Player O "
buttonDisable()
computerMove()
Else
' DirectCast(sender, Button).Image = (My.Resources.Luigi)
DirectCast(sender, Button).Text = "O"
flag = False
My.Computer.Audio.Play(My.Resources.marioJump, AudioPlayMode.Background)
playerTurn.Text = " Turn: Player X "
buttonDisable()
End If
If muteOff.Visible = True Then
My.Computer.Audio.Stop()
End If
win()
checkDraw()
End Sub


Thanks in advanced!





SQL: Random query of row but sorted

What I want to achieve is to get a random set of row everytime I queried the database but still sorted say alphabetically. Is it possible? Thanks for any help.





Random Number Minecraft

Im trying to set a random number but excluding a certain number in the random.



public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {


Player player = (Player) sender;

if(commandLabel.equalsIgnoreCase("random")){

Random random = new Random();

int randomId = random.nextInt(300);

if(randomId >= 100 && randomId <= 200){
player.sendMessage("" + randomId);
}

while(randomId != 124){

randomId = random.nextInt(300);

}

}


I want to EXCLUDE the number 124 in the random.





Online api for random words generator

I am searching for an online free API that will provide me a a random word with a list of definitions in XML or JSON format(it doesn't make any difference); I searched a lot without any useful link. Every time I got an API, I found it to be fake or non complete(i.e. doesn't provide definitions). Any help is appreciated, and Thanks a lot.





Query random item per day in android sql

I am developing a mobile application that has thousands of records in a table and has a word of the day feature. The problem is that sqlite does not support seeding random function like mysql does in this sample query



SELECT *
FROM word_table
ORDER BY RAND('. date("mdY") .') LIMIT 1


Is there any other way that I can just query 1 item per day without inserting date to each item as it is time consuming?


Thanks Guys





how to play random .wav sounds?

I have a group of .wav sounds which are contained in a folder within the package. In the following code It will always play the same .wav sound every time the button is pressed. how to to add the Random function to read from the folder and play a different sound each time the button is pressed.



public void actionPerformed(ActionEvent e){
if (e.getSource() == Button)
play("/nameofthefolder/nameofsound.wav");

}




samedi 27 décembre 2014

Keep getting the same random values when using a function

I want to make a program that will do some kind of battle logs. You strike with 50% chance of hitting the enemy and deal damage from 10 to 25.



from random import randint

hitChance = randint(0,1)
damage = 10 + randint(0, 15)
HP = 100

def atack():
global HP

if hitChance is 0:
print("Missed")

elif hitChance is 1:
HP -= damage
print(damage, " delt")
print(HP, " left")

while HP > 0:
atack()
print("You defeated the enemy!")


However when i run this code it either stuck in an infinite loop of "missed" or deals the same damage values.





Where should I subtract 1 when generating random numbers?

When I want a random item of a list, I normally do:



import random
random.randint(0, len(array)-1)


(and then put that in as the index for the list - array[<codeabove>] )


However, I was wondering if it was more efficient / better practise to do the following:



import random
random.randint(1, len(array)) -1


Does it make any difference to execution time, or is better practise in general to use one over the other?





Add class to every few random elements with jquery

I have a sequence of elements, let's say:



<div class="tile1"></div>
<div class="tile2"></div>
<div class="tile3"></div>
<div class="tile4"></div>


etc.


How would I use Jquery to add the new class "color" to every few random elements with an increment varying between 2 and 6 like so:



<div class="tile1"></div>
<div class="tile2 color"></div>
<div class="tile3"></div>
<div class="tile4"></div>
<div class="tile5 color"></div>
<div class="tile6"></div>
<div class="tile7 color"></div>
<div class="tile8"></div>
<div class="tile9"></div>
<div class="tile10"></div>
<div class="tile11"></div>
<div class="tile12 color"></div>


etc.





Encode sequences of integers for randomness testing

I need to test the randomness of multiple sequences of integers. All sequences have the same number of integers, all integers are of range [0, 55439] (including 0 and 55439). I'm planning to test them with the NIST test suite (http://csrc.nist.gov/rng).


The NIST test suite only accept binary streams, so I must encode those integers into binary strings of the same length. Since 55440 isn't a power of 2, I cannot use the binary representation of these integers. If the binary representation is used, the most significant bit of the the representation is more likely to be 0, which will result in false negatives.


How should those integers be encoded ?





sql update random number


if (empty($_SESSION['last_read_topic']) || $_SESSION['last_read_topic'] != $topic)

{
$smcFunc['db_query']('', '
UPDATE {db_prefix}topics
SET num_views = num_views + 99
WHERE id_topic = {int:current_topic}',
array(
'current_topic' => $topic,
)
);

$_SESSION['last_read_topic'] = $topic;
}


in line... SET num_views = num_views + 99


how i random number between 1-99


thank you so much


i have answer thank you http://stackoverflow.com/users/3349551/nodisplayname



SET num_views = num_views + ROUND(((99-1-1) * RAND() + 1), 0)




vendredi 26 décembre 2014

Encode integers into binary stream for random test

I want to test the randomness of a sequence of generated integers. The integers are of range [1, 55440]. I'm using the NIST randomness test suite (http://csrc.nist.gov/rng). Since the NIST test suite only accepts binary streams, I must convert the integers to a binary stream.


I cannot use the binary representation of those integers directly, because of the range of the integers. 55440 is less than 65536 = 2^16, so the most significant bit of the binary representation is more likely to be 0, which may cause false negatives.


How should those integer be encoded for NIST test ?





Random Name To Exact File In Android

I need to generate random name to exact file in android programmatically.I mean that every time java runs the code it should generate random name not to overwrite the old one.Can i achieve that?





Android Image Name Randomize and Retrive

Good day guys.I created app which captures and saves image in randomized name.I want to know how is it able to retrive Last captured image and show on imageview??i fully mean last captured because for example if i capture heaps there will be heaps names randomaly created but i want to retrive on image view last captured image with saving this randomizing feature.Can i?





Random value in objective c gives incorrect numbers

I need to get random float values in range [-1, 1].



CGFloat max = 1;
CGFloat min = -1;


I use following code:



((float)arc4random()/RAND_MAX)*(max-min)+min


But i get value between -1.007 to 2.879 and so on. Where i have a problem. Thank you.





delete certain percent of rows randomnly

How can I delete 80% percent of my records randomly in sql





Qt qrand in cycle in Windows generate same numbers

I have qt application using qml. qrand in cycle works wrong, in code works right. This problem appears only at windows. Here is example:


In main.cpp at begin i print:



QTime time = QTime::currentTime();
qsrand((uint)time.msec());


then in cycle i use qrand



for (int j = 0; j < 4; j++)
for (int i = 0; i < 1000; i++){
int r1 = qrand() % 150;
int r2 = qrand() % 150;
qDebug() << r1 << r2 << endl;
}


in output there are 2 different numbers repeats about 200 times, then changes:



8 58
8 58
8 58
...
120 1
120 1
120 1
...


if i use qrand not in cycle, it works right. But, if i make function, that generates random numbers with qrand this function works wrong. In linux on gcc 64 bit compiler the same code works right, it generates different numbers in every line. In windows 7 and 8 with MSVC2012_OpenGL_32bit qrand works wrong. Also, i tried standard srand and rand(), it also works wrong. I checked (uint)time.msec(), it is always different. But if i put qsrand into cycle program generates not perfect, but different numbers:



for (int j = 0; j < 4; j++)
for (int i = 0; i < 1000; i++){
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
int r1 = qrand() % 150;
int r2 = qrand() % 150;
qDebug() << r1 << r2 << endl;
}


Output not perfect couse it qrand just generates different numbers more often, but again not always.


UPDATE: i tried c++11 random in windows and it works. I didn't try it in linux yet. But the question about qrand is still alive.


The c++11 random which i used: std random functions not working - Qt MinGw





select randomnly rows without changing the order in sql query

I searched every where to find sql query to select rows randomly without changing the order almost everyone uses something like this SELECT * FROM table WHERE type = 1 ORDER BY RAND() LIMIT 25 but above query changes the order. I need a query which selects randomly among the rows but dosnt changes the order, cause every record has a date also





mysql random select Latest 15 in 100 rows data


$sql = "SELECT `url`,`title`,`vid` FROM `video` ORDER BY `time` DESC limit 15";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);


This SQL can select the top new 15 rows data.


I want display the top new 100, but just show 15


How to select faster?





jeudi 25 décembre 2014

Is intel's RdRand TRNG or PRNG?

I've searched the net for quite a while and couldn't find a definitive answer. I want to know the quality of random numbers generated by intel's rdrand instructions. How does it compare to IDQ's cards for example? Is it truly random or pseudo random?


Thanks





For Statement With Randomiser

My application was working perfectly until I basically re-did a bunch of the code to add more features. The game is basically a randomizer telling you your job in the game, because you don't want others knowing your job. There is Murderer, Judge, Backup-Judge, and Innocent. I created a admin panel to make sure certain features are working. This version of the app supports 5-8 players. In the app there is an admin function so if you only have 5 players you can click a button and it will tell you whether or not the main jobs, Murderer, And Judge(or Backup Judge incase the main judge dies or the randomiser selects this before the judge) are in the first 5 strings. Because if it is not, you must re-run the application until you can play correctly. So i have a feature that checks it it will work for: 5 players, 6 players, 7 players, and 8 players.


UPDATE - Sorry: The main problem is that it is no longer setting the variable to: job1, job2, etc. When you run the code and it opens the window, and you click the button to see the first variable, it will display it, when you click it 2 times to get to the next one, its blank. When using the admin panel and clicking on 8 Players, it will only say their is 1 of the xx position. xx is whatever job is the first variable/job1. It only displays if its murderer, judge, co-judge/backup-judge.


Here is the code:



package main;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {

private static JFrame window = new JFrame();

private static JPanel one = new JPanel();
private static JPanel two = new JPanel();
private static JPanel three = new JPanel();

//1-4 Players
private static JLabel job1 = new JLabel();
private static JLabel job2 = new JLabel();
private static JLabel job3 = new JLabel();
private static JLabel job4 = new JLabel();
private static JLabel job5 = new JLabel();
private static JLabel job6 = new JLabel();
private static JLabel job7 = new JLabel();
private static JLabel job8 = new JLabel();
private static JLabel jobprint = new JLabel();
private static JLabel apcheck = new JLabel();

private static JButton next = new JButton("Click To Find Your Position");
private static JButton ap = new JButton("Admin Panel");

private static JButton five = new JButton("Five Players");
private static JButton six = new JButton("Six Players");
private static JButton seven = new JButton("Seven Players");
private static JButton eight = new JButton("Eight Players");
private static JButton apexit= new JButton("Exit Admin Panel");

private static int countertwo = 0;
private static int counter = 0;
private static int m5 = 0;
private static int j5 = 0;
private static int m6 = 0;
private static int j6 = 0;
private static int m7 = 0;
private static int j7 = 0;
private static int m8 = 0;
private static int j8 = 0;
private static int cj = 0;



public static void shuffleArray(String[] a) {
int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}

private static void swap(String[] a, int i, int change) {
String helper = a[i];
a[i] = a[change];
a[change] = helper;
}

public static void main(String[] args) {
String[] a = new String[] {"Murderer", "Judge", "Backup Judge", "Innocent", "Innocent", "Innocent", "Innocent", "Innocent"};
shuffleArray(a);

next.setVisible(true);
job1.setVisible(false);
job2.setVisible(false);
job3.setVisible(false);
job4.setVisible(false);


for (String i : a) {
System.out.println(i);
counter++;
if(counter == 1){
job1.setText(i);
if(job1.getText() == "Murderer"){
m5++;
}
if(job1.getText() == "Judge"){
j5++;
}
if(job1.getText() == "Backup Judge"){
cj++;
}
}
if(counter == 2){
job1.setText(i);
if(job2.getText() == "Murderer"){
m5++;
}
if(job2.getText() == "Judge"){
j5++;
}
if(job2.getText() == "Backup Judge"){
cj++;
}
}
if(counter == 3){
job1.setText(i);
if(job3.getText() == "Murderer"){
m5++;
}
if(job3.getText() == "Judge"){
j5++;
}
if(job3.getText() == "Backup Judge"){
cj++;
}
}
if(counter == 4){
job1.setText(i);
if(job4.getText() == "Murderer"){
m5++;
}
if(job4.getText() == "Judge"){
j5++;
}
if(job4.getText() == "Backup Judge"){
cj++;
}
}
if(counter == 5){
job1.setText(i);
if(job5.getText() == "Murderer"){
m5++;
}
if(job5.getText() == "Judge"){
j5++;
}
if(job5.getText() == "Backup Judge"){
cj++;
}
}
if(counter == 6){
job1.setText(i);
if(job6.getText() == "Murderer"){
m6++;
}
if(job6.getText() == "Judge"){
j6++;
}
if(job6.getText() == "Backup Judge"){
cj++;
}
}
if(counter == 7){
job1.setText(i);
if(job7.getText() == "Murderer"){
m7++;
}
if(job7.getText() == "Judge"){
j7++;
}
if(job7.getText() == "Backup Judge"){
cj++;
}
}
if(counter == 8){
job1.setText(i);
if(job8.getText() == "Murderer"){
m8++;
}
if(job8.getText() == "Judge"){
j8++;
}
if(job8.getText() == "Backup Judge"){
cj++;
}
}
}
apexit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
five.setVisible(false);
six.setVisible(false);
seven.setVisible(false);
eight.setVisible(false);
apcheck.setVisible(false);
}
});

ap.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
five.setVisible(true);
six.setVisible(true);
seven.setVisible(true);
eight.setVisible(true);
apcheck.setVisible(true);
// hide.setVisible(true);
}
});
five.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(j5 + m5 == 2){
apcheck.setText("Murderer And Judge Assigned");
System.out.println("Murderer & Judge Positions - ASSIGNED - 5 Players");
}else if(j5 + m5 != 2){
apcheck.setText("Murderer And Judge *NOT* Assigned - *RE-RUN*");
System.out.println("Murderer & Judge Positions - NOT ASSIGNED - 5 Players");
}
}
});
six.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(j6 + m6 + j5 + m5 == 2){
apcheck.setText("Murderer And Judge Assigned");
System.out.println("Murderer & Judge Positions - ASSIGNED - 6 Players");
}else if(j6 + m6 != 2){
apcheck.setText("Murderer And Judge *NOT* Assigned - *RE-RUN*");
System.out.println("Murderer & Judge Positions - NOT ASSIGNED - 6 Players");
}
}
});
seven.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(j7 + m7 + j6 + m6 + j5 + m5 == 2){
apcheck.setText("Murderer And Judge Assigned");
System.out.println("Murderer & Judge Positions - ASSIGNED - 7 Players");
}else if(j7 + m7 + j6 + m6 + j5 + m5 != 2){
apcheck.setText("Murderer And Judge *NOT* Assigned - *RE-RUN*");
System.out.println("Murderer & Judge Positions - NOT ASSIGNED - 7 Players");
}
}
});
eight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if(j8 + m8 + j7 + m7 + j6 + m6 +j5 + m5 + cj == 3){
apcheck.setText("Murderer And Judge Assigned");
System.out.println("Murderer & Judge Positions - ASSIGNED - 8 Players");
}else if(j8 + m8 + j7 + m7 + j6 + m6 +j5 + m5 + cj!= 3){
apcheck.setText("Murderer And Judge *NOT* Assigned - *RE-RUN*");
System.out.println("ERROR: FIX CODE!");
System.out.println("CJ: " + cj + " J: " + (j5 + j6 + j7 + j8) + " M: " + (m5 + m6 + m7 + m8) + "**");
}
}
});

next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(countertwo == 0){
jobprint.setVisible(true);
jobprint.setText(job1.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 1){
jobprint.setText("");
next.setText("Click To Find Your Position");
countertwo++;
}else if(countertwo == 2){
jobprint.setText(job2.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 3){
jobprint.setText("");
next.setText("Click To Find Your Position");
countertwo++;
}else if(countertwo == 4){
jobprint.setText(job3.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 5){
jobprint.setText("");
next.setText("Click To Find Your Position");
countertwo++;
}else if(countertwo == 6){
jobprint.setText(job4.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 7){
jobprint.setText("");
next.setText("Click To Find Your Position");
countertwo++;
}else if(countertwo == 8){
jobprint.setText(job5.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 9){
jobprint.setText("");
next.setText("Click To Find Your Position");
countertwo++;
}else if(countertwo == 10){
jobprint.setText(job6.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 11){
jobprint.setText("");
next.setText("Click To Find Your Position");
countertwo++;
}else if(countertwo == 12){
jobprint.setText(job7.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 13){
jobprint.setText("");
next.setText("Click To Find Your Position");
countertwo++;
}else if(countertwo == 14){
jobprint.setText(job8.getText());
next.setText("Click Again");
countertwo++;
}else if(countertwo == 15){
jobprint.setText("By Fletcher Henneman");
next.setVisible(false);
}
}
});


window.setLayout(new GridLayout(5, 1));
window.setSize(500,400);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(true);

window.add(one);
window.add(two);
window.add(three);

one.setLayout(new GridLayout(3, 4));
two.setLayout(new GridLayout(3, 4));

one.add(jobprint);

two.add(next);
two.add(ap);

two.add(five);
two.add(six);
two.add(seven);
two.add(eight);
three.add(apcheck);
three.add(apexit);

five.setVisible(false);
six.setVisible(false);
seven.setVisible(false);
eight.setVisible(false);

window.setVisible(true);
}
}




Generate random time for subactions inside of repeatActionforever under sequence for SWIFT

Hi I'm trying to generate random time intervals everytime the action is repeated but it only generates the time interval randomly only when the vied did load.


Here is my code :



let moveBucketLeft = SKAction.moveByX(400, y: 0, duration: NSTimeInterval(grabRandomTime()))
let moveBucketRight = SKAction.moveByX(-400, y: 0, duration: NSTimeInterval(grabRandomTime()))
moveBucketLeftAndRight = SKAction.sequence([moveBucketLeft,moveBucketRight])
let repeatMovement = SKAction.repeatActionForever(moveBucketLeftAndRight)
bucket.runAction(repeatMovement)


The method grabRandomTime just generates a random duration between 1 and 5 .


I need all the help I can help. Thank you!





Java Thread Random

Ok, so I want to generate a random number for printing in a thread. One and two work fine, but three just prints out the same random number. So if a generates 1928, it sleeps for 1928 over and over again. How do I make dynamically random numbers? Three is the only one where I want to interrupt if another random number(num) is smaller than 1000.



package thread;

import java.util.Random;

public class Threads {

public static Thread one;
public static Thread two;
public static Thread three;

public static int numbers[] = { 1, 2, 3, 4, 5 };
public static String letters[] = { "a", "b", "c", "d", "e" };
public static float negatives[] = { -1, -2, -3, -4, -5 };
public static Random rand = new Random();

public static void main(String args[]) {
startSequences();
one.setName("one");
two.setName("two");
three.setName("three");
one.start();
two.start();
three.start();
}

public static void startSequences() {
one = new Thread() {
public void run() {
try {
System.out
.println("Numbers\n-----------------------------------");
for (int i = 0; i < numbers.length; i++) {
int a = rand.nextInt(3999);
System.out.printf(
"%s is sleeping for %d milliseconds. \n",
Thread.currentThread().getName(), a);
Thread.sleep(a);
System.out.println(Thread.currentThread().getName()
+ " is done sleeping.");
System.out.printf("current number is %s\n", numbers[i]);
}

} catch (InterruptedException e) {
System.out.printf("%s has been interrupted. How rude!",
Thread.currentThread().getName());
} finally {
System.out.printf("%s is finally done!\n", Thread
.currentThread().getName());
}
}
};

two = new Thread() {
public void run() {
try {
one.join();
System.out
.println("\nLetters\n-----------------------------------");
for (int i = 0; i < letters.length; i++) {
int a = rand.nextInt(3999);
System.out.printf(
"%s is sleeping for %d milliseconds.\n", Thread
.currentThread().getName(), a);
Thread.sleep(a);
System.out.println(Thread.currentThread().getName()
+ " is done sleeping.");
System.out.printf("current letter is %s\n", letters[i]);
}
} catch (InterruptedException e) {
System.out.printf("%s has been interrupted. How rude!",
Thread.currentThread().getName());
} finally {
System.out.printf("%s is now done. Finally!", Thread
.currentThread().getName());
}
}
};

three = new Thread() {
public void run() {
try {
int num = rand.nextInt(3999);
two.join();
if (num < 1000) {
System.out
.printf("\n%s is being interrupted because the random was %d and lower than 1000.",
Thread.currentThread().getName(), num);
Thread.sleep(2000);
Thread.currentThread().interrupt();
} else {
int a = rand.nextInt(3999);
System.out
.println("\nNegatives-----------------------------------\n");
System.out
.printf("the number was %s, Therefore, it will not be interrupted.",
num);
for (int i = 0; i < negatives.length; i++) {
System.out.printf(
"\n%s is sleeping for %d milliseconds.",
Thread.currentThread().getName(), a);
Thread.sleep(a);
System.out.printf("\n%s has finished sleeping.",
Thread.currentThread().getName());
System.out.printf(
"\ncurrent negative number is %s",
negatives[i]);
}
}
} catch (InterruptedException e) {
System.out.printf("\n%s has been interrupted. How rude!",
Thread.currentThread().getName());
} finally {
System.out.printf("\n%s is now done. Finally!", Thread
.currentThread().getName());
}
}
};
}

}




Cross Validation WEKA random

WEKA Cross Validation:



Classifier cls = new J48();
Evaluation eval = new Evaluation(data);
Random rand = new Random(1); // using seed = 1
int folds = 10;
eval.crossValidateModel(cls, data, folds, rand);
System.out.println(eval.toSummaryString());


What does it mean "rand"? How does cross validation in this case? 10 folds are always mixed?


Thank you!





mercredi 24 décembre 2014

randomly choose between classes and apply them to div upon page load?

Is this possible?: Upon page load, for any <figure> that has a class called '.random' will randomly assign its image an element that'll be between float:left; or float:right;.


I have set up a jsfiddle.


Many thanks and happy christmas eve / christmas!





How to get the amount of the specified random number in Java FOR LOOP

I would like to ask how to get the amount of the specified number. For example, I want to see the amount of the number 1234 which has been generated in the random generator. I would like it to print out the amount of the specified number which has been generated.


Merry Christmas. Thanks for your reply.





Random int function behavior in Java

I have the following piece of code:



public class Main {
private static final Random rnd = new Random();

private static int getRand(int n) {
return (Math.abs(rnd.nextInt())%n);
}

public static void main(String[] args) {
int count=0, n = 2 * (Integer.MAX_VALUE/3);
for(int i=0; i<1000000; i++) {
if(getRand(n) < n/2) {
count++;
}
}
System.out.print(count);
}
}


This always gives me a number closer to 666,666. Meaning two-thirds of the numbers generated are below the lower half of n. Not that this is obtained when n = 2/3 * Integer.MAX_VALUE. 4/7 is another fraction that gives me a similar spread (~5714285). However, I get an even spread if n = Integer.MAX_VALUE or if n = Integer.MAX_VALUE/2. How does this behavior differ with the fraction used. Can somebody throw some light on it.


PS: I got this problem from the book Effective Java by Joshua Bloch.





Working with random integers

Here is the assignment: For this program, there are two "parts". The first part will run the trials and determine how many caps each trial opens before finding a winning cap. Every trial (person) will be a winner. The number of caps opened by each trial is written to the file. (The output file should contain only integers). (This is where you will use nested loops...a for and a while...not two for's)


The second part of the program will read in the values and calculate the average. The average should be between 4.5 and 5.5 since there is a 1 in 5 chance of winning.


I know I have many mistakes, I want someone to tell me where to start. I do not know much about java.


My code:



int randNum = 0;
Random randNumList = new Random();

int counter = 0;
Scanner in = new Scanner(System.in);
System.out.println("How many trials will there be?");
int trials = in.nextInt();

int winner = 0;

PrintWriter outFile = new PrintWriter (new File("cap.txt"));
//run trials
for (int loop = 1; loop <= trials; loop++)
{
//select random number until 5 is selected
randNum = randNumList.nextInt(6);
for (randNum = randNumList.nextInt(6); randNum == 5; randNum++)
{
randNum = randNumList.nextInt(6);
counter++;
}

outFile.println(loop + " " + randNum);
}


outFile.close ( ); //close the file when finished

String token = " ";
Scanner inFile = new Scanner(new File("cap.txt"));

while (inFile.hasNext())
{
token = inFile.next();
if(token.equals("5"))
winner++;
}

double average = winner/counter;
System.out.println("The average number is " + average);




Random CSS value

I have this page where I have 3 triangles made purely out of CSS. Every time someone loads the page I want the triangle to have different sizes.


Here's the thing illustrated in a JSFiddle : http://ift.tt/1AK9ZMz


What I would like to do is to randomly set the value of border-width of every triangle at page load.


I was thinking doing that with JavaScript with a Math.random or something but I didn't manage to do it, nor found some help on the internet (I don't know how to write in Javascript).


I would appreciate a little help or guidance for this. Thanks a lot





Repetitive usage of Java's SecureRandom

I'm a little bit confused about the usage of SecureRandom. I need to generate n random numbers in a loop. Is it secure to use the same SecureRandom instance for each generation? Are there any difference between the solutions below in terms of cryptographic strength?


1) Single instance without seeding



SecureRandom sr = new SecureRandom();
for(int i = 0; i < n; ++i) sr.nextInt();


2) New instance for each generation



for(int i = 0; i < n; ++i) new SecureRandom().nextInt();


3) Single instance with seeding



SecureRandom sr = new SecureRandom()
for(int i = 0; i < n; ++i) {
byte[] seed = sr.generateSeed(32);
sr.setSeed(seed);
sr.nextInt();
}




Cross-platform cross-language cross-everything actually deterministic random number generator

I'm looking for an algorithm to generate random numbers from a given seed but with the particular requirement that it will always generate the same sequence of number regardless of the underlying computer architecture or language implementation.


I already know of Mersenne Twister, however, the numbers it generates differ when using different implementations (i.e. C MT vs Javascript MT).


Do algorithms with this property exist? Also, I don't need a state-of-the-art RNG, I don't even need it to be cryptographically secure, I just want to drive a "random" simulation on one place and have it follow the same behavior on a different implementation.





random generator and openCV in c++

This is my function for generating random white noise in openCV and c++. Can anyone point me to the real problem ?



int i,j;

int h = image.cols;
int w = image.rows;

for(int k=0; k<n ; k++)
{

i = Random(h);
j = Random(w);


if(image.channels() == 1)
{
image.at<uchar>(j,i) = 255;
}
else if (image.channels() == 3)
{
image.at<cv::Vec3b>(j,i)[0] = 255;
image.at<cv::Vec3b>(j,i)[1] = 255;
image.at<cv::Vec3b>(j,i)[2] = 255;

}

}


![enter image description here][1]





mardi 23 décembre 2014

How to use a random generated number in a parameter

So i am trying to change the enemies health based on a randomly number. When I try to pass a number using the random class I get an error:



The method changeEnemyHealth(int, int) in the type enemyStats is not applicable for the arguments (int)


And the code:



int enemyDamage = Random_damage.nextInt(31) + 270;
enemyStats.changeEnemyHealth(enemyDamage);
playerStats.changePlayerMana(-4);

public class enemyStats{

public static void changeEnemyHealth(int EHealth){
EnemyHealth += EHealth;
}
}




Random Choice is out of list range in Python?

I am trying to create a program that will guess the number you entered. I was trying to get the computer to get the number in as few guesses as possible so I am doing something like a binary search. I keep getting a Index out of range when I run the code and it gets to total = total[the_low_one:computer2_guess]. I am confused why it is out of range. Should I be adding or subtracting one to the_low_one each time it hits a new low so it stays in range? I would appreciate any help as I am lost. Thanks a bunch in advance! Code:



def second_computer():
global computer2_score
computer2_score=0
computer2_guess= -1
the_low_one=1
the_high_one=1000000
total= range(1,1000000)
while computer2_guess != pick_number:
computer2_guess=random.choice(total)
if computer2_guess>pick_number:
total=total[the_low_one:computer2_guess]
the_high_one=computer2_guess-1
else:
total=total[computer2_guess:the_high_one]
the_low_one=computer2_guess+1
computer2_score+=1