473,386 Members | 1,679 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Randomly selecting an element in an array that has not been selected before..

Hi,
Im having problems in randomly selecting an element in an array that
has not been selected before.. in other words, I have an array of
answers to questions, then I want to select 5, with one of them being
the correct answer to the question, and the others not..
Here is my code.. (I already have the correct answer at array position
[0])

for($i=1;$i<=4;$i++)
{
//choose a random number in array range
$phraseArr_random_answer=rand(1,$phraseArr_size);
// check to see if random selection has not already been chosen

for($j=0;$j<=$i;$j++)
{
//check to see if element has already been chosen (j is current
array)
echo">> ".$answerArr[$j][2] ."<< >>".
$phraseArr[$phraseArr_random_answer][2]."<< <br />";
if(strcmp($answerArr[$j][2],$phraseArr[$phraseArr_random_answer][2]))
{
$alreadyUsed="FALSE";
$i--;
//document.writeln("choices[j] = " + choices[j] + " and i = " + i
// + " and viet[random_choice] = " + viet[random_choice] + "<br
/>");
//break;
echo"test";
}
else
{
$alreadyUsed="TRUE";/*
}
}
//add a random selection from phraseArr into each element of
answerArr
if ($alreadyUsed=="TRUE")
{
$answerArr[$j][2]=$phraseArr[$phraseArr_random_answer][2];
}

$answerArr[$i]=$phraseArr[$phraseArr_random_answer][2];
echo $answerArr[$i]." - ";
}

Thanks to anyone who can tell me the problem with this..
Jul 17 '05 #1
5 3100
On 28 Jun 2004 06:39:13 -0700, ad*******@yahoo.com (Joe Six-Pack)
wrote:
Im having problems in randomly selecting an element in an array that
has not been selected before.. in other words, I have an array of
answers to questions, then I want to select 5, with one of them being
the correct answer to the question, and the others not..
Here is my code.. (I already have the correct answer at array position
[0])


why not use the shuffle-function to mix up the array?

Here is an example:

<?
$questions = array(
array("correct answer", 1),
array("false1", 0),
array("false2", 0),
array("false3", 0),
array("false4", 0)
);

srand ((float)microtime()*1000000);
shuffle($questions);

echo "<pre>";
print_r($questions);
echo "</pre>";

$chosen = $questions[3];
echo "you chose: $chosen[0]<br>";

if ($chosen[1] == 1)
{
echo "correct answer<br>";
} else {
echo "wrong answer<br>";
}
Regards

Marian

--
Tipps und Tricks zu PHP, Coaching und Projektbetreuung
http://www.heddesheimer.de/coaching/
Jul 17 '05 #2
"Marian Heddesheimer" <26*************@spamgourmet.com> wrote in message
news:6o********************************@4ax.com...
On 28 Jun 2004 06:39:13 -0700, ad*******@yahoo.com (Joe Six-Pack)
wrote:
Im having problems in randomly selecting an element in an array that
has not been selected before.. in other words, I have an array of
answers to questions, then I want to select 5, with one of them being
the correct answer to the question, and the others not..
Here is my code.. (I already have the correct answer at array position
[0])


why not use the shuffle-function to mix up the array?


Or use array_rand() to random pick out an element. Then use array_splice()
to remove that has been selected.
Jul 17 '05 #3
On Mon, 28 Jun 2004 06:39:13 -0700, Joe Six-Pack wrote:
Hi,
Im having problems in randomly selecting an element in an array that has
not been selected before.. in other words, I have an array of answers to
questions, then I want to select 5, with one of them being the correct
answer to the question, and the others not.. Here is my code.. (I already
have the correct answer at array position [0])


The algorithm is as follows:

$n = size( $array );
while ( $n > 0 )
{
// generate a random number from 0 to $n
$i = rand(0, $n );
$temp = $array[$i];
$array[$i] = $array[$n - 1];
$array[$n - 1] = $temp;
$n--;
}

Of course, I'm not sure that this loop runs any faster than shuffle.

As always, make sure your script seeds the random number generator before
calling rand or shuffle.

What you have to decide is what to shuffle - the array of possible answers
or an array of indexes into the array of possible answers (in this case,
use array_rand, passing in size($array) as the second parameter).

HTH,
La'ie Techie

Jul 17 '05 #4
ad*******@yahoo.com (Joe Six-Pack) wrote in message
news:<48**************************@posting.google. com>...

Im having problems in randomly selecting an element in an array that
has not been selected before..


Randomness has NOTHING to do with whether an element has been selected
before. If your array has n elements, there is a (1/(n*n)) chance that
the next choice will be the same as last.

Cheers,
NC
Jul 17 '05 #5
Nikolai Chuvakhin wrote:
ad*******@yahoo.com (Joe Six-Pack) wrote in message
news:<48**************************@posting.google. com>...

Im having problems in randomly selecting an element in an array that
has not been selected before..
Randomness has NOTHING to do with whether an element has been selected
before. If your array has n elements, there is a (1/(n*n)) chance that
the next choice will be the same as last.


I think you parsed his request wrong, Nikolai: :-)
problem: randomly selecting (an element in an array
that has not been selected before).


I.e., sampling without replacement.

Chung's suggestion is a good --and might be the fastest; I certainly
haven't found a faster-- way to do that.

Margaret
--
(To mail me, please change .not.invalid to .net, first.
Apologies for the inconvenience.)
Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Bob Bedford | last post by:
I've a site where companies add their article. I'de like to provide a "lasts articles" table. By this, I'll show last articles inserted. But I won't always the same articles at any refresh....
3
by: Pawe | last post by:
I'm desinging a graphical interface and I frequently take advantage of the double click event. Unfortunately in most browsers double clicking also involves selecting and I would like to avoid that...
3
by: james.dixon | last post by:
Hi I was wondering if anyone else had had this problem before (can't find anything on the web about it). I have three select elements (list boxes - from here on I'll refer to them as 'the...
4
by: James | last post by:
Just learning C#. What's the easiest way to assign numbers 1-10 randomly to an array? Basically I just want to take the numbers 1-10 and arrange them randomly in slots 0-9 of an array. Thanks
6
by: Fred Morrison | last post by:
Do you know of a way to load a hash table with random key/value pairs (e.g., 2/"Two",1/"One",3/"Three") and then iterate through the entries in "sorted" (key sequence) order...
27
by: one man army | last post by:
Hi All- I am new to PHP. I found FAQTS and the php manual. I am trying this sequence, but getting 'no zip string found:'... PHP Version 4.4.0 $doc = new DomDocument; $res =...
2
by: areef.islam | last post by:
Hi, I am kinda new to javascript and I am having this problem with selecting multiple options from a select tag. Hope someone can help me out here. here is my code...
9
by: Generic Usenet Account | last post by:
I had a need to randomly select an element from an STL collection. It does not appear that this functionality is provided out-of-the-box with STL. Here is my crude implementation. I am using...
2
dlite922
by: dlite922 | last post by:
Before traversing my code, here's what my goal is and what this function does: I have a table of fields that dynamically grows as the user enters information. A minimum of 3 rows must always...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.