Sitemap
Pranay Kothapalli

Pranay Kothapalli

I write about Algorithms, Web, Software Engineering. I try to pick and solve one problem a day. You can follow me on GitHub — https://github.com/kotAPI

Algorithm (Beginner) — Shuffle Algorithm

2 min readDec 8, 2018
Press enter or click to view image in full size

If you’ve ever been bored of listening to songs in an order on your phone and have ever used the shuffle feature to change the order of the songs, you’ve used a variant of a shuffle algorithm.

I’ve used this algorithm to add an eye candy effect on my blog, you can see the letters shuffle and dance when you hover over the list items.

Implementing the shuffle algorithm is pretty fun. Here’s your challenge for today.

INPUT:

Get Pranay Kothapalli’s stories in your inbox

Join Medium for free to get updates from this writer.

An array of numbers

[1,2,3,4,5,6,7,8,9]

OUTPUT:
An array of randomized(shuffled) numbers different from the input.

[7,9,8,1,4,3,2,5,6]

NOTE: The most accurate shuffle algorithm is the one that is always random, you could write an algorithm that rearranges the numbers in a specific order depending on the input length or whatever. There are more than one ways to shuffle numbers. I will write a simple implementation of a shuffle algorithm which is also my favorite in this post.

Solution Ahead

The key is to get the total input count of numbers your function gets

  • Keep generating random numbers from 0 to N
  • Now that you have the random number between 0 and N, let's call it i. Now pick the number at index i. Swap it with 0.
  • And, that’s it, keep repeating this til N is reached.
1 2 3 4 5 6 7 8 9
// Generate a random number between 0 and N
// say i is 4, swap 4 with 1
1 2 3 4 5 6 7 8 9
<----->
4 2 3 1 5 6 7 8 9
// Now generate a random number between 1 and N
// swap the resulting index number with 1
// Repeat
4 1 3 2 6 5 9 7 8
// Your output will be a shuffled

The array after the algorithm finishes running is now shuffled.

Let me know in the comments if you tried solving this challenge. If you have a better way to do this, go ahead and post a link to your solution and lets discuss! Hope you enjoyed reading (and coding)!
Follow me if you’d want to keep updated with more challenges.

If you want to explore a list of more Algorithms and CS stuff, head over to Awelgorithms.

--

--

Pranay Kothapalli
Pranay Kothapalli

Written by Pranay Kothapalli

I write about Algorithms, Web, Software Engineering. I try to pick and solve one problem a day. You can follow me on GitHub — https://github.com/kotAPI