473,786 Members | 2,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_rand om_answer=rand( 1,$phraseArr_si ze);
// 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">> ".$answerAr r[$j][2] ."<< >>".
$phraseArr[$phraseArr_rand om_answer][2]."<< <br />";
if(strcmp($answ erArr[$j][2],$phraseArr[$phraseArr_rand om_answer][2]))
{
$alreadyUsed="F ALSE";
$i--;
//document.writel n("choices[j] = " + choices[j] + " and i = " + i
// + " and viet[random_choice] = " + viet[random_choice] + "<br
/>");
//break;
echo"test";
}
else
{
$alreadyUsed="T RUE";/*
}
}
//add a random selection from phraseArr into each element of
answerArr
if ($alreadyUsed== "TRUE")
{
$answerArr[$j][2]=$phraseArr[$phraseArr_rand om_answer][2];
}

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

Thanks to anyone who can tell me the problem with this..
Jul 17 '05 #1
5 3125
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)microti me()*1000000);
shuffle($questi ons);

echo "<pre>";
print_r($questi ons);
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 Projektbetreuun g
http://www.heddesheimer.de/coaching/
Jul 17 '05 #2
"Marian Heddesheimer" <26************ *@spamgourmet.c om> wrote in message
news:6o******** *************** *********@4ax.c om...
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.go ogle.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*******@yaho o.com (Joe Six-Pack) wrote in message
news:<48******* *************** ****@posting.go ogle.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
2017
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. Question 1: how to get a "random" selection from the database, giving more priority to the last inserted (the ones with higher articleID) Question 2: I'd like to provide one article by client. I won't show 3 articles from the same client only because...
3
2465
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 since whatever is selected has dark blue background and white letters what spoils the whole visual effect.... Any way I can block it por avoid it?
3
2415
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 list boxes'). Users can add and remove items from the list boxes. When the users are adding and removing items, the list boxes are single
4
2719
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
7832
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 (1/"One",2/"Two",3/"Three")? The following just returns them in the order they were loaded: Dim hshPrimaryKeyInfo as New Hashtable <snip code to Add entries to hash table> For Each hshEntry As DictionaryEntry In hshPrimaryKeyInfo
27
4623
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 = $doc->loadHTMLFile("./aBasicSearchResult.html"); if ( $res == true ) { $zip = $doc->getElementById('zipRaw_id')->value; if ( 0 != $zip ) {
2
3663
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 /////////////////////////////////////////////////////////////////////////////////////// <form action="whatever.php" method="post"> <select name="zip_code" onchange="makeRequest('getCity.php?state='+this.form.zip_code.options.value)" multiple="multiple" size="20">
9
3179
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 advance and distance in my approach. Is distance guaranteed to return an integral value? If not, can anyone suggest improvements: --Song ///// Header File //////
2
3418
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 exist. (read the psedo code and comment if you need to know what it does) disregard the debugging , commented alerts. What i'm trying to do is without passing the ID or field that called this function, set the focus to the next element. what's...
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8989
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5397
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4066
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3669
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.