Shuffle Algorithm (Swap Method)

The shuffle algorithm is a way to generate random numbers that never repeat. For example, suppose you need to generate ten random numbers, and all ten must be “unique.” Many people’s first instinct is to call the rand function to get a random value, store it in an array, and compare it against the numbers already in the array. That method is simple, but its performance is very poor. The shuffle algorithm introduced here is worlds apart from that approach in terms of performance. The principle behind the shuffle algorithm is actually very simple: first store the numbers in an array, then scramble them. ...

June 5, 2011 · 3 min

[C++] Reversing Numbers and Strings (Applications: Type Conversion, String Handling, Loops)

This is a fairly simple problem: it just reverses a number or a string. For example, input "linroex" and the output is "xeornil", or input 123 and get 321. The solution isn't hard. In C++, you can access a string like an array, so we set up a loop whose end value is the length of the input string. On each pass, we move the last remaining character of string X to the first position of string Y. When the loop finishes, the reversal is complete. ...

March 6, 2011 · 2 min

[VB] [C++] Calculating n! (Factorial)

Calculating the factorial of n is very simple. I wrote this program for permutations and combinations: I wanted a rough idea of how many possible answers there would be, so I wrote an n! function to compute the factorial value. A factorial is 123…..n. In a permutation of 5 items, the result is at most 5432*1, which means there are at most 120 possible answers. Below, I’ve made n! into a Function, with a VB version and a C++ version. People who are just starting to learn loops can use this function to practice how loops work. Also, because I was worried that an integer wouldn’t be able to hold the result, I used a string to return the value. When you use this Function, you need to convert the return value to a numeric type first. ...

January 5, 2011 · 1 min