Friday, January 1, 2016

yesterday we were discussing a problem where we had to find the number of passwords possible from observed M fingerprints and the password being N letters long.
We stated that when
M == N then the number of permutations is N!
If N > M then there are repetitions of some of the letters and we broke up the case as
               a letter appearing twice
               a letter appearing thrice
               :
               a letter appearing N-M+1 times
              and the above repeated for each of the M letters
The number of permutations in each case can be determined by dividing the permutations by the factorial of  the number of objects that are identical.
Let us take a few examples
For M=3 N=5 we have  M * (N!/(2!2!) + N!/3!)
For M=3 N=6 we have  M * (N!/(2!2!2!) +  N!/(3!2!1!) + N!/(4!1!1!)) where 4 = N-M+1
Note the denominators are such that the repetitions together with single occurrences add up to N
Finding the different denominators is easy because we are trying to find the sum s with at most p components where s = N and p = N-M
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SumToN
{
    class Program
    {
        static void Main(string[] args)
        {
            var sequence = new List<int>();
            GenSeq(6, 3, ref sequence);
            PrintSequence(sequence);
        }
        static void PrintSequence(List<int> sequence)
        {
            Console.WriteLine();
            for(int i = 0; i < sequence.Count; i++) {Console.Write(sequence[i]);}
            Console.WriteLine();
            return;
        }
        static void GenSeq(int s, int p, ref List<int> sequence)
        {
            if (s == 0) {if(p==0)PrintSequence(sequence); return;}
            if (s != 0 && p == 0) { return; }
            for (int i = 0; i <= s; i++)
            {
                sequence.Add(i);
                GenSeq(s - i, p - 1, ref sequence);
                sequence.RemoveAt(sequence.Count - 1);
            }
        }
    }
}


No comments:

Post a Comment