Number of ways such that only K bars are visible from the left | Function to calculate the number of bars that are visible from the left for a particular arrangement ; If current element is greater than the last greater element , it is visible ; Function to calculate the number of rearrangements where K bars are visiblef from the left ; Vector to store current permutation ; Check for all permutations ; If current permutation meets the conditions , increment answer ; Driver code ; Input ; Function call
def noOfbarsVisibleFromLeft ( v ) : NEW_LINE INDENT last = 0 NEW_LINE ans = 0 NEW_LINE for u in v : NEW_LINE INDENT if ( last < u ) : NEW_LINE INDENT ans += 1 NEW_LINE last = u NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def nextPermutation ( nums ) : NEW_LINE INDENT i = len ( nums ) - 2 NEW_LINE while i > - 1 : NEW_LINE INDENT if nums [ i ] < nums [ i + 1 ] : NEW_LINE INDENT j = len ( nums ) - 1 NEW_LINE while j > i : NEW_LINE INDENT if nums [ j ] > nums [ i ] : NEW_LINE INDENT break NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT nums [ i ] , nums [ j ] = nums [ j ] , nums [ i ] NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT nums [ i + 1 : ] = reversed ( nums [ i + 1 : ] ) NEW_LINE return nums NEW_LINE DEDENT def KvisibleFromLeft ( N , K ) : NEW_LINE INDENT v = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT v [ i ] = i + 1 NEW_LINE DEDENT ans = 0 NEW_LINE temp = list ( v ) NEW_LINE while True : NEW_LINE INDENT if ( noOfbarsVisibleFromLeft ( v ) == K ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT v = nextPermutation ( v ) NEW_LINE if v == temp : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 2 NEW_LINE print ( KvisibleFromLeft ( N , K ) ) NEW_LINE DEDENT