samedi 28 février 2015

Quiz Program using a Text File

Am trying to create a quiz program in Python where the questions are stored in one txt file with the answers in another. The questions are set out in the text file as follows:


Which one of these is a percussion instrument? A. Trumpet B. Euphonium C. Viola D. Glockenspiel


The program pulls the questions out in random order and keeps score of the number of right answers. I know how to open files, read from them and display the contents of the file on the screen, I even know now how to randomise the info in the file. However, as there are multiple lines involved AND another file to get the answer from, I have no idea where to start. I would really appreciate any help you could offer me. Feel free to ask questions if you need to clarify anything.





C# console app random number generation

How can I get the random number generator method to loop and produce new random numbers? Do I need a separate class before Main that handles the random number generation? If so, how do I get the scope of those variables to Main? The console app is supposed to repeat integer math problems to practice with a loop that conditions on correct or incorrect answer. Also, what syntax am I overlooking to loop back to a new instance of randomly generated integers? TIA.



public class Multiplication
{
public static void Main(string[] args)
{
Random randomNumbers = new Random(); // random number generator
int num01 = randomNumbers.Next(1, 11);
int num02 = randomNumbers.Next(1, 11);
int value = 0;
while (true)
{
if (value != -1)
{
Console.Write("Please enter the answer to {0} x {1} = ?", num01, num02);
int product = num01 * num02;
Console.WriteLine();
int answer = Convert.ToInt32(Console.ReadLine());

while (product != answer)
{
Console.WriteLine("Incorrect, enter another guess: ");
answer = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Correct. Your answer was {0} \n {1} x {2} = {3} Very good!",
answer, num01, num02, product);
//keep console open
Console.WriteLine();
Console.WriteLine("Press - 1 to exit");
value = Convert.ToInt32(Console.ReadLine());
}
else
{
break;
}
}
}
}




xCode Swift: Developing a Random Point game with progressively harder rounds

Using: xCode 6, Swift /w SpriteKit


Prompt: I am developing a game and part of it requires that a point that is randomly sized between 32 x 32 and 64 x 64 is randomly generated around the screen with a number inside it.


Basically the user then needs to tap the dots in the order they appear. Once the dots run out the user wins (Dots remaining number is in the corner)


Issue: My issue that once the point is generated I need the next point to appear while the the proceeding point is still active.


--



  1. While point 1 appears point 2 is fading in.

  2. Randomly generated around the screen.

  3. Number ordered.

  4. Optimized for performance in mind


--


EDIT: Realized I forgot to post some code!


Basics that I have:



let screenWidth = screenSize.width
let screenHeight = screenSize.height
var x = arc4Random() % screenWidth
var y = arc4Random() % screenHeight


All ideas and theories are welcome! Thanks for all help that is given.





Java get random double between two doubles

I want to get a random between two doubles. Example:



0.00 and 0.50


then get random between them output is:



0.23


how do i do this with java





SELECT FROM @random_table SQL-SERVER 2008 R2

I'm having an issue with the following code:



DECLARE @table varchar(50), @value int
SET @table = 'randomTable'
EXEC('SELECT @value = exercicio FROM '+@table+' WHERE cod=2')


I need to do a couple of operations like that one above in some random tables. I want to select a value and store in a variable preveiously declared. But when I tried to execute that code, I received the following message:



Must declare the scalar variable "@value".


I'm out of ideas. Any suggestions?





Generate random number from normal distribution fortran

i need to generate random number from normal distribution with mean = 0 and variance = 1 in FORTRAN

any help??





Define buttonnummer programmatically?

I'm trying to set the title of a button in Swift. The button title and number is random. I have button1..16. Swift doesn't accept 'button' with 'String doesn't have a member named 'setTitle'. How can I make Swift accept this?



var buttonNumber = arc4random_uniform(16) + 1
var targetNumber = arc4random_uniform(20) + 1
var button = "button\(buttonNumber)"
button.setTitle("\(targetNumber)", forState: UIControlState.Normal)




Random GameObject

Who can help me? I have code unity 2D:



public GameObject Tube1;
public GameObject Tube2;
public GameObject Tube3;


So, how to Random(Tube1,Tube2,Tube3) in c# script; Thank you very much!





vendredi 27 février 2015

Algorithm to generate positive random integers smaller than given integer n

There are algorithms to generate random numbers like:



number = (previous_number * constant + other_constant) mod third_constant


for carefully selected constants. But I need algorithm to generate random integers that are in range of 0 to n-1. (Obviously not running loop and getting the counter, I need randomness). How is this possible? Thank you.





How to have seven unique number between 0 and 14?

I need to have seven unique number between 0 and 14 (from 0 to 13). I came up with the below code -



private Set<Integer> generateNumber() {
Set<Integer> randomNumberList = new HashSet<Integer>();

while (true) {
if (randomNumberList.size() == 7) {
break;
}
randomNumberList.add(random.nextInt((14 - 0) + 1) + 0);
}

return randomNumberList;
}


Is there any better way of doing this? I am not sure whether I should use while true here for this simple thing.





Checking for randomness using the Chi-Square Test

I'm running a simulation for a class project that relies heavily on random number generators, and as a result we're asked to test the random number generator to see just how "random" it is using the Chi-Square static. After looking through the some posts here, I used the follow code to find the answer:



observed = []
for i in range(0, numIterations):
tempList.append(randint(0, 100))
data = np.array(observed)
print "(chi squared statistic, p-value) with", numOfIter, "samples generated: ", chisquare(data)


However, I'm getting a p-value of zero when numIterations is greater than 10, which doesn't really make sense considering the null hypothesis is that the data is uniform. Am I misinterpreting the results? Or is my code simply wrong?





Dynamic Weighting Randomization

I'm trying to make a path by drawing from a pre-defined set of tiles, each of which are of a certain "type". However, I want to weight the randomization so that each "type" starts off with an equal chance, but certain conditions will cause the weighting of a particular "type" (such as having been chosen very often) to either increase or decrease.


I'm not very familiar with randomization algorithms. Are there any pre-existing algorithms that are a good match for my setup?





how to create non duplicated random numbers - Xcode [duplicate]


This question already has an answer here:




I am creating a random number game that has 9 different numbers and i want to randomise the numbers so they are randomised with non duplicates (e.g., 1,4,2,3,6,5,9,7,8) but at the moment i am just getting 9random numbers between 1 and 9 with multiple duplicates. Can anyone suggest anything without changing the existing code too much.


Thank you.



-(IBAction)Randomise

{


int rNumber1 = arc4random_uniform(9);

Text1.text = [NSString stringWithFormat: @"%d",rNumber1 + 1];

if ([Text1.text isEqualToString: @"1"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text1.text isEqualToString: @"2"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text1.text isEqualToString: @"3"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text1.text isEqualToString: @"4"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text1.text isEqualToString: @"5"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text1.text isEqualToString: @"6"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text1.text isEqualToString: @"7"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text1.text isEqualToString: @"8"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text1.text isEqualToString: @"9"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"9.png"]];
}





int rNumber2 = arc4random_uniform(9);


Text2.text = [NSString stringWithFormat: @"%d",rNumber2+1];


if ([Text2.text isEqualToString: @"1"])
{
[AnimatedPicture1 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text2.text isEqualToString: @"2"])
{
[AnimatedPicture1 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text2.text isEqualToString: @"3"])
{
[AnimatedPicture1 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text2.text isEqualToString: @"4"])
{
[AnimatedPicture1 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text2.text isEqualToString: @"5"])
{
[AnimatedPicture1 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text2.text isEqualToString: @"6"])
{
[AnimatedPicture1 setImage:[UIImage imageNamed:@"6.png"]];
}


else if ([Text1.text isEqualToString: @"7"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text1.text isEqualToString: @"8"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text1.text isEqualToString: @"9"])
{
[AnimatedPicture setImage:[UIImage imageNamed:@"9.png"]];
}




int rNumber3 = arc4random_uniform(9);


Text3.text = [NSString stringWithFormat: @"%d",rNumber3+1];


