Meaning: In probability theory, the expected value (or expectation, or mean, or the first moment) of a random variable is the weighted average of all possible values that this random variable can take on.
Suppose random variable ‘X‘ can take value x1 with probability p1, value x2 with probability p2, and so on, up to value xk with probability pk. Then the expectation of this random variable ‘X’ is defined as:
E[X] = x1*p1 + x2*p2 + x3*p3 + ……………. + xk*pk;
Example : For the six faced dice with faces, 1, 2, 3, 4, 5, 6 : the expectation is: (assuming equal probability of getting all faces).
E[X] = 1* 1/6 + 2 * 1/6 + 3 * 1/6 + 4 * 1/6 + 5 * 1/6 + 6 * 1/6
E[X] = 3.5
Thus the expectation is 3.5.
Problem Section : Random Sort Riddles using Expectation.
After having a bit of theory of expectation, we will now solve one very tricky riddles using expectation and Dynamic Programming.
Problem Statement: Problem description can be found at:
http://community.topcoder.com/stat?c=problem_statement&pm=8590&rd=12174&rm=&cr=7452866
Don’t go for navie recursive code. It will for sure exceed the limit of 2second. So think of memoisation technique.
Here below is the implementation for the same using Dynamic Programming (recursion + memoisation approach):
Map <int[], Double> map = new TreeMap <int[], Double>(new Comparator<int[]>() { public int compare(int[] p1, int[] p2) { for(int i = 0; i < p1.length; i++) { if(p1[i] != p2[i]) return p1[i] - p2[i]; } return 0; } }); public double solve(int[] p) { double deno = 0, num = 0; int[] arr = new int[p.length]; if(map.containsKey(p)) return map.get(p); for(int i = 0; i < p.length; i++) { for(int j = i + 1; j < p.length; j++) { if(p[i] > p[j]) { arr = (int[])p.clone(); int temp =p[i]; p[i] = p[j]; p[j] = temp; num += 1 + solve(p); deno++; temp =p[i]; p[i] = p[j]; p[j] = temp; } } } if(deno == 0) num = 0; else num /= deno; map.put(arr, num); return num; } public double getExpected(int[] p) { return solve(p); }