Random Array Selection

without repeating selections

Page 1 of 1

3 Replies - 1752 Views - Last Post: 05 September 2010 - 04:02 PM

#1 Fuingurth   User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 118
  • Joined: 13-August 09

Random Array Selection

Posted 30 August 2010 - 09:29 PM

Hello all,

So, I am attempting to select a random entry from an array, and then make it so that particular entry will not be selected again until every entry has been selected.
Basically, I don't want to see any of the same entries, until all of the entries in the array have been selected.

So if this were my array....
keywords = 
[
 "ppc", 
 "games", 
 "advertise", 
 "meta", 
 "home", 
 "gaming", 
 "welcome"
]
var keyword = keywords[Math.floor(Math.random()*keywords.length)]

document.write(keyword);



I would not want to see an output of
meta, advertise, home, meta, gaming, welcome, ppc, welcome


since meta was selected a second time before everything had been selected once.


I would like to see something more like
meta, advertise, gaming,ppc, welcome, home, games, advertise, ppc,

since this did not select any entry multiple times before every entry had been randomly selected.( the second loop started at the second "advertise" in case you didn't catch the differences.


But as you can see from the code that I have posted above, I do not know how to do this. I have seen examples where the entries that were randomly selected, were actually deleted from the array entirely but this is not what I want to do. I just want every entry to be selected once, and then for the process to be restarted.
As always, thanks for all your help guys!

Is This A Good Question/Topic? 0
  • +

Replies To: Random Array Selection

#2 Martyr2   User is online

  • Programming Theoretician
  • member icon

Reputation: 5283
  • View blog
  • Posts: 14,104
  • Joined: 18-April 07

Re: Random Array Selection

Posted 30 August 2010 - 10:18 PM

One method you can do is run through a loop where you randomly pick two entries and swap them. Do that like 50 times and then you can just iterate through the array one by one until you reach the end. Then swap them all randomly again and restart the loop.

:)
Was This Post Helpful? 1
  • +
  • -

#3 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4214
  • View blog
  • Posts: 13,315
  • Joined: 08-June 10

Re: Random Array Selection

Posted 31 August 2010 - 12:07 AM

something I found useful to create a shuffled array
	function randOrd() 
	{
		return (Math.round(Math.random()) - 0.5); 
	}

	yourArray.sort(randOrd);


Was This Post Helpful? 1
  • +
  • -

#4 Fuingurth   User is offline

  • D.I.C Head
  • member icon

Reputation: 11
  • View blog
  • Posts: 118
  • Joined: 13-August 09

Re: Random Array Selection

Posted 05 September 2010 - 04:02 PM

Thank you both, I have gotten it to work thanks to you guys.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1