Distinct Numbers obtained by generating all permutations of a Binary String
Given a binary string S, the task is to print all distinct decimal numbers that can be obtained by generating all permutations of the binary string.
Examples:
Input: S = “110”
Output: {3, 5, 6}
Explanation:
All possible permutations are {“110”, “101”, “110”, “101”, “011”, “011”}.
Equivalent decimal numbers of these binary strings are {6, 5, 6, 5, 3, 3} respectively.
Therefore, the distinct decimal numbers obtained are {3, 5, 6}.Input: S = “1010”
Output: {3, 5, 6, 9, 10, 12}
Approach: The problem can be solved using a Set. Follow the steps below to solve the problem:
- Convert the given string to a list of characters.
- Permute this list using built-in python function itertools. permutations().
- Initialize an empty string s.
- Traverse the list of permutations and perform the following steps for each permutation:
- Iterate over the characters and add them to the string.
- Convert this binary string to equivalent decimal.
- Insert the current decimal value obtained into a set.
- Finally, print the numbers present in the set.
Below is the implementation of the above approach:
Python3
# Python3 program for the above approach from itertools import permutations # Function to convert binary # string to equivalent decimal def binToDec(n): num = n dec_value = 0 # Initializing base # value to 1, i.e 2 ^ 0 base1 = 1 len1 = len (num) for i in range (len1 - 1 , - 1 , - 1 ): if (num[i] = = '1' ): dec_value + = base1 base1 = base1 * 2 # Return the resultant # decimal number return dec_value # Function to print all distinct # decimals represented by the # all permutations of the string def printDecimal(permute): # Set to store distinct # decimal representations allDecimals = set () # Iterate over all permutations for i in permute: # Initialize an empty string s = "" # Traverse the list for j in i: # Add each element # to the string s + = j # Convert the current binary # representation to decimal result = binToDec(s) # Add the current decimal # value into the set allDecimals.add(result) # Print the distinct decimals print (allDecimals) # Utility function to print all # distinct decimal representations # of all permutations of string def totalPermutations(string): # Convert string to list lis = list (string) # Built in method to store all # the permutations of the list permutelist = permutations(lis) printDecimal(permutelist) # Given binary string binarystring = '1010' # Function call to print all distinct # decimal values represented by all # permutations of the given string totalPermutations(binarystring) |
{3, 5, 6, 9, 10, 12}
Time Complexity: O(N * N!)
Auxiliary Space: O(N * N!)