Java Program to Generate and Display 4-Character Lexicographic Strings with Custom Constraints

 Assignment Description:



This assignment asks you to write a Java program that displays all 4-character strings in lexicographic (dictionary) order on the screen, with one string per line. Only the characters 'a', 'b', 'c', and 'd' may be used in the strings, with characters allowed to repeat within the same string. The character 'b' must always be immediately followed by the character 'a' within any string. Additionally, no string may contain both the character 'd' and the character 'a'. The program should output the total number of generated strings at the end. No input is required, and you must not use pre-calculated strings; all valid strings should be generated dynamically at runtime. Your solution should not exceed 200 lines of code.

solution 



public class Lexical {

public static void main(String[] args) {

           displayAllStrings("abcd");

       }

public static void displayAllStrings(String s ) {

         char[] ArrayCharacter = new char[s.length()];

         Helper(s , ArrayCharacter ,  0, s.length()-1);

        }

public static void Helper(String word, char[] Arr, int first , int end  )

    {

        for (int i = 0; i <  word.length(); i++)

        {

            Arr[first] = word.charAt(i);

            if (first == end )

            {

  String string = new String(Arr);

                if( !(string.charAt(3)=='b' || string.contains("a") && string.contains("d"))   &&  CheckRules(  string  ))

                    System.out.println(string);

            }

            else

                Helper(word, Arr, first + 1 , end );

        }

    }

public static boolean CheckRules(String word){

        for(int i=0;i<word.length()-1;i++)

        {

            if(word.charAt(i)=='b' && word.charAt(i+1)!='a')

                return false ;

        }

        return true ;

    }

}// class


📩 Need a similar solution? Email me: adel455@hotmail.com



Previous Post Next Post

Comments

Nepali Graphics - Learn design, Animation, and Progrmming