AlgoDaily Solution

1// Shuffle function implementation - fill in your code!
2function shuffle(arr) {
3   for (let i = 0; i < arr.length; i++) {
4     const j = i + Math.floor(Math.random() * (arr.length - i));
5     [arr[i], arr[j]] = [arr[j], arr[i]];
6  }
7}
8
9const arr = [1, 2, 3, 4];
10const permutations = [
11  [1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2],
12  [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1],
13  [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1],
14  [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]
15];
16
17// Shuffle the array
18shuffle(arr);
19
20// Validate the shuffled array
21const isValidPermutation = permutations.some(permutation => JSON.stringify(permutation) === JSON.stringify(arr));
22
23if (isValidPermutation) {
24  console.log('The shuffled array is a valid permutation:', arr);
25} else {
26  console.log('Something went wrong! The shuffled array does not match any of the valid permutations.');
27}

Community Solutions

Community solutions are only available for premium users.

Access all course materials today

The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.