Monday, October 19, 2015


Q:Given a string find the first non repeating character in it
A:
void getFirstNonRepeatingCharacter(String input)
{
    var freq = new Dict<char, int>();
    for(int i = 0; i < input.Length; i++)
    { 
        freq[input[i]] += 1;
     }
    foreach (KeyValuePair<char, int> kvp in freq)
    {
        if (kvp.value == 1)
             Console.WriteLine("{0}", freq[kvp.key]);
     }
 }


Let n and k be fixed positive integers of the same parity, k n. We are given 2n lamps
numbered 1 through 2n; each of them can be on or off. At the beginning all lamps are off. We
consider sequences of k steps. At each step one of the lamps is switched (from off to on or from
on to off).
Let N be the number of k-step sequences ending in the state: lamps 1, . . . , n on, lamps
n+1, . . . , 2n off.
Let M be the number of k-step sequences leading to the same state and not touching lamps
n+1, . . . , 2n at all.
Find the ratio N/M.

Let us call the first set of operations that results in N as admissible
Let us call the second set of operations that result in M as restricted.

For a lamp to remain on, it must be switched an odd number of times.
For a lamp to remain off, it must be switched an even number of times.

Take any lamp l  1<=l <= n and supposed it was switched kl times which should be odd number for the lamp to remain on. Select arbitrarily an even number of Kl switches and replace each of them by the switch of the lamp n+l. This can be done in 2^(kl-one) ways because a kl element set must have 2^(kl-1) subsets of even cardinality. and we started out by saying k1 + .. kn = k.
Since each lamp can be affected independent of others, there are 2^(k1-1) . 2^(k2-1) . 2^(k3-1) . ...2^(kn-1)  = 2 ^(k-n) ways of combining these actions. In any one of these combinations, the end state is the desired state as per the question.
Therefore N/M = 2 ^(k-n).

No comments:

Post a Comment