If last ball required is of type P and the number of balls of P type is 1 while number of balls of other color is 0 the number of ways is 1.
if ( $ p == 1 && $ q == 0 && $ r == 0 && $ last == 0 ) return 1 ;