if ([Text3.text isEqualToString: @"1"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text3.text isEqualToString: @"2"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text3.text isEqualToString: @"3"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text3.text isEqualToString: @"4"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text3.text isEqualToString: @"5"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text3.text isEqualToString: @"6"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text3.text isEqualToString: @"7"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text3.text isEqualToString: @"8"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text3.text isEqualToString: @"9"])
{
[AnimatedPicture2 setImage:[UIImage imageNamed:@"9.png"]];
}



int rNumber4 = arc4random_uniform(9);


Text4.text = [NSString stringWithFormat: @"%d",rNumber4+1];


if ([Text4.text isEqualToString: @"1"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text4.text isEqualToString: @"2"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text4.text isEqualToString: @"3"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text4.text isEqualToString: @"4"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text4.text isEqualToString: @"5"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text4.text isEqualToString: @"6"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text4.text isEqualToString: @"7"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text4.text isEqualToString: @"8"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text4.text isEqualToString: @"9"])
{
[AnimatedPicture3 setImage:[UIImage imageNamed:@"9.png"]];
}



int rNumber5 = arc4random_uniform(9);


Text5.text = [NSString stringWithFormat: @"%d",rNumber5+1];


if ([Text5.text isEqualToString: @"1"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text5.text isEqualToString: @"2"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text5.text isEqualToString: @"3"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text5.text isEqualToString: @"4"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text5.text isEqualToString: @"5"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text5.text isEqualToString: @"6"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text5.text isEqualToString: @"7"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text5.text isEqualToString: @"8"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text5.text isEqualToString: @"9"])
{
[AnimatedPicture4 setImage:[UIImage imageNamed:@"9.png"]];
}




int rNumber6 = arc4random_uniform(9);


Text6.text = [NSString stringWithFormat: @"%d",rNumber6+1];


if ([Text6.text isEqualToString: @"1"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text6.text isEqualToString: @"2"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text6.text isEqualToString: @"3"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text6.text isEqualToString: @"4"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text6.text isEqualToString: @"5"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text6.text isEqualToString: @"6"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text6.text isEqualToString: @"7"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text6.text isEqualToString: @"8"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text6.text isEqualToString: @"9"])
{
[AnimatedPicture5 setImage:[UIImage imageNamed:@"9.png"]];
}



int rNumber7 = arc4random_uniform(9);


Text7.text = [NSString stringWithFormat: @"%d",rNumber7+1];


if ([Text7.text isEqualToString: @"1"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text7.text isEqualToString: @"2"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text7.text isEqualToString: @"3"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text7.text isEqualToString: @"4"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text7.text isEqualToString: @"5"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text7.text isEqualToString: @"6"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text7.text isEqualToString: @"7"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text7.text isEqualToString: @"8"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text7.text isEqualToString: @"9"])
{
[AnimatedPicture6 setImage:[UIImage imageNamed:@"9.png"]];
}




int rNumber8 = arc4random_uniform(9);


Text8.text = [NSString stringWithFormat: @"%d",rNumber8+1];


if ([Text8.text isEqualToString: @"1"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text8.text isEqualToString: @"2"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text8.text isEqualToString: @"3"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text8.text isEqualToString: @"4"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text8.text isEqualToString: @"5"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text8.text isEqualToString: @"6"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text8.text isEqualToString: @"7"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text8.text isEqualToString: @"8"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text8.text isEqualToString: @"9"])
{
[AnimatedPicture7 setImage:[UIImage imageNamed:@"9.png"]];
}



int rNumber9 = arc4random_uniform(9);


Text9.text = [NSString stringWithFormat: @"%d",rNumber9+1];


if ([Text9.text isEqualToString: @"1"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"1.png"]];
}

else if ([Text9.text isEqualToString: @"2"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"2.png"]];
}

else if ([Text9.text isEqualToString: @"3"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"3.png"]];
}

else if ([Text9.text isEqualToString: @"4"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"4.png"]];
}

else if ([Text9.text isEqualToString: @"5"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"5.png"]];
}

else if ([Text9.text isEqualToString: @"6"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"6.png"]];
}

else if ([Text9.text isEqualToString: @"7"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"7.png"]];
}

else if ([Text9.text isEqualToString: @"8"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"8.png"]];
}

else if ([Text9.text isEqualToString: @"9"])
{
[AnimatedPicture8 setImage:[UIImage imageNamed:@"9.png"]];
}



AnimatedPicture.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture1.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture2.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture3.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture4.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture5.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture6.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture7.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];

AnimatedPicture8.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:@"1.png"],
[UIImage imageNamed:@"2.png"],
[UIImage imageNamed:@"3.png"],
[UIImage imageNamed:@"4.png"],
[UIImage imageNamed:@"5.png"],
[UIImage imageNamed:@"6.png"],
[UIImage imageNamed:@"7.png"],
[UIImage imageNamed:@"8.png"],
[UIImage imageNamed:@"9.png"], nil];



[AnimatedPicture setAnimationRepeatCount:3];
AnimatedPicture.animationDuration = 1.0;
[AnimatedPicture startAnimating];


[AnimatedPicture1 setAnimationRepeatCount:3];
AnimatedPicture1.animationDuration = 1.0;
[AnimatedPicture1 startAnimating];

[AnimatedPicture2 setAnimationRepeatCount:3];
AnimatedPicture2.animationDuration = 1.0;
[AnimatedPicture2 startAnimating];

[AnimatedPicture3 setAnimationRepeatCount:3];
AnimatedPicture3.animationDuration = 1.0;
[AnimatedPicture3 startAnimating];

[AnimatedPicture4 setAnimationRepeatCount:3];
AnimatedPicture4.animationDuration = 1.0;
[AnimatedPicture4 startAnimating];

[AnimatedPicture5 setAnimationRepeatCount:3];
AnimatedPicture5.animationDuration = 1.0;
[AnimatedPicture5 startAnimating];

[AnimatedPicture6 setAnimationRepeatCount:3];
AnimatedPicture6.animationDuration = 1.0;
[AnimatedPicture6 startAnimating];

[AnimatedPicture7 setAnimationRepeatCount:3];
AnimatedPicture7.animationDuration = 1.0;
[AnimatedPicture7 startAnimating];

[AnimatedPicture8 setAnimationRepeatCount:3];
AnimatedPicture8.animationDuration = 1.0;
[AnimatedPicture8 startAnimating];


}




C - Monte Carlo Integration - Randoms not random and count not counting?

Heads up, I'm a bit of a C newbie :P


I'm trying to figure out why my program isn't running as intended.


First, it's supposed return an x and y value within the range 0.0 to 10.0, which it does, but shouldn't randoms reset after each run? I'm getting the same X and Y values every time I run the program.


Second, my loop doesn't seem to be doing anything. The count isn't increasing at all and I have no clue why - I'm assuming this is fixed, I should start seeing some correct results.



#include <stdio.h>
#include <stdlib.h>

void throwDart(double *x, double *y)
{
double min = 0.0, max = 10.0;

*x = (max - min) * ((double)rand() / (RAND_MAX)) + min; //don't nec. need min - example format
*y = (max - min) * ((double)rand() / (RAND_MAX)) + min; //^same
}

double Fun(double x)
{
return ((0.3*x*x) - (0.2*x) - 5); //estimate value of definite integral using this function
}

int main()
{
double x, y, P; //(x,y) is location, P is number of darts that hit below the curve/total thrown
int N, e; //N is number of darts, e is area under curve
int c = 0; //initialize count of darts that hit below the curve

throwDart(&x, &y);

printf("How many darts would you like to throw?\n");
scanf("%d", &N);

for (int i = 0; i < N; i++)
{
if (y <= Fun(x))
c++;
}

P = c/N;
e = 100.00 * P;

//most of the following prints just to see what is and isn't working
printf("X is %lf\n", x);
printf("Y is %lf\n", y);
printf("N is %d\n", N);
printf("c is %d\n", c);
printf("P is %d\n", P);
printf("Area under the curve is %d\n", e);

system("Pause");

}




