Some code snippets that do some fun stuff...
Random walker on a number line
A person starts from 0 on the number line. With every step - it can move either one unit left or one unit right. The choice is made with equal probability. Based on this condition, the code prints the position of the random walker for N steps. [Code here]
A sub category of this is to draw the random walk on a place with uniform distribution over (L, R, T, B) [Code here]
Would like to plot the distribution of these on the 2D plane. It would be a cool visualization in Octave or something! :) But am bored to do that right now... Will do it later.
Spiral matrix
A spiral matrix is the one that looks as follows:
Generate a square matrix of size n, such that
-- it has elements from 1 to n*2 (or 0 to n*2-1)
-- lowest element is at [n,n]
-- elements are arranged in a spiral order
|-------------------------------------------------
| |----------------------------------| |
| | |-----------------| | |
| | | | |
n^2-n-1 | ---------<--------<-------< V
n^2-n <-----------------<--------<---------<--|
n^2-n+1 n^2-n+2 ...... (n^2-3) (n^2-2) (n^2-1) n^2
Example for N=3:
5 6 7
4 9 8
3 2 1
Example for N=6:
11 12 13 14 15 16
10 27 28 29 30 17
9 26 35 36 31 18
8 25 34 33 32 19
7 24 23 22 21 20
6 5 4 3 2 1
Printing primes
Sieve of Eratosthenes is one of the known methods to list prime numbers upto a given max value. It works in a very nice way by eliminating the multiple of all primes seen so far upto the max value, moving one value at a time. Have written a code in python to list the primes using this technique. [Code here]
Printing permutations
This is a very typical problem. I do not know what made me code this up, but just felt like doing it today. The problem is to print all possible permutations of a give set of elements. For simplicity the code uses an integer n and prints out all possible permutations of <0, 1, 2 ... n-1> [Code here]