2 Replies - 8980 Views - Last Post: 12 January 2015 - 02:25 PM

#1 kiwi2  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 8
  • View blog
  • Posts: 178
  • Joined: 16-September 08

Random Array element picker Java Script

Posted 01 November 2008 - 08:05 AM

Description: self explanatorysimilar to php's built-in shuffle();, shuffles the array and returns one random result.
<html><head></head></body>
<script>
var ar = new Array(4);
ar[0] = "HELLO";
ar[1] = "GOODBYE";
ar[2] = "THANK YOU";
ar[3] = "GOOD DAY";
function shuffle(h) 
{ 
var num = Math.floor(Math.random() * h.length);
var j = h[num];
return j; 
} 
var t = shuffle(ar); 
 
document.write(t) 
</script></body></html>


Is This A Good Question/Topic? 0
  • +

Replies To: Random Array element picker Java Script

#2 RetardedGenius  Icon User is offline

  • >>──(Knee)──►
  • member icon

Reputation: 127
  • View blog
  • Posts: 555
  • Joined: 30-October 10

Re: Random Array element picker Java Script

Posted 18 September 2011 - 01:33 PM

It's not shuffling the array at all, it's merely selecting a pseudo-random element of the array; the order of the array remains intact. Why are all of the Javascript snippets lacking in quality so badly?
Was This Post Helpful? 0
  • +
  • -

#3 JMRKER  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 134
  • View blog
  • Posts: 868
  • Joined: 25-October 08

Re: Random Array element picker Java Script

Posted 12 January 2015 - 02:25 PM

Original code was a "Random Array Element Picker" rather than an "Array Shuffler".

Here is a modification to the code to demonstrate the difference...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />

<title> Random Pick/Shifter </title>

</head>
<body>
<pre id="debug"></pre>

<script>
var ar = ["HELLO", "GOODBYE", "THANK YOU", "GOOD DAY", 'HOLA', 'ADIOS', 'POR FAVOR', 'GRACIAS'];
function rndPick(h) { 
  var num = Math.floor(Math.random() * h.length);
  return h[num];
} 
document.getElementById('debug').innerHTML = 'Array:<br>'+ar.join(', ');
var t = rndPick(ar); 
document.getElementById('debug').innerHTML += '<p>Random pick: <br>'+t;

function shuffle(array) {
  var tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}
ar = shuffle(ar);
document.getElementById('debug').innerHTML += '<p>Array shuffled:<br>'+ar.join(', ');

arr = ar.slice(0);
t = '';  
while (arr.length > 0) { t += arr.shift()+'<br>'; }
document.getElementById('debug').innerHTML += '<p>Shifted array selections:<br>'+t;

document.getElementById('debug').innerHTML 
  += '<p>Shifted array contents if array not saved:<br>'+arr+'<p>arr length: '+arr.length;


</script>

</body>
</html>


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1