Count anagrams having first character as a consonant and no pair of consonants or vowels placed adjacently


Anagrams are a fascinating concept in computer science and language processing. They are essentially words or phrases made by rearranging the letters of another word or phrase. The challenge increases when we introduce specific rules. Today, we'll delve into a unique problem - counting anagrams that start with a consonant and have no adjacent consonants or vowels. We'll use C++ to develop a solution and walk through an illustrative example.

Algorithm Explanation

Our task is to count anagrams under two constraints −

  • The first character must be a consonant.

  • There should be no adjacent consonants or vowels.

To implement this, we will −

  • Extract consonants and vowels separately.

  • Implement a recursive function to generate combinations adhering to our rules.

C++ Implementation

Let's explore a step-by-step C++ implementation −

Example

Let's explore a step-by-step implementation in various programming languages −

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char anagrams[10000][10];
int anagramsCount = 0;

// Function to check if a character is vowel
int isVowel(char c) {
   return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

// Function to generate anagrams following rules
void generateAnagrams(char *s, char *consonants, char *vowels, int n) {
   // Base case: when string length reaches n
   if (strlen(s) == n) {
      strcpy(anagrams[anagramsCount++], s);
      return;
   }

   // Add consonants and vowels alternatively
   if (strlen(s) % 2 == 0) { // Add consonant
      for (int i = 0; i < strlen(consonants); i++) {
         char newConsonants[10];
         strcpy(newConsonants, consonants);
         memmove(newConsonants + i, newConsonants + i + 1, strlen(newConsonants) - i);
         generateAnagrams(strncat(strdup(s), &(consonants[i]), 1), newConsonants, vowels, n);
      }
   } else { // Add vowel
      for (int i = 0; i < strlen(vowels); i++) {
         char newVowels[10];
         strcpy(newVowels, vowels);
         memmove(newVowels + i, newVowels + i + 1, strlen(newVowels) - i);
         generateAnagrams(strncat(strdup(s), &(vowels[i]), 1), consonants, newVowels, n);
      }
   }
}
int main() {
   char str[10];
   strcpy(str, "abc");

   char consonants[10] = "";
   char vowels[10] = "";
   for (int i = 0; i < strlen(str); i++) {
      if (isVowel(str[i])) {
         strncat(vowels, &(str[i]), 1);
      } else {
         strncat(consonants, &(str[i]), 1);
      }
   }

   generateAnagrams("", consonants, vowels, strlen(str));

   printf("Anagrams count: %d\n", anagramsCount);

   return 0;
}

Output

Anagrams count: 2
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string> anagrams;

// Function to check if a character is vowel
bool isVowel(char c) {
   return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

// Function to generate anagrams following rules
void generateAnagrams(string s, string consonants, string vowels, int n) {
   // Base case: when string length reaches n
   if (s.length() == n) {
      anagrams.push_back(s);
      return;
   }
   
   // Add consonants and vowels alternatively
   if (s.length() % 2 == 0) { // Add consonant
      for (int i = 0; i < consonants.length(); i++) {
         generateAnagrams(s + consonants[i], consonants.substr(0, i) + consonants.substr(i + 1), vowels, n);
      }
   } else { // Add vowel
      for (int i = 0; i < vowels.length(); i++) {
         generateAnagrams(s + vowels[i], consonants, vowels.substr(0, i) + vowels.substr(i + 1), n);
      }
   }
}
int main() {
   string str;
   str="abc";
   
   string consonants = "", vowels = "";
   for (int i = 0; i < str.length(); i++) {
      if (isVowel(str[i])) vowels += str[i];
      else consonants += str[i];
   }
   
   generateAnagrams("", consonants, vowels, str.length());
   
   cout << "Anagrams count: " << anagrams.size() << endl;
   
   return 0;
}

Output

Anagrams count: 2
import java.util.ArrayList;

public class AnagramGenerator {

   static ArrayList<String> anagrams = new ArrayList<>();

   // Function to check if a character is vowel
   static boolean isVowel(char c) {
      return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
   }

   // Function to generate anagrams following rules
   static void generateAnagrams(String s, String consonants, String vowels, int n) {
      // Base case: when string length reaches n
      if (s.length() == n) {
         anagrams.add(s);
         return;
      }

      // Add consonants and vowels alternatively
      if (s.length() % 2 == 0) { // Add consonant
         for (int i = 0; i < consonants.length(); i++) {
            generateAnagrams(s + consonants.charAt(i), consonants.substring(0, i) + consonants.substring(i + 1), vowels, n);
         }
      } else { // Add vowel
         for (int i = 0; i < vowels.length(); i++) {
            generateAnagrams(s + vowels.charAt(i), consonants, vowels.substring(0, i) + vowels.substring(i + 1), n);
         }
      }
   }

   public static void main(String[] args) {
      String str = "abc";
      String consonants = "";
      String vowels = "";
      for (int i = 0; i < str.length(); i++) {
         if (isVowel(str.charAt(i))) {
            vowels += str.charAt(i);
         } else {
            consonants += str.charAt(i);
         }
      }

      generateAnagrams("", consonants, vowels, str.length());
      System.out.println("Anagrams count: " + anagrams.size());
   }
}

Output

Anagrams count: 2
anagrams = []

# Function to check if a character is vowel
def isVowel(c):
   return c in ['a', 'e', 'i', 'o', 'u']

# Function to generate anagrams following rules
def generateAnagrams(s, consonants, vowels, n):
   global anagrams
   # Base case: when string length reaches n
   if len(s) == n:
      anagrams.append(s)
      return

   # Add consonants and vowels alternatively
   if len(s) % 2 == 0:  # Add consonant
      for i in range(len(consonants)):
         generateAnagrams(s + consonants[i], consonants[:i] + consonants[i+1:], vowels, n)
   else:  # Add vowel
      for i in range(len(vowels)):
         generateAnagrams(s + vowels[i], consonants, vowels[:i] + vowels[i+1:], n)

str = "abc"

consonants = ""
vowels = ""
for char in str:
   if isVowel(char):
      vowels += char
   else:
      consonants += char

generateAnagrams("", consonants, vowels, len(str))
print("Anagrams count:", len(anagrams))

Output

Anagrams count: 2

This program takes an input string and separates the consonants and vowels. It then recursively generates anagrams by adding consonants and vowels alternatively.

Test Case Example

Suppose we run the program with the input string "abc". This string has two consonants ("b" and "c") and one vowel ("a"). The possible anagrams following the rules would be "bca" and "cab".

Conclusion

In this tutorial, we've learned how to count anagrams with specific rules in C++. We discussed an approach involving separating consonants and vowels and using recursion to generate the anagrams. This not only deepens our understanding of anagrams but also expands our knowledge of how to handle constraints in programming problems.

Updated on: 16-Oct-2023

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements