Home > Article > Backend Development > Lexicographic ranking of binary strings
In this article, we will explore an interesting problem involving binary strings and lexicon ordering. Our task is to find the lexicographic ranking of a given binary string. We'll demonstrate our solution using C, a popular programming language known for its efficiency and flexibility.
Dictionary order (also called alphabetical order or dictionary order) is the arrangement of words in alphabetical order according to their constituent letters.
Given a binary string, we need to determine its lexicographic ranking among all permutations. The lexicographic rank of a string is its position in the set of all permutations when they are listed lexicographically.
Our approach includes the following key steps −
Initialize count − Initialize a counter to store the number of '1's in the binary string.
Ranking calculation − Iteratively traverses the binary string from left to right. If the current character is '1', calculate its rank using a combined formula and decrement the counter for each subsequent '1'.
Return Result− The result will be the lexicographic order of the binary string.
The following C code outlines our solution −
#include <bits/stdc++.h> using namespace std; // Function to calculate factorial int fact(int n) { int res = 1; for (int i = 1; i <= n; i++) res *= i; return res; } // Function to find lexicographic rank of a binary string int lexRank(string str) { int rank = 1; int onesCount = count(str.begin(), str.end(), '1'); for (char c : str) { if (c == '1') { onesCount--; rank += fact(onesCount); } } return rank; } int main() { string str = "110"; int result = lexRank(str); cout << "Lexicographic rank of the binary string: " << result << endl; return 0; }
Lexicographic rank of the binary string: 3The Chinese translation of
Consider binary string −
str = "110"
The permutations and combinations of this binary string are: "011", "101", "110". In lexicographic order, these permutations are: "011", "101", "110".
The binary string "110" has a rank of 3, which is the output of our program.
The problem of finding the lexicographic ranking of a binary string is a very interesting problem, which is based on our understanding of binary strings, permutations and lexicographic order. This solution implemented in C shows how we can use basic programming constructs to solve this problem efficiently.
The above is the detailed content of Lexicographic ranking of binary strings. For more information, please follow other related articles on the PHP Chinese website!