Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
/*
// INITIAL ALGORITHM
const arr = [1, 3, 4, 5, 2, 5]
for(let i = 0; i < arr.length; i++) {
  // generate a random integer less than arr.length
  let randomPosition = parseInt(Math.random()*arr.length);
  
  // swap current element with element at randomPosition
   let temp = arr[i];
   arr[i] = arr[randomPosition];
   arr[randomPosition] = temp;
}
console.log(arr)
*/
// IMPROVED
/*
const arr = [1, 3, 4, 5, 2, 5]
const arrCopy = [...arr]
for(let i = 0; i < arrCopy.length/2; i++) {
  // generate a random integer less than arr.length
  let randomPosition = parseInt(Math.random()*arr.length);
  
  // swap current element with element at randomPosition
   let temp = arrCopy[i];
   arrCopy[i] = arrCopy[randomPosition];
   arrCopy[randomPosition] = temp;
}
console.log("Original array (unchanged): ", arr)
console.log("Shuffled copy of array: ",arrCopy)
*/
// BREAKING DOWN TO FUNCTIONS
// returns a shuffled array
function shuffleArray(arr) {
  const arrCopy = [...arr]
  
  for(let i = 0; i < arrCopy.length/2; i++) {
  // generate a random integer less than arr.length
  let randomPosition = parseInt(Math.random()*arr.length);
  
  // swap current element with element at randomPosition
  swap(arrCopy, i, randomPosition)
  }
  return arrCopy
}
// Swaps array elements at the provide indices
function swap(inputArray, index1, index2) {
  let temp = inputArray[index1];
  inputArray[index1] = inputArray[index2];
  inputArray[index2] = temp;
}
const arr = [1, 3, 4, 5, 2, 5]
console.log(shuffleArray(arr))
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
Olusamimathspro
0viewers