Generate random QString yields same result every time

I'm working on a QT project where a user inputs their full name and the program generates a random 5 character password based off of the letters in their name. Unfortunate I've run into an issue where it works but every time I rerun the program it yields the same result. So it clearly isn't very random. Even after exiting QT Creator and opening it again and running the program with the same user input it yields the same results.


I also am required to generate the password without spaces.


Here is my code:



while(password.length() < 5) {
int index = qrand() % fullName.length();
QChar nextChar = fullName.at(index);
if (!nextChar.isSpace()) {
password.append(nextChar);
}
}


Any solution would be much appreciated.





How would I append items to a list, use that information, clear the list, and then use it again?

This is just a part of the code that I am using to try to make a game sort of like yahtzee. It probably looks a little rough (this is my first project since finishing the codeacademy course).


What I need to do is put the number between 1-6 randomly chosen associated with each dice into a list that I can work with to eventually decide if the numbers are 3 of a kind, four of a kind and so on.


I just need a simple way to work with the numbers in the list and then after they choose to roll again I can erase the numbers and add new random numbers to the list.



dice_1 = random.randrange(1,7)
dice_2 = random.randrange(1,7)
dice_3 = random.randrange(1,7)
dice_4 = random.randrange(1,7)
dice_5 = random.randrange(1,7)

dice_list = []

def roll_dice(): #adds random number of dice to dice_list
dice_list.append(dice_1)
dice_list.append(dice_2)
dice_list.append(dice_3)
dice_list.append(dice_4)
dice_list.append(dice_5)

def choice():
player_turn = 1
while player_turn <= 3:
roll_again = raw_input("Would you like to roll again? (yes or no)")
if len(roll_again) == 3:
del dice_list[0:len(dice_list)]
roll_dice() #Find out how to delete what was already in that list and exchange it with the new numbers
dice_pics()
break
player_turn += 1
elif len(roll_again) == 2:
read_dice()
break
else:
print "That was not a yes or no answer! Try again!"


`





Error in odd spot

I'm trying to debug an error I'm getting:



"Catchable fatal error: Object of class mysqli_result could not be converted to string in /home/dsnook/public_html/SecretSanta/scramble.php on line 69" Line 69 is :$sql="UPDATE users SET GivingGroupNum='$idquery' WHERE Email='$giver'"; and line 38 is: $randnum=rand(0, ($count-1));



So I try to put a var_dump of the variable causing the problem. After I add the var_dump and run it again I get a timeout error for line 38.


This confuses the hell outa me since I change nothing anywhere near or having to do with line 38. Which is where I get the rand value. Below is my entire code for the page.



<?php
session_start();
require('./include/config.inc.php');
if(!isset($_COOKIE['email']))
include('./include/header.html');
else
include('./include/header2.html');


$gname=$_SESSION['gname'];
$orderarray=array();
$gmemberarray=array();
$sql="SELECT GroupMember FROM santagroup WHERE GroupName='$gname'";
$gmemberquery=mysqli_query($link, $sql);
echo "<br><br>";

foreach($gmemberquery as $person){
$gmemberarray[]=$person;
}

//*********************************************************************************************************

//***************************************************************************************************
$neworder=array();
$xcount=count($gmemberarray);
//fill the array with numbers and a setting of false *hasn't been used*
while($xcount>=1){
//$orderarray[($xcount-1)]=arrray();
$orderarray[($xcount-1)][0]=($xcount);
$orderarray[($xcount-1)][1]=false;
$xcount--;
//echo "<br>OrderArray: ".$orderarray[$xcount][0];
}
$xcount=count($gmemberarray);
$count=$xcount;
while($xcount>=1){
R:
$randnum=rand(0, ($count-1));

$rand2=$randnum+1;
if($orderarray[$randnum][1]==true) //If it's already been used get a different number
goto R; //otherwise try again
if($xcount!=($randnum+1)){ //if it's not equal to itself
$neworder[($xcount-1)]=($randnum+1);
$orderarray[$randnum][1]=true;
//echo "<br><br>Neworder ".$xcount.": ".$neworder[($xcount-1)];
}
else
goto R; //otherwise try again
$xcount--;

}
$xcount=count($gmemberarray);
while($xcount>=1){
//echo "<br>xcount: ".$xcount;
$person=$neworder[$xcount-1];
$giver1=$gmemberarray[$xcount-1];
$giver=reset($giver1);
$receiver=reset($gmemberarray[$person]);
//$receiver=reset($receiver1);
echo "<br>Groupname: ".$gname." GiverEmail: ".$giver." ReceiverEmail: ".$receiver;
$sql="INSERT INTO santaset (GroupName, GiverEmail, ReceiverEmail) VALUES ('$gname', '$giver', '$receiver')";
$insertquery=mysqli_query($link, $sql);

$sql="SELECT GroupSetID FROM santaset WHERE GiverEmail='$giver' AND ReceiverEmail='$receiver'";
$idquery=mysqli_query($link, $sql);

//var_dump($idquery);
$sql="UPDATE users SET GivingGroupNum='$idquery' WHERE Email='$giver'";
$setinfo=mysqli_query($link, $sql);
$sql="UPDATE users SET ReceivingGroupNum='$idquery' WHERE Email='$receiver'";
$setinfo=mysqli_query($link, $sql);
$xcount--;
}


?>




Random number generator, what's wrong with my approach/statistics? [JS]

First of all, what I want to know is if I am doing a systematic fault or am I messing up with the math, or do you have any ideas what could be wrong?


I was trying to write a little random number generator which numbers can be influenced / verified by the user (provably fair). The generated number is between 4096 and 65535. I simulated the function 100,000 times and get some strange statistics (Or am I thinking wrong??). Why is the chance that the number is under 8000 around ~50%. Shouldn't it be 50% around the middle of the number range (~30700)?


Here is the output of the simulation:



< 65536 : 100000 Times :100%
< 60000 : 91813 Times :91.813%
< 56000 : 86406 Times :86.406%
< 52000 : 81334 Times :81.334%
< 48000 : 76743 Times :76.743%
< 32768 : 62356 Times :62.356%
< 32000 : 61748 Times :61.748%
< 30719 : 60860 Times :60.86%
< 24000 : 56628 Times :56.628%
< 16000 : 52871 Times :52.871%
< 12000 : 51540 Times :51.54%
< 8000 : 50447 Times :50.447%
< 6000 : 36003 Times :36.003%
< 5096 : 21583 Times :21.583%
< 4608 : 11714 Times :11.714%
< 4250 : 3674 Times :3.674%
< 4100 : 100 Times :0.1%
< 4096 : 0 Times :0%


A little more details on the function I wrote:


I am generating two hashes. One is the userhash and the other is the serverhash. Both of these have a format like e.g.:



Server =3CDC3C8C97DEE62169B2C403BB2B6B501C1B0A0BD8015699B47DA67789C3F628
User =CF27CC73E33E0AC1DA5239DE8DAF94044D89B8636DA90F4CE510E652C8AC7F54


(The Userhash, is generated by a unique ID. The Serverhash is generated by taking a random number (standard function: math.random() )and a timestamp and then HMAC-SHA-512 them.)


To get my "random" number, i take both (user and server) hashes and add them as hexadecimal numbers (userhash + serverhash = result). Then I take the result and cut everything except the first 4 digits. (E.g result = CF27) After that, I convert it to decimal again.


The smallest number I can get from this should be in Hex 1000 (dec=4096), the biggest in Hex FFFF (dec=65535). That means my random number should be in a Range of 4096 - 65535.





What is the minimal non-zero value Math.random() can return in javascript

I know computers can't work with continuums. Math.random() javascript function returns a floating-point number between 0 (inclusively) and 1 (exclusively). I wonder what is the minimal non-zero number it can return. What "step" has this function?





How to shuffle a table of records in Delphi?

I have a table of questions each with a category and I want to query the database to first find questions of a specific category, and then retrieve a random question from that category. I was planning on doing this by shuffling all the records so they are in no particular order in the table, and then finding the first question that has the category I'm looking for. I know this will work, I just have no idea how to shuffle all the records in the table to get them in a random order. Anybody got any ideas on how to do this? Or an alternate method I could use? Thanks in advance. - George





PRGN in iOS KeyChain

My boss is asking me, which PRGN (Pseudo Random Generator Number) is using our iOS App for encrypting and decrypting data.


We are using the native KeyChain services for storing the data and I don't know what to answer since we are using the KeyChainItemWrapper for accessing the single items i.e. password, ports, etc. in our App and there is not too much reference about this.


I already debugged the app to see if I find something but I couldn't find something yet.


Any help would be appreciated, thanks





Java if Stuff in joptionpane

after a long time i came back to java and i try to write a short game about random numbers


The game should look like that:



  1. A Text box appears which asks for the difficulty (Done)

  2. A random number appears according to the difficulty (Stuck)

  3. A Textbox says "You Won, roll Again?" or "You Lose, roll Again" in both cases a loop is needed thats starts at 2. (no clue...)


Im currently stuck at 2. i can generate a random number but after i choose the difficulty nothing happens


here's the code :



package randomnumbergame;

import java.awt.Component;
import javax.swing.JOptionPane;

public class RandomNumberGame {

double n;
double e;
double h;
Component frame = null;
String answer = null;

public static void main(String[] args) {

String[] options = new String[] {"Easy", "Normal", "Hard"};
JOptionPane.showOptionDialog(null, "What Difficulty do you want ?", "Difficulty",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
Object answer = null; }
{
if ("Hard".equals(answer)) {
n = Math.random();
long n3 = Math.round(Math.random()*99999);
System.out.println (n3);
JOptionPane.showMessageDialog(frame, n3 ,"Your randomly generated Number is:" , JOptionPane.PLAIN_MESSAGE) ;

}else if ("Normal".equals(answer)) {
h = Math.random();
long n4 = Math.round(Math.random()*9999);
System.out.println (n4);
JOptionPane.showMessageDialog(frame, n4 ,"Your randomly generated Number is:" , JOptionPane.PLAIN_MESSAGE) ;

}else if ("Easy".equals(answer)) {
e = Math.random();
long e4 = Math.round(Math.random()*999);
System.out.println (e4);
JOptionPane.showMessageDialog(frame, e4 ,"Your randomly generated Number is:" , JOptionPane.PLAIN_MESSAGE) ;
}
}
}


what is wrong with it ? I looked trought several Questions here but i couldn't figure it out.





How can I randomly choose between multiple values, in an Array or not, each with it's own probability? in Java

I'm building a very simple text based Russian Roulette "game", and as I was making a 7 slot bulletChamber array, I kinda realized I'm only storing two values, which are either "there's a bullet" or "there's not a bullet".


and I'm just wondering if there's a way where I can randomly choose between two variables where each one has it's own probability ex 5/7 for no bullet and 2/7 for bullet?





How do I get a macro to select a random string

Ok, So at school, we have a maths test thing, called Rainbow Maths. As I have completed it; I was asked to make some more. How ever, every class needs different questions. I decided to make a Rainbow maths genarator so every class can run a macro; and create there times table/ maths questions.


Ok. So what I would like to do is make a random selector. I can have a list in my code and it can randomly select one of the x amount of items in the list. I have worked out how to do the rest; its just this random selector. I am using Excel 2010. Thanks -


Sodex





Choose a random letter and change it (JAVA)

Hello everyone im new to Java and i need help in my code



/**
* @(#)Changing.java
*
*
* @author
* @version 1.00 2015/2/27
*/

import java.util.Random;
public class Changing {

public static void main(String[] args) {
Random generator = new Random();
int num1;
String phrase = "This is a pencil";

int len = phrase.length();
num1 = generator.nextInt(len);
char c = phrase.charAt(num1, 'x');
String mut1 = phrase.replace(c, 'x');
System.out.println(mut1);



}


}


I need to make progrom to pick a random letter and change it to X


Thank you





searching for errors in my random number generator

i'm supposed to be creating a "game" that assigns a random number and allows user to guess the number, it is then supposed to display the amount of guesses made. just wondering what i'm missing since I cant currently get it to compile... wouldn't mind having my errors pointed out.



// ---------1---------2---------3---------4---------5---------6---------7
// 1234567890123456789012345678901234567890123456789012345678901234567890
import java.util.Scanner;
import java.util.Random;

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

int low = 1;
int max = 100;
int randomNumber = random.nextInt(max - low + 1) + low;
Random rand = new Random();
return randomNumber;

String guessCount = 1;
int userNumber;


Scanner keyboard = new Scanner(System.in);
userNumber = keyboard.nextInt();



while (userNumber != randomNumber)

if (userNumber > randomNumber)
{
System.out.println("Too high, try again.");
}
else (userNumber < randomNumber)
{
System.out.println("Too low, guess again.");
}

else (userNumber == randomNumber)
{
System.out.println("It took you " + "of guesses.");
}

}
}




C# Random Shuffle Game

I'm relatively new to C#, and am currently working on a shuffle game. The idea is that the numbers are shuffled when the user presses 'new game', and the user then has to get the tiles in descending order by swapping the empty block with any adjacent number.


The swapping of numbers works, but I can't manage to create a random shuffle without having either duplicate numbers or having a '0'.


Help?!





Difference between mt_rand() and rand()

What is the difference between using mt_rand($min, $max) and rand($min, $max) about the speed?





jeudi 26 février 2015

MySQL random record with RAND() and caluses

I have a database where I want to get a random draw from my entries. I can do that perfectly with:



$query = "SELECT * FROM mytable ORDER BY RAND()


The problem is that the database contains the entry order of horse jumpers in a competition and no jumper can jump consecutively. I have the following setup:


|jumper | horse | id|


| Pedro | gfs | 1 |


| Gustavo | psg | 2 |


| Breno | sdwed | 3 |


| bruno | sdsd | 4 |


| Carlos | powkd | 5 |


| Andrea | linda | 6 |


| Gustavo | handara | 7 |


I have to prevent the jumper Gustavo from being drawn consecutively to jump since he would have to change horses very fast. In fact, if he is drawn, he can only be drawn again after 3 other competitors. Would appreciate any ideas on how to do that.





random integers,removing elements

I have been trying several ways to remove some elements and can't seem to get it to work. The program needs the [] and ,. I have tried nums.remove(x).



import random
ROWS = 7
COLS = 1

def main():
nums = [0, 0, 0, 0, 0, 0, 0]
for r in range(ROWS):
nums[r] = random.randint(20, 80)
nums = [int(r) for r in nums]
print(nums)
print('The largest integer is',max(nums))
print('The lowest integer is',min(nums))
nums.sort()
print('The middle 5 sorted low to high',nums, )


main()


desired output:



79 30 39 33 41 43 53
The highest number is 79
The lowest number is 30
The middle 5 sorted high to low:
43 41 39 33 30


Current output:



[22, 35, 39, 24, 75, 24, 33]
The largest integer is 75
The lowest integer is 22
The middle 5 sorted low to high [22, 24, 24, 33, 35, 39, 75]




Shuffling two lists separately in Python

here is my code:



import random
from random import shuffle

a = ['a','b','c','d']
b = ['a','b','c','d']
c = ['w','x','y','z']
d = ['w','x','y','z']
indices = random.sample(range(len(a)), len(a))
a = map(a.__getitem__, indices)
b = map(b.__getitem__, indices)
shuffle(c)
shuffle(d)
print a,b,c,d


What this code does is it shuffles a and b in the same order, and shuffles c and d in their own order. What I am trying to do now is making two longer lists composed of a and c, and b and d, and put them in a randomized order. What I want though is for a and b stay the same order across lists. Is there any way to do this? Any help will be greatly appreciated. :)


Edit:


I would like the output to look something like this, where lists a&b correspond and c&d are just randomized independently.


['d','x','w','b','a','y','c','z']


['d','z','y','b','a','x','c','w']





Random Numbers based on the ANU Quantum Random Numbers Server

I have been asked to use the ANU Quantum Random Numbers Service to create random numbers and use Random.rand only as a fallback.



module QRandom

def next
RestClient.get('http://ift.tt/1AOlK3T'){ |response, request, result, &block|
case response.code
when 200
_json=JSON.parse(response)
if _json["success"]==true && _json["data"]
_json["data"].first || Random.rand(65535)
else
Random.rand(65535) #fallback
end
else
puts response #log problem
Random.rand(65535) #fallback
end
}
end

end


Their API service gives me a number between 0-65535. In order to create a random for a bigger set, like a random number between 0-99999, I have to do the following:



(QRandom.next.to_f*(99999.to_f/65535)).round


This strikes me as the wrong way of doing, since if I were to use a service (quantum or not) that creates numbers from 0-3 and transpose them into space of 0-9999 I have a choice of 4 numbers that I always get. How can I use the service that produces numbers between 0-65535 to create random numbers for a larger number set?





Creating random pairs from lists

I am trying to create a program that will print pairs of the elements in a list. I need to create a dictionary (that is empty at first) where I can store values, Loop through the list to make a pair and make sure there are no duplicates.


When I loop in the list, I need to get a random number and I can use it to remove an element. Remove the randomly selected element from the list using pop method, store the element to a variable, say element1. Repeat it to create element2.


Map the element1 to element2 by inserting the element1 as key to the pairs dictionary, and setting its value to element2, that is, if we call pairs[element1] later it should give us the value of element2.


Print the result using dictionary’s items() and keys() methods.


The catch is, I can't use the random module :(


Example is this:



list = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]


Sample run of the program, this creates 3 pairs because there are 6 elements in the list.



Pair 1: Mother and Aunt
Pair 2: Uncle and Sister
Pair 3: Brother and Father


Here is my program for now:



family = ["Mother", "Father", "Aunt", "Uncle", "Brother", "Sister" ]

for x in family:


pairs = {}


How can I improve/add to this code?





randomly splice values into array

I have an array "A" of scrambled, randomly generated ASCII characters... and a message "M". I want to insert the characters of message M into array A such that the order of M's characters are intact... but randomly distributed throughout array A.


Original array: zH$@%@$#@$@^^#@(%*$@^&@!$^%&


Sample output: zH$@%@^t$#@$@^^h#@(%*$@^&@i!$^%&s, etc...



var randomChars = [];
for(var i=33;i<127;++i) {
var letter = document.createElement('span');
letter.innerHTML = String.fromCharCode(i);
randomChars.push(letter);
}

var message = "this is a message";
for (var i = 0; i < message.split("").length; i++) {
var rand = Math.floor((Math.random() * randomChars.length) + 1);
var letters = document.createElement('span');
letters.innerHTML = message.split("")[i];
letters.setAttribute("hidden","");
randomChars.splice(rand, 0, letters);
}


Fiddle: http://ift.tt/1DelYzN





Generalized Extreme Value Distribution in C++ (GEV)

the GEV Distribution (http://ift.tt/1vBT3bk) has 3 parameters:


μ ∈ R — location,


σ > 0 — scale


ξ ∈ R — shape


However, the C++ 11 library only supports a extreme_value_distribution that only supports 2 parameters:


http://ift.tt/1FxegTM


So this implementation lacks the shape parameter (ξ). Is there a way to generate random numbers in C++ with a GEV distribution?





Generate random number uniformly over a range in Java

How do I generate a secure uniform random number within a range? The range could be between 0 to 100. (The upper bound is not a power of 2).


java.security.SecureRandom seems to provide the range 0..2^n.





Selecting random values in a set in mathematica

I have a set which has {0} and other 8 elements, total 9 elements. I want to choose random 3 value in this set and create a 3x1 column matrix. This will repeat all possible choices in the set. How can I do?





Oracle - generate unique random varchar values for each row of a table

I have to update a 'varchar2' column in a table with random values, but the catch is that the column is defined with 'unique' constraint, due to which I am getting the error saying that "Unique constraint violated".


Can somebody help please.


Thanks





Suffle element such that, no element should come at its original index

I have a list of Object elements



SourceList ResultList (Expected)

Obj_A Obj_F

Obj_B Obj_C

Obj_C Obj_G

Obj_D Obj_B

Obj_E Obj_A

Obj_F Obj_B

Obj_G Obj_E


Suffle elements in SourceList such that, no element should come at its original index(in SourceList ) in ResultList .


For Example, in SourceList C is at index 2, so it must not come at index 2 in ResultList


So far, i have looked into Dearrangement Wiki , but algo gives me possible arrangements and i need just one.





Random Number in a loop jquery

I would for every loop an other random number, but it does not want worke... I don't know why.



$(document).ready(function(){

setTimeout("execute()",5000);

})

function execute(){
for(i=0;i<5;i++){
var zWindow = $(window).height();
var yWindow = $(window).width();
var z=Math.floor((Math.random() * zWindow) + 1);
var y=Math.floor((Math.random() * yWindow) + 1);
$("#egg").css({
"top": z,
"left": y
});
$("#egg").delay(1000).fadeIn(10).delay(3000).fadeOut(100);
}

}




mercredi 25 février 2015

Dice roll not working C++ deafult_random_engine

For some reason I keep getting 6 every time. I know of another way to do a random dice roll, but I wanted to learn how to use the deafult_random_engine. thanks a bunch, Mike



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

using namespace std;

int main()
{
default_random_engine randomGenerator(time(0));
uniform_int_distribution<int> diceRoll(1, 6);

cout << "You rolled a " << diceRoll(randomGenerator) << endl;
}




Randomly generating 3 letter dictionary words to emulator using sprites

I have three sprites that I want to randomly generate, all come in the form of pngs. I'm not sure how to store CCSprites in an array to compile as a word. (i.e. [p.png,a.png,r.png] which prints out par).


I have this so far:



rocket[0] = [CCSprite spriteWithImageNamed:@"b.png"];
rocket[0].scale = (0.4f);
rocket[0].positionType = CCPositionTypeNormalized;
rocket[0].position = ccp(0.5f,0.2f);

rocket[1] = [CCSprite spriteWithImageNamed:@"a.png"];
rocket[1].scale = (.4f);
rocket[1].positionType = CCPositionTypeNormalized;
rocket[1].position = ccp(0.7f,0.2f);

rocket[2] = [CCSprite spriteWithImageNamed:@"g.png"];
rocket[2].scale = (.4f);
rocket[2].positionType = CCPositionTypeNormalized;
rocket[2].position = ccp(0.9f,0.2f);

[self addChild:rocket[0]];
[self addChild:rocket[1]];
[self addChild:rocket[2]];

[self intro];


I'm able to generate one single word, which is fixed, but I don't know to generate a random three letter word every time I start the emulator. Sorry if this is a noobish question. Any suggestions would help!





Write a program that prints a random number between 1 and N inclusive

The program needs to prompt the user to enter the value of N. (Hint: use rand () to generate the random number).





Random string split into characters

I have a procedure, that generates a random string without any delimiter. I store return value of this as a string, but I would like to split this text into characters and after that examine each characters. I try to use above code to split string into characters, but it gives Type mismatch error.



Sub gen()
Dim s As String
s = textgen(4000, 5)
Dim buff() As String
ReDim buff(Len(s) - 1)

For i = 1 To Len(s)
buff(i - 1) = Mid$(s, i, 1)
Next

MsgBox (buff) ' type mismatch
End Sub




Create a random matrix of matrixes from predefined values without repetition Octave

So I'm trying to create 2 randomized players to a noughts and crosses game. My ideia was to randomly create a vector(1:9) of diferent matrixes(1:2)(coordinates of the board) so that the first player would play in the first coordinate,etc but i soon found that I had no ideia in how to do that. I tried to do randperm to create a vector from 1 to 9 and then do a function that mapped each number to a coordinate but as i wanted to repeat it a lot of times it would be resource and time consuming. Any ideias?


Thanks in advance





Arbitrary 2D random number generation based on single seed

I am trying to fully cover a 2D space with random values based on a seed and starting at an origin, from which i want to be able to go into all directions without much computation.


The basic idea is that i need a function float rnd_2d(int x, int y, uint64_t seed); that generates a random number based on the inputs in O(1).


My goal is to create noise procedurally in all directions.





What is the average minimum distance between two Sobol points?

Having the first n points of a d-dimensional Sobol sequence, what is the average Euclidean distance from one arbitrarily point to its nearest neighbour?





random dice generator C++

How can i modify my program so it has a single parameter representing the number of dice to be rolled instead of automatically rolling two dice? This is my code so far.



#include <cstdlib>
#include <iostream>

using namespace std;

int dice_score()
{

srand(time(NULL));
int roll1 = rand() % 6 + 1;
int roll2 = rand() % 6 + 1;
return roll1;
return roll2;

}




Generate random useless (lorem ipsum) cpp code that compiles correctly?

I need random c++ code to test a tool that fixes minor issues detected with cpp lint.


Basically, the idea is:



  1. Generate random code.

  2. Check with cpplint

  3. Add errors randomly.

  4. Check with cpplint.

  5. Run fixer.

  6. Check with cpplint.

  7. Compare results between runs #1, #2 & #3





Random statement asking same statement?? Python

I have been trying to make a mathimatical quiz that asks a random question then asks another random question for a range of 10 times, what my problem is is that it will ask a random question then the same question again and again and again etc.



import random

opList = ["+", "*", "-"]
numberofQuestions = 10
num1 = random.randint(0, 10)
num2 = random.randint(0, 10)
ops = random.choice(opList)
question = "%d %s %d" % (num1, ops, num2)
answer = eval(question)
totalScore = 0


childName = input("Enter your name: ")
print("Thank you for signing up for Arithmetic Quiz " + childName)
for i in range(numberofQuestions):
reply = int(input("What is " + question + " ? "))
if reply == answer:
print("Correct!!")
totalScore += 1
else:
print("Incorrect!!")




Create table and change background color using JavaScript

My task is this: I want to create a page with the button and a horizontal table of results from 1 to 20.


When you click a button, you get a random number, display it on a page and the cell with this number should change color to green. If the number appears for the second time, make it grey.


If the cell is already grey, nothing happens. That's it this is my code plth helpm me if you can. thanks





Random number generator android

ActivityMain.java



package com.abhinav.random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

public int count=0;
public int rand_num;
public int n;
EditText edt_rand;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rand_num=(int)(Math.random()*100);
edt_rand=(EditText)findViewById(R.id.edt_rand);
n = Integer.parseInt(edt_rand.toString());
}

public void onclick(View v){
if(count!=5){
if(n>rand_num){
Toast toast=Toast.makeText(this,"Your number is greater", Toast.LENGTH_SHORT);
toast.show();
}
if(n<rand_num){
Toast toast=Toast.makeText(this,"Your number is greater", Toast.LENGTH_SHORT);
toast.show();
}
else{
new AlertDialog.Builder(this)
.setTitle("Task complete")
.setMessage("You Win")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
})
.show();
}
}
else{
new AlertDialog.Builder(this)
.setTitle("No Chances Left")
.setMessage("You Lose")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
})
.show();
}

}

}


main_activity.xml



enter code here
<EditText
android:id="@+id/edt_rand"
android:hint="@string/number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"
></EditText>

<Button
android:id="@+id/btn_rand"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/edt_rand"
android:layout_below="@+id/edt_rand"
android:layout_marginTop="23dp"
android:text="@string/click"
android:onClick="onclick"/>


Whats wrong with the above code?





output random words with ascii in PHP

I have to write a program that will output random words with random letters, in fact I wrote this:



$array=array();
$n=10;

for ($i=0;$i<$n;$i++){
$l=rand(4,10);
?><br><?

for ($j=0;$j<$l;$j++){
$cas=rand(65,90);
$array[$j]=$cas;


if($j>1){


Now, I have to check that there won't be 3 consonants and 3 vocals near to each others. Have I to write IF or WHILE? like



if(($array[$j-1]=65 || $array[$j-1]=69...) && ($array[$j-2]==65...)
if(($array[$j-1]=66 || $array[$j-1]=67)&&($array[$j-2]=66))


or



while(($array[$j-1]==65) && ($array[$j-2]=65)
while(($array[$j-1]==66) && ($array[$j-2]=66)




mardi 24 février 2015

determinism for the __gnu_parallel::random_shuffle generator

I was hoping to use the parallel gnu extensions to accelerate a shuffle of an array, the shuffled array would then be used as a workload for an experiment involving sorting. My two goals are speed in generating the workload, and reproducibility of the experiment's results. A description of these gnu extensions is provided here. I ended up confused about the interface:


From what I read, either I pass my own RNG, like the standard library allows, but then I assume I need to worry about thread safety. The documentation here (std::random_shuffle in cppreference) doesn't say much about thread safety requirements on the generator, neither does the gnu link above. So, I assume the worst.


Or, If I don't pass my own RNG, then I assume the library takes care of it. I assume they do consider the multi-threading issues of the RNG in the implementation (though I couldn't find documentation affirming this either). But this leaves me with the problem: I wanted to control the seed to make sure the experiment I am doing is repeatable. I found no documentation about controlling the seed of their default generator.


Both approaches have clear shortcomings.


A third option is to pass in a thread safe generator, for example, by using a lock on it. This seems silly, considering i'm trying to parallelize it. It may still be better than purely sequential shuffle. I haven't tried.


Another option would be one based on thread local state, but I'm starting to get annoyed at having to think so much about how to use this library function.


Note: generating the workload in advance and remembering it is not an option, as I want to generate multiple GBs of data.


What would you do? Do you know of some other documentation I missed?





Create matrix of random integers in range by step using Python

I would like to create a matrix (rows/columns determined by user) of random integers in a range by step. I have been trying to get step into random.random_integers but it has not been working for me. Example output:


Size 3x4, range 22-37, step 2:

[[26 22 32 28]

[24 30 26 22]

[36 34 22 36]]





Java hashmap choose random but by chance

I have 2 hashmaps.



rewards<integer,integer>
chances<integer,integer>


rewards is like : 57,500000000;9210,2500;9209,50;6660,1;6 (id-count)


chances is like : 57,95;9210,70;9209,65;6660,15; (id-chance %) id is the same both maps.


So i want to choose one id but by these chances so low chances will have lower chance to be selected. i am fully confused. thanks you! (but i need to chooce 1 id , not zero not more than 1)





cannot instantiate the type random [duplicate]


This question already has an answer here:




Im trying to create a random character generator but I keep getting the error "Cannot instantiate the type Random" why is this?


Here is the code:



private static char randomChar(){
Random rand = new Random(); // This is obviously the error
char c = (char)((rand.nextInt()*26)+'a');

return c;
}




What is a frequency count in java [on hold]

I have an assignment that asks me to create a frequency count--i.e. how many integers are equal to 1-- after filling an array with 1000 integers. Can someone explain or give me a tutorial as to what a frequency count is? Thank you for all your help!!





How to get the indices for randomly selected rows in a list (Python)

Okay, I don't know if I phrased it badly or something, but I can't seem to find anything similar here for my problem.


So I have a 2D list, each row representing a case and each column representing a feature (for machine learning). In addition, I have a separated list (column) as labels.


I want to randomly select the rows from the 2D list to train a classifier while using the rest to test for accuracy. Thus I want to be able to know all the indices of rows I used for training to avoid repeats.


I think there are 2 parts of the question: 1) how to randomly select 2) how to get indices


again I have no idea why I can't find good info here by searching (maybe I just suck)


Sorry I'm still new to the community so I might have made a lot of format mistake. If you have any suggestion, please let me know.


Here's the part of code I'm using to get the 2D list



#273 = number of cases
feature_list=[[0]*len(mega_list)]*273
#create counters to use for index later
link_count=0
feature_count=0
#print len(mega_list)
for link in url_list[:-1]:

#setup the url
samp_url='http://ift.tt/1zEgj4L'+link
samp_url = "%20".join( samp_url.split() )

#soup it for keywords
samp_soup=BeautifulSoup(urllib2.urlopen(samp_url).read())
keywords=samp_soup.find('meta')['content']
keywords=keywords.split(',')

for keys in keywords:
#print 'megalist: '+ str(mega_list.index(keys))
if keys in mega_list:
feature_list[link_count][mega_list.index(keys)]=1


mega_list: a list with all keywords


feature_list: the 2D list, with any word in mega_list, that specific cell is set to 1, otherwise 0





I have this sample code and it throws an error:



std::random_device rd; // only used once to initialise engine
std::mt19937 rng(rd); // random-number engine used
std::uniform_int_distribution<int> uni(0, 7); // guaranteed unbiased

int random_integer = uni(rng);


The error is:



Error 1 error C2039: 'generate' : is not a member of 'std::random_device' c:\program files (x86)\microsoft visual studio 12.0\vc\include\random 1618 1 Life



Can somone explain me please, why is this happening? It seems to be an error in the header file and not in my code.


How can I fix it?


Thank you.





Python Random Function without using random module

I need to write the function -



random_number(minimum,maximum)


Without using the random module and I did this:



import time

def random_number(minimum,maximum):
now = str(time.clock())
rnd = float(now[::-1][:3:])/1000
return minimum + rnd*(maximum-minimum)


I am not sure this is fine.. is there a known way to do it with the time?





Program that creates a random string of characters and acts as a password generator

I'm writing this program that asks the user for password length and then creates a random string of characters that length using characters ! to ~. The only part that I am stuck on is that it is creating multiple strings where I only need one. Any input would be appreciated.



import java.util.*;
public class pw
{
public static void main(String[]arg)
{
Scanner in = new Scanner(System.in);
Random gen = new Random();
System.out.println("Enter password length: ");
int length = in.nextInt();

for(int i=1; i < length; i++)
{
int slength = length+gen.nextInt(length - 1);
StringBuilder s = new StringBuilder(slength);

while(s.length() <= length)
{
s.append((char)(33+gen.nextInt(126)));
}
System.out.println(s.toString());
}
}
}




List of Non-Repeating Ints in Java? Assignment

I'm trying to create a list of 20 integers between 0 and 26 (so in the 1-25 range) that does not repeat as a part of an assignment. I thought I had it figured out, but the program keeps looping over and over without ever ending. Can anyone help me out?



import java.util.Random;

public class prog433a
{
public static void main(String args[])
{
Random r = new Random();

int[] list = new int[20];

for (int k = 0; k < list.length; k++)
{
boolean notADupe = false;

while (notADupe == false)
{
list[k] = r.nextInt(25) + 1;
for (int j = 0; j < list.length; j++)
{
if (list[j] == list [k] && j != k)
{
notADupe = true;
}
else
{
notADupe = false;
break;
}

}

System.out.println(list[k]);
}
}
}
}


EDIT: This is different from the other question because I am trying to figure out how to check for uniqueness using the methods that I am allowed to use in my assignment (essentially, the ones I'm already using in the code).





Selecting a Random Card in Java

I'm new to java programming and have started creating a poker game. So far have have the cards and deck created but I want to be able to select a random card but I don't want to shuffle the deck.


This is my code so far:



import java.util.ArrayList;
import java.util.List;


public class PockerMain {

public PockerMain() {
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {
List<PokerCard> deck = cardDeck();
for (int i = 0; i < deck.size(); i ++)
{
PokerCard card = deck.get(i);
System.out.println(card);
}

}
private static PokerCard createCard (short suit, short rank)
{
PokerCard card = new PokerCard (suit, rank);
return card;
}
private static List<PokerCard> cardDeck ()
{
List<PokerCard> deck = new ArrayList<PokerCard> ();
for (int i = 0; i < 4; i ++)
{
for (int j = 0; j < 13; j ++)
{
PokerCard card = createCard ((short)i, (short)j);
deck.add(card);
}

}
return deck;
}
}




Visual Studio 2013 will insert random code into CSS when click RUN in browser... Why?

I have annoying issue with Visual Studio 2013.


Very often VS will replace some one line of code (ASP.NET C#) with other code apparently copied from other place...


For example


I have .test{ float: right; }


After I click Run in Firefox, I will find .test{ float:right; rss-icon:hover { background-color: #209b60;


Interesting is this isn’t happening every time, it isn’t clipboard content and I do not have anything highlighted. Only solution to protect content of CSS file, is to close that file…


Any idea why my VS is doing this ?? Very annoying as it’s destroys my code every few runs and sometimes it is difficult to find what was replaced and where (it happens only to opened files)





How do you randomly select a non-blank numerical value from a row (Excel)

Does anybody know the excel formula how to randomly select a non-blank value in a row which has blank cells and cells with numbers?


Here is an example table to show:



1,1 2,2 3,3 4,4 5,5


1,1 0 0 0


2,2 0 0


3,3 0 0


What I please need is for the excel formula to be able to randomly select one of the 0's at the 1,1 row (possible places are at columns 1,1 2,2 and 5,5), and then for example I would get back the 0 at the 2,2 column.


If possible, can you also recommend how to get excel to repeat (recursion) the same formula to now randomly choose one of the 0's at row 2,2, as that was the column it randomly chose the 0 from in the previous step.





Is it possible to add weight to images in a generator?

Firstly, I would like to thank you for taking time out of your day for clicking on this post. :)


Ok, so I am bored and wish to make a random image generator (which is working fine), however, I was wondering is there a way to add weight to certain images which won't appear as much as others?


I have attached the code below:



<script language="JavaScript">

function random_imglink(){
var myimages=new Array()

myimages[1]="Blue_Car.png"
myimages[2]="Red_Car.png"
myimages[3]="White_Car.png"
myimages[4]="Black_Car.png"


var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()


function confirmRefresh() {
var okToRefresh = confirm("Do you really want to refresh the page?");
if (okToRefresh)
{
setTimeout("location.reload(true);",10);
}
}

</script>
<input type="button" value="Generate a new player" onClick="document.location.reload(true)">


</script>
</a></p>


I do have a SMALL amount of knowledge regarding JavaScript, however, I'm no pro.


I would like to thank everyone who helps me.


Also may I add, there will be an incentive for someone who can help me get this done! Thank you!





is it safe to use rand for generating confirmation code ? php

when the user want to reset his password , I send to his email a 6 digits code, then I check if the user enter the matched code !


I am generating the code using rand function :



$code = rand ( 100000, 999999 );


is it safe to do that ?





Randomizing script for HexChat IRC Client, in Python or Perl

I have a hunch that the answer to this is embarassingly easy, but nonetheless I can't figure it out (the fact that I don't know any of these languages at all might be the case). What I need is a script which would work this way:



  1. First, you type command like !random and a number from the range 1-100 (the number would mean the probability of success in %) [like this: !random 78]

  2. Then, it would - basing on given probability - choose whether you succeeded or not [for example, with !random 78, there is 78% probability that the outcome would be "Success"]

  3. Then, it would show on a channel a public message what the outcome is ("Success" or "Failure")


I need this one for online text RPG sessions. Also sorry for my bad English.





NSubstitute mock extension method

I want to do mock extension method, but it does not work. How can this be done?



public static class RandomExtensions
{
public static IEnumerable<int> NextInt32s(this System.Random random, int neededValuesNumber, int minInclusive, int maxExclusive){...}
}
....
[Fact]
public void Select()
{
var randomizer = Substitute.For<DefaultRandom>();
randomizer.NextInt32s(3, 1, 10).Returns(new int[] { 1, 2, 3 });
}




Output random words

I have to write a program that will output random words(with random letters) and that will not have 3 vocals or consonants near, so i wrote:


$array=array();

$n=10;



for ($i=0;$i<$n;$i++){
$l=rand(4,10); // $l=word length
?><br><?


for ($j=0;$j<$l;$j++){

$cas=rand(65,90); //$cas=random letters
$array[$j]=$cas;


if($j>1){
if (($array[$j-1]==65 || $array[$j-1]==69 || $array[$j-1]==73 || $array[$j-1]==79 || $array[$j-1]==85) ^ ($array[$j-2]==65|| $array[$j-2]==69 || $array[$j-2]==73 || $array[$j-2]==79 || $array[$j-2]==85)){ //will do XOR '^'


$cas=rand(65,90);
$array[$j]=$cas;

}
}

$m=chr($array[$j]);
echo $m;
}
}


?>


don't know why but it seems that IF doesn't work, 'cause when I output it'll print also words with 3 or more consonants or vocal. Can anybody help me? thanks :D and sorry for bad english :P





lundi 23 février 2015

Xor of random numbers or UUID

I'm developing data structure where each entity should have unique identifier. I'm thinking about using 64 bit random numbers or Boost UUID http://ift.tt/1zbJprd for this.


If I do copying of some entities I need to generate for copies new UUIDs (because otherwise some entities will have duplicate UUIDs). But updating UUIDs requires updating links between entities. So I'm thinking about uniform change to all UUID's: before copying of entities I will generate some LoadingUUID and update all UUIDs using formula:



NewEntityID = EntityID xor LoadingUUID


The question is: will xor of two UUIDs substantially increase probability of clashing UUIDs?





How to generate random name of person using php?

Thanks anyone in advance for answering/attempting to answer my question.


I'm currently using a php script to generate random string, but now I'd like to generate random name of a person instead of generating just a random string. My old code looked something like this:



<?php
function RandomString($length) {
$keys = array_merge(range('a', 'z'), range('A', 'Z'));
for($i=0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}

print RandomString(6);
?>


Thanks Again in Advance.





How to make teams using math.random() in javascript?

I want to make a Javascript function which will take 3 inputs: Starting Number, Ending Number and Number of Teams.


When the user enters the data and hits enter, A HTML table will be displayed which will make teams based on Size Of Team between the Beginning and End numbers.



var Beg; //input for starting number
Var End; // input for ending number
var no_of_teams; //input for number of teams


Math.floor((Math.random() * End) + Beg);


What code should I write to make a HTML table out of the the math.random numbers.


Eg:


User enters


Beg : 43


End : 63


no_of_teams : 5


The Output will be :


Team 1: 54,52,63,43


Team 2: 58,61,49,60


Team 3: 51,52,53,55


Team 4: 49,59,47,44


Team 5: 56,57,45,46





Snake game - how to calculate the next apple position

I'm implementing a Snake game in javascript for fun, I have successfully implemented the snake, its movements and the snake-growth thing as it eats an apple.


To calculate the apple position I'm currently following these steps:



  1. create a new apple object

  2. create random coordinates (X and Y, between game-container boundaries) for the apple

  3. check if the coordinates of the apple are equal to one of the snake-blocks coordinates

  4. if step #3 is TRUE, recalculate the position of the apple, else draw the apple in the game-container


Unfortunately I found out that this algorithm is very weak.. let's say I have a 10 x 10 game container, the red square is the apple, the green square is my snake head (initial game state)


enter image description here


as the game progresses the snake eats more and more apples, increasing its length and leaving less and less empty cells to place an apple


enter image description here


Now suppose that the snake reaches a length equals to 99 while eating an apple. This means that there's only one square left to place the next apple. My algorithm (this is the worst case obviously) could take forever in order to randomize the correct value, as it discards any randomized position that it's already taken by the snake's head or tail, not caring at all to randomize the new position in a range of "empty cells" only but instead randomizing on the whole 10 x 10 game canvas.


How should I proceed to solve my busillis? Can you give me any advice on a good algorithm that I can use?


Thank you





Objective-C random alphabet no repeat

i made a random for A-Z. The random letter is shown in a label. everything works fine. But the letter should not repeat till every letter from A-Z is called. I´am new in xcode an need a litte help. heres my code in the .m file.



NSString *letters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-(NSString *) randomStringWithLength:(int) len {

NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

for (int i=26; i<len; i++) {
[randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]]; buchstabeAusgabe.text = randomString;
}

return randomString;}



-(void)neuerGenerator {

int text = rand() %26;

switch (text) {
case 0:
buchstabeAusgabe.text =@"A";
break;
case 1:
buchstabeAusgabe.text =@"B";
break;
case 2:
buchstabeAusgabe.text =@"C";
break;
case 3:
buchstabeAusgabe.text =@"D";
break;
case 4:
buchstabeAusgabe.text =@"E";
break;
case 5:
buchstabeAusgabe.text =@"F";
break;
case 6:
buchstabeAusgabe.text =@"G";
break;
case 7:
buchstabeAusgabe.text =@"H";
break;
case 8:
buchstabeAusgabe.text =@"I";
break;
case 9:
buchstabeAusgabe.text =@"J";
break;
case 10:
buchstabeAusgabe.text =@"K";
break;
case 11:
buchstabeAusgabe.text =@"L";
break;
case 12:
buchstabeAusgabe.text =@"M";
break;
case 13:
buchstabeAusgabe.text =@"N";
break;
case 14:
buchstabeAusgabe.text =@"O";
break;
case 15:
buchstabeAusgabe.text =@"P";
break;
case 16:
buchstabeAusgabe.text =@"Q";
break;
case 17:
buchstabeAusgabe.text =@"R";
break;
case 18:
buchstabeAusgabe.text =@"S";
break;
case 19:
buchstabeAusgabe.text =@"T";
break;
case 20:
buchstabeAusgabe.text =@"U";
break;
case 21:
buchstabeAusgabe.text =@"V";
break;
case 22:
buchstabeAusgabe.text =@"W";
break;
case 23:
buchstabeAusgabe.text =@"X";
break;
case 24:
buchstabeAusgabe.text =@"Y";
break;
case 25:
buchstabeAusgabe.text =@"Z";
break;

default:
break;
}}




Generate random number between -1 and 1?

So I found this useful website with a lot of code and explanation to perlin and simplex noise. However, the code is written in a different language. I was able to rewrite most of it for java, however there is one function that 1. I don't understand, and 2. I don't know how to write it in java. The code is:



function IntNoise(32-bit integer: x)

x = (x<<13) ^ x;
return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);

end IntNoise function


Again, I don't know what language it is written in. However, the author states that the function returns a random number between -1 and 1. Can someone explain what exactly the & symbol does? And why there are a bunch of seemingly random numbers? And is there a simple way to convert this to java?





Random alphabetic string in java

I want to generate random string contains only alphabets in java. the string generated is used as a key in encryption.





Java - Generate 9 random numbers without duplicates [duplicate]


This question already has an answer here:




How can I generate 9 random numbers without any duplicates and not too much code.





Code not working (Randomize Array)

Hey i wanted to ask for help since i dont know why my code is not working. Im new to android programming and wanted to ask for help.



public class MotivationalQuotesMenu extends Activity {

int [] images = {R.drawable.mem1, R.drawable.mem2, R.drawable.mem3};

public static int[] RandomizeArray(int[] images){
Random rgen = new Random(); // Random number generator

for (int i=0; i<images.length; i++) {
int randomPosition = rgen.nextInt(images.length);
int temp = images[i];
images[i] = images[randomPosition];
images[randomPosition] = temp;
}

return images;
}


And then...



class loladapter extends ArrayAdapter<String> {
Context context;
//class that shows a specific row in listview

private loladapter(Context c, String[] titles, int imgs[]) {


super(c, R.layout.singlerow, R.id.textView, titles);
this.context = c;
images = imgs;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.singlerow, parent, false);
ImageView myimageie = (ImageView) row.findViewById(R.id.imageView);

myimageie.setImageResource(images[position]);
return row;

}
}


Random images wont show.. just the same array with the same order