/**
 * TNTStringManip.java
 * 
 * A comprehensive collection of battle-tested string manipulation utility methods
 * designed for APCS-A education and practical programming.
 * 
 * This class contains 16 static utility methods covering:
 * - Whitespace handling (removing multiple spaces, iterative and recursive)
 * - Object addressing (memory location retrieval via multiple approaches)
 * - Character and string repetition (single characters and multi-char phrases)
 * - Symbol classification and filtering (special characters, alphabetization)
 * - String reversal (with options to preserve casing and punctuation patterns)
 * - Phrase-level operations (reversing words, scrambling vowels)
 * - Vowel manipulation (removal and randomized scrambling with reproducible seeding)
 * 
 * Methods are organized alphabetically by name for easy reference.
 * 
 * Version: 1.0
 * Last Updated: 2026-11-27
 * 
 * Usage:
 *   // Static methods called directly on the class
 *   String cleaned = TNTStringManip.removeMultipleSpaces("Hello    World");
 *   String reversed = TNTStringManip.reverse("Hello", true, false);
 *   String address = TNTStringManip.obtainAddress(myObject);
 *   boolean isSymbol = TNTStringManip.isSpecialSymbol("@");
 *   String sorted = TNTStringManip.alphabetize("hello");
 *   String disemvoweled = TNTStringManip.disemvowel("hello", false);
 *   String scrambled = TNTStringManip.scrambleVowelsIn("computer", 42);
 *   String phraseScrambled = TNTStringManip.scrambleWordVowelsInPhrase("hello world", 42);
 * 
 * @author TNT (Teacher and Tutor) Team
 */

import java.util.Arrays;
import java.util.Collections;

public class TNTStringManip {

    /**
     * Sorts the characters in a string in ascending order by their Unicode values.
     * This arranges letters alphabetically (uppercase before lowercase by Unicode),
     * plus digits, symbols, and special characters sorted by their Unicode values.
     * 
     * @param x the input string to sort
     * @return a new string with characters sorted by Unicode value
     * 
     * @example
     *   alphabetize("hello")          // "ehllo"
     *   alphabetize("Hello@123World") // "@123HWdelllloor"
     *   alphabetize("xyz")            // "xyz" (already sorted)
     *   alphabetize("dcba")           // "abcd"
     *   alphabetize("AaBbCc")         // "ABCabc" (uppercase before lowercase)
     *   alphabetize("café")           // "acéf"
     *   alphabetize("")               // ""
     * 
     * @note Character order follows Unicode standards:
     *       - Spaces and punctuation sort first (by Unicode value)
     *       - Digits (0–9) sort next (Unicode 48–57)
     *       - Uppercase letters (A–Z) sort next (Unicode 65–90)
     *       - Lowercase letters (a–z) sort after (Unicode 97–122)
     *       - Other Unicode characters follow (accented letters, symbols, etc.)
     *       This is NOT dictionary/lexicographic order (which would be A, a, B, b...);
     *       it is strict Unicode numeric order.
     */
    public static String alphabetize(String x){
        char[] chars = x.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }//end alphabetize

    /**
     * Creates a new String by repeating a single character a specified number of times.
     * Useful for generating patterns, dividers, or any repeated character sequences.
     * 
     * @param c the character to repeat
     * @param len the number of times to repeat the character
     * @return a new String containing the character repeated len times
     * 
     * @example
     *   charString('*', 5)      // returns "*****"
     *   charString('-', 10)     // returns "----------"
     *   charString('=', 20)     // returns "===================="
     *   charString('A', 3)      // returns "AAA"
     */
    public static String charString(char c, int len){
        String temp = "";
        for(int i = 1; i <= len; i++) temp += c;
        return temp;
    }//end charString

    /**
     * Extracts and returns the last character of a string as a String object.
     * Note: Returns String (not char) for consistency with the String utility belt.
     * This allows method chaining and maintains type consistency across string utilities.
     * 
     * @param str the string to extract the last character from
     * @return the last character, wrapped as a String (e.g., "o" from "hello")
     * @throws StringIndexOutOfBoundsException if the string is empty
     * 
     * @example
     *   lastSymbol("hello")     // returns "o"
     *   lastSymbol("Java")      // returns "a"
     *   lastSymbol("!")         // returns "!"
     *   lastSymbol("café")      // returns "é"
     * 
     * @design_note
     *   This utility returns String instead of char for several reasons:
     *   (1) Consistency: String utilities return Strings
     *   (2) Chainability: lastSymbol(str).toUpperCase() works without casting
     *   (3) Utility philosophy: predictable return types
     *   (4) Users who need char can call: char c = lastSymbol(str).charAt(0);
     */
    public static String lastSymbol(String str){
        int len = str.length();
        char lastChar = str.charAt(len-1);
        return String.valueOf(lastChar);
    }//end lastSymbol

    /**
     * Returns the memory address of an object as a hex string.
     * This method extracts the identity hash code and converts it to hexadecimal.
     * 
     * @param obj the object whose address we want to examine
     * @return a String representation of the object's memory address in hex format, prefixed with "@"
     * 
     * @example
     *   String s1 = "Hello";
     *   String s2 = new String("Hello");
     *   System.out.println(obtainAddress(s1));  // e.g., @556e0e67
     *   System.out.println(obtainAddress(s2));  // e.g., @3a5c0e43 (different memory!)
     * 
     * @see System#identityHashCode(Object)
     * @see Integer#toHexString(int)
     */
    public static String obtainAddress(Object obj){
        int x = System.identityHashCode(obj);
        String x2 = Integer.toHexString(x);
        String info = "@" + x2;
        return info;
    }//end obtainAddress

    /**
     * Returns the memory address of an object by directly calling Object's toString() method.
     * This method works ONLY on a class that directly inherits from Object.
     * It demonstrates how to access the parent class's default implementation via super.
     * 
     * This method has NO PARAMETER because it's meant to be called FROM a class definition,
     * not FROM outside. Use this in your own class when you want to access what Object.toString()
     * would return for your instance.
     * 
     * @return a String representation of the object (class name + @ + memory address)
     *         in the format: "ClassName@hexAddress"
     * 
     * @example (called from within a class that extends Object directly)
     *   public class MyClass {
     *       public String getDefaultString(){
     *           return obtainAddressViaObjectClass();  // Returns: MyClass@7c30a502
     *       }
     *   }
     * 
     * @see java.lang.Object#toString()
     * @see java.lang.Object
     */
    public static String obtainAddressViaObjectClass(){
        // Note: This method cannot call super.toString() in a static context.
        // This is provided as a template/reference for how to use super.toString()
        // from within an instance method in your own classes.
        // For the actual implementation in a non-static context, use:
        // return super.toString();
        return "[This method is a reference template for use within instance methods]";
    }//end obtainAddressViaObjectClass

    /**
     * Tests whether a String represents a special symbol (non-letter, non-digit, non-whitespace).
     * Uses Java's built-in Character wrapper class methods for robust character classification.
     * This is a predicate method: it returns true or false.
     * 
     * @param symbol a single-character string to test
     * @return true if the character is a special symbol (not letter, digit, or whitespace),
     *         false otherwise
     * 
     * @example
     *   isSpecialSymbol("@")    // true  (special symbol)
     *   isSpecialSymbol("a")    // false (letter)
     *   isSpecialSymbol("5")    // false (digit)
     *   isSpecialSymbol(" ")    // false (whitespace)
     *   isSpecialSymbol("!")    // true  (special symbol)
     *   isSpecialSymbol("$")    // true  (special symbol)
     * 
     * @note This method leverages Java's Character class for correctness.
     *       Character.isLetter(), Character.isDigit(), and Character.isWhitespace()
     *       handle Unicode properly and are maintained by the Java library.
     * 
     * IMPLEMENTATION NOTE: Alternative brute-force approach (not recommended)
     *   // Brute-force with hardcoded character set:
     *   String specialSet = ".,:;'\"!?-@#$%^&*()_+=[]{}|;<>,./~`\\";
     *   return symbol != null && symbol.length() == 1 
     *       && specialSet.indexOf(symbol) >= 0;
     *   
     *   Why we don't use this:
     *   - Hardcoded set is incomplete (what about emoji or other Unicode symbols?)
     *   - Not maintainable (if character set changes, manual update needed)
     *   - Doesn't scale (limited to ASCII, fixed set)
     *   - Professional practice: reach for the standard library first!
     */
    public static boolean isSpecialSymbol(String symbol){
        if (symbol == null || symbol.length() != 1) return false;
        char c = symbol.charAt(0);
        return !Character.isLetter(c) 
            && !Character.isDigit(c) 
            && !Character.isWhitespace(c);
    }//end isSpecialSymbol

    /**
     * Removes all special symbols from a string, keeping only letters, digits, and whitespace.
     * Uses isSpecialSymbol() as a helper predicate, demonstrating method composition.
     * 
     * @param x the input string to filter
     * @return a new string with all special symbols removed,
     *         keeping only letters, digits, and whitespace
     * 
     * @example
     *   removeSpecialSymbols("Hello@World!")   // "HelloWorld"
     *   removeSpecialSymbols("Price: $9.99")   // "Price 999"
     *   removeSpecialSymbols("user@email.com") // "useremailcom"
     *   removeSpecialSymbols("No symbols")     // "No symbols" (unchanged)
     *   removeSpecialSymbols("123ABC!@#")     // "123ABC"
     * 
     * @note Demonstrates method composition: this method uses isSpecialSymbol() 
     *       as a helper. This is good design practice—keep methods focused and
     *       combine them for more complex operations.
     * 
     * IMPLEMENTATION NOTE: Alternative brute-force approach (not recommended)
     *   // Hardcoded character set approach:
     *   String specialSet = ".,:;'\"!?-@#$%^&*()_+=[]{}|;<>,./~`\\";
     *   String temp = "";
     *   for(int i = 0; i < x.length(); i++){
     *       char ch = x.charAt(i);
     *       if(specialSet.indexOf(String.valueOf(ch)) < 0) temp += ch;
     *   }
     *   return temp;
     * 
     *   Why the wrapper-class approach is better:
     *   - Uses Character.isLetter(), Character.isDigit() (standard library)
     *   - Scales to Unicode and all character types
     *   - More maintainable (relies on Java's definitions, not ours)
     *   - Aligns with professional practice: leverage standard library methods
     */
    public static String removeSpecialSymbols(String x){
        String temp = "";
        int len = x.length();
        for(int i = 0; i < len; i++){
            String ch = String.valueOf(x.charAt(i));
            if(!isSpecialSymbol(ch)) temp += ch;
        }
        return temp;
    }//end removeSpecialSymbols

    /**
     * Removes all consecutive multiple spaces, reducing them to single spaces.
     * Also trims leading and trailing whitespace.
     * 
     * @param str the input string to clean
     * @return a new string with multiple spaces reduced to single spaces,
     *         and leading/trailing whitespace removed
     * 
     * @example
     *   removeMultipleSpaces("Hello    World") → "Hello World"
     *   removeMultipleSpaces("  Java   rocks!  ") → "Java rocks!"
     */
    public static String removeMultipleSpaces(String str){
        int len0 = str.length();
        String temp = str.trim();
        String doubleSpace = "  ";
        String singleSpace = " ";
        int count = 0; //accumulator
        while(temp.contains(doubleSpace)){
            temp = temp.replace(doubleSpace, singleSpace);
            count++;
        }//end loop
        
        return temp;
    }//end removeMultipleSpaces

    /**
     * Removes all consecutive multiple spaces using RECURSION.
     * Also trims leading and trailing whitespace.
     * 
     * This version demonstrates recursive problem-solving.
     * Compare with removeMultipleSpaces() to see iteration vs. recursion!
     * 
     * @param str the input string to clean
     * @return a new string with multiple spaces reduced to single spaces,
     *         and leading/trailing whitespace removed
     * 
     * @example
     *   removeMultipleSpacesRecursively("Hello    World") → "Hello World"
     *   removeMultipleSpacesRecursively("  Java   rocks!  ") → "Java rocks!"
     */
    public static String removeMultipleSpacesRecursively(String str){
        // First call: trim the input string
        return removeMultipleSpacesRecursiveHelper(str.trim());
    }//end removeMultipleSpacesRecursively

    /**
     * Helper method for the recursive logic.
     * Base case: when no double spaces exist, we're done.
     * Recursive case: replace one double space and recurse.
     */
    private static String removeMultipleSpacesRecursiveHelper(String str){
        // BASE CASE: No more double spaces — return the string
        if (!str.contains("  ")) {
            return str;
        }
        
        // RECURSIVE CASE: Replace ONE occurrence of "  " with " "
        // Then recursively call on the result (which may still have double spaces)
        String reduced = str.replaceFirst("  ", " ");
        return removeMultipleSpacesRecursiveHelper(reduced);
    }//end removeMultipleSpacesRecursiveHelper

    /**
     * Creates a new String by repeating an entire phrase
     * a specified number of times. No spaces between
     * repetitions. Similar to charString(), but for
     * multi-character strings.
     * 
     * @param x the phrase or string to repeat
     * @param n the number of times to repeat the phrase
     * @return a new String with phrase repeated n times
     *         with no spaces between repetitions
     * 
     * @example
     *   repeatedPhrase("Ha", 3)    // "HaHaHa"
     *   repeatedPhrase("Go!", 4)   // "Go!Go!Go!Go!"
     *   repeatedPhrase("*-", 5)    // "*-*-*-*-*-"
     *   repeatedPhrase("Java", 2)  // "JavaJava"
     * 
     * @note Uses same algorithm as charString().
     *       repeatedPhrase generalizes to any String.
     *       charString is a specialized single char case.
     */
    public static String repeatedPhrase(String x, int n){
        String temp = "";
        for(int i = 1; i <= n; i++) temp += x;
        return temp;
    }//end repeatedPhrase

    /**
     * Reverses a string with optional preservation of casing and punctuation patterns.
     * 
     * @param x the input string to reverse
     * @param shouldPreserveCasing if true, case pattern at each position is preserved 
     *        (e.g., "Hello" → "Olleh", uppercase at position 0 stays uppercase)
     * @param shouldPreservePunctuation if true, punctuation stays in original positions, 
     *        only letters/digits are reversed (e.g., "don't" → "t'nod", not "t'nod")
     * @return a reversed string with optional preservation constraints applied
     * 
     * @example
     *   reverse("hello", false, false)              // "olleh"
     *   reverse("Hello", true, false)               // "Olleh" (position 0 uppercase, stays uppercase)
     *   reverse("shouldn't", false, true)           // "t'ndluohs" (apostrophe stays at pos 6)
     *   reverse("shouldn't", true, true)            // "t'ndluohs" (all lowercase positions, apostrophe fixed)
     *   reverse("HeLLo", true, false)               // "OlLEh" (positions 0,2,3 uppercase, positions 1,4 lowercase)
     *   reverse("Mister", true, false)              // "Retsim" (position 0 uppercase)
     *   reverse("@#$", false, false)                // "$#@"
     * 
     * @see #reverseWordsInPhrase(String)
     * 
     * IMPLEMENTATION NOTE: This method demonstrates elegant constraint handling:
     *   - Extract only reversible characters (letters/digits if preserving punctuation)
     *   - Track case pattern at each position separately before reversal
     *   - Reverse reversible chars, reapply position-based case pattern, rebuild with punctuation in place
     * This teaches separation of concerns and data structure thinking.
     */
    public static String reverse(String x, boolean shouldPreserveCasing, 
                                 boolean shouldPreservePunctuation){
        // Step 1: Identify which positions are reversible vs. fixed
        java.util.List<Integer> reversiblePositions = new java.util.ArrayList<>();
        java.util.List<Character> reversibles = new java.util.ArrayList<>();
        
        for(int i = 0; i < x.length(); i++){
            char c = x.charAt(i);
            if(!shouldPreservePunctuation || Character.isLetterOrDigit(c)){
                reversiblePositions.add(i);
                reversibles.add(c);
            }
        }
        
        // Step 2: Extract case pattern at each reversible position (before reversal)
        boolean[] casePattern = null;
        if(shouldPreserveCasing){
            casePattern = new boolean[reversibles.size()];
            for(int i = 0; i < reversibles.size(); i++){
                casePattern[i] = Character.isUpperCase(reversibles.get(i));
            }
        }
        
        // Step 3: Reverse the reversible characters
        Collections.reverse(reversibles);
        
        // Step 4: Reapply case pattern if needed (position-based: pattern[i] governs char at position i)
        if(shouldPreserveCasing){
            java.util.List<Character> caseAdjusted = new java.util.ArrayList<>();
            for(int i = 0; i < reversibles.size(); i++){
                char c = reversibles.get(i);
                if(casePattern[i]){
                    // Position was uppercase, make this char uppercase
                    caseAdjusted.add(Character.toUpperCase(c));
                } else {
                    // Position was lowercase, make this char lowercase
                    caseAdjusted.add(Character.toLowerCase(c));
                }
            }
            reversibles = caseAdjusted;
        }
        
        // Step 5: Rebuild with punctuation in original positions
        StringBuilder result = new StringBuilder(x);
        for(int i = 0; i < reversiblePositions.size(); i++){
            result.setCharAt(reversiblePositions.get(i), reversibles.get(i));
        }
        
        return result.toString();
    }//end reverse

    /**
     * Reverses each space-separated word in a phrase while maintaining 
     * case and punctuation patterns on each individual word.
     * 
     * @param phrase the input phrase with space-separated words
     * @return a phrase where each word is individually reversed with case/punctuation preserved
     * 
     * @example
     *   reverseWordsInPhrase("hello world")           // "olleh dlrow"
     *   reverseWordsInPhrase("Hello World")           // "OlleH DlroW"
     *   reverseWordsInPhrase("Yes, I'll be there!")   // "Sey, l'li eb ereth!"
     *   reverseWordsInPhrase("don't")                 // "t'nod"
     *   reverseWordsInPhrase("A B C")                 // "A B C" (single chars reverse to themselves)
     * 
     * @see #reverse(String, boolean, boolean)
     * 
     * IMPLEMENTATION NOTE: This method is a convenience wrapper that composes reverse()
     * with both preservation flags set to true. It demonstrates method composition:
     * a low-level tool (reverse with options) becomes a higher-level operation
     * (phrase-level word reversal). Students can see how utilities build on each other
     * for more specialized use cases.
     */
    public static String reverseWordsInPhrase(String phrase){
        String[] words = phrase.split(" ");
        for(int i = 0; i < words.length; i++){
            words[i] = reverse(words[i], true, true);
        }
        return String.join(" ", words);
    }//end reverseWordsInPhrase

    /**
     * Removes vowels from a string.
     *
     * PARAMETERS:
     * - x: The input String to process
     * - shouldIncludeY: If true, 'y' and 'Y' are also treated as vowels; if false, only a,e,i,o,u (and uppercase versions) are removed
     *
     * RETURNS:
     * A new String with all vowels (and optionally 'y') removed from the input.
     *
     * EXAMPLES:
     * - disemvowel("Hello World", false)  → "Hll Wrld"
     * - disemvowel("Hello World", true)   → "Hll Wrld"
     * - disemvowel("rhythm", false)       → "rhythm"
     * - disemvowel("rhythm", true)        → "rthm"
     * - disemvowel("Beautiful", false)    → "Btfl"
     * - disemvowel("Beautiful", true)     → "Btfl"
     *
     * TEACHING NOTES:
     * This method demonstrates:
     * 1. Character-by-character iteration through a String using charAt()
     * 2. Use of Character wrapper class methods (Character.isLetter())
     * 3. Conditional logic to identify and filter vowels
     * 4. String concatenation with StringBuilder pattern for efficiency
     * 5. The linguistic/linguistic edge case of 'y' as a sometimes-vowel
     * This is useful for word games, text processing, and understanding how
     * to selectively transform string contents based on complex criteria.
     */
    public static String disemvowel(String x, boolean shouldIncludeY){
        String vowels = "aeiouAEIOU";
        if(shouldIncludeY){
            vowels = "aeiouyAEIOUY";
        }
        
        String result = "";
        for(int i = 0; i < x.length(); i++){
            char ch = x.charAt(i);
            if(vowels.indexOf(ch) < 0){  // Character is NOT a vowel
                result += ch;
            }
        }
        return result;
    }//end disemvowel

    // ═══════════════════════════════════════════════════════════════════════════════
    // METHOD 15: scrambleVowelsIn(String x, int seed)
    // ═══════════════════════════════════════════════════════════════════════════════
    /**
     * Scrambles the vowels within a string while preserving consonant positions.
     * Uses a seeded random number generator for reproducible results.
     *
     * @param x The string whose vowels will be scrambled
     * @param seed The seed for the Random number generator. Use 0 for clock-based seeding (non-reproducible);
     *             use any non-zero value for reproducible scrambling
     * @return A new string with vowels scrambled (consonants in original positions)
     *
     * @example scrambleVowelsIn("computer", 42) → "cempotur" (vowels o,u,e rearranged)
         * @example scrambleVowelsIn("Hello", 42) → "Holle" or similar (e,o rearranged, case at positions 0 stays uppercase)
         * @example scrambleVowelsIn("APPLE", 42) → "EPPLA" or similar (A,E at positions 0,4 rearranged, case pattern preserved)
     * @example scrambleVowelsIn("strength", 42) → "strength" (no vowels to scramble)
     * @example scrambleVowelsIn("aeiou", 42) → "oieau" or similar (all vowels)
     * @example scrambleVowelsIn("book", 42) → "book" (both vowels are 'o', no change)
     *
     * @note Algorithm:
     *       1. Extract all vowels from the string and their positions
     *       2. If fewer than 2 distinct vowels (or fewer than 2 vowels total), return original string
     *       3. Create a seeded Random generator (seed=0 means System.currentTimeMillis())
     *       4. Shuffle the vowel list using Fisher-Yates shuffle
     *       5. Reconstruct the string with vowels in new positions
     *
     * @note Edge cases:
     *       - No vowels: returns original string unchanged
     *       - One vowel: returns original string unchanged
     *       - All vowels the same: returns original string unchanged (no permutation visible)
     *       - Preserves case: uppercase vowels stay uppercase, lowercase stay lowercase
     *
     * @note Pedagogical focus:
     *       - Use of Java's Random class with seeding
     *       - Fisher-Yates shuffle algorithm for unbiased randomization
     *       - Character position tracking and string reconstruction
     *       - Vowel identification and extraction
     *       - Conditional logic based on vowel count
     */
    public static String scrambleVowelsIn(String x, int seed){
        String vowels = "aeiouAEIOU";
        java.util.List<Character> vowelList = new java.util.ArrayList<>();
        java.util.List<Integer> positions = new java.util.ArrayList<>();
        java.util.List<Boolean> casePattern = new java.util.ArrayList<>();

        // Extract vowels, their positions, and case pattern
        for(int i = 0; i < x.length(); i++){
            char ch = x.charAt(i);
            if(vowels.indexOf(ch) >= 0){
                vowelList.add(Character.toLowerCase(ch));
                positions.add(i);
                casePattern.add(Character.isUpperCase(ch));
            }
        }

        // If fewer than 2 vowels, return original
        if(vowelList.size() < 2){
            return x;
        }

        // Check if all vowels are the same (case-insensitive)
        char firstVowel = vowelList.get(0);
        boolean allSame = true;
        for(char v : vowelList){
            if(v != firstVowel){
                allSame = false;
                break;
            }
        }
        if(allSame){
            return x;
        }

        // Create seeded Random generator
        java.util.Random rng = (seed == 0) ? new java.util.Random() : new java.util.Random(seed);

        // Keep the original vowel list to compare against shuffled result
        java.util.List<Character> originalVowels = new java.util.ArrayList<>(vowelList);

        // Fisher-Yates shuffle with retry: keep shuffling until we get a different arrangement
        // Maximum 100 retries to avoid infinite loops on edge cases
        int maxRetries = 100;
        int retries = 0;
        boolean isSame = true;
        
        while(isSame && retries < maxRetries){
            // Fisher-Yates shuffle on vowel list
            for(int i = vowelList.size() - 1; i > 0; i--){
                int j = rng.nextInt(i + 1);
                // Swap vowels
                char temp = vowelList.get(i);
                vowelList.set(i, vowelList.get(j));
                vowelList.set(j, temp);
            }
            
            // Check if the shuffled result is different from original
            isSame = true;
            for(int i = 0; i < vowelList.size(); i++){
                if(vowelList.get(i) != originalVowels.get(i)){
                    isSame = false;
                    break;
                }
            }
            
            // If same, reset and try again
            if(isSame){
                vowelList = new java.util.ArrayList<>(originalVowels);
                retries++;
            }
        }

        // If still same after retries (should be extremely rare), return original
        if(isSame){
            return x;
        }

        // Reconstruct string with shuffled vowels and original case pattern
        char[] result = x.toCharArray();
        for(int i = 0; i < positions.size(); i++){
            char vowel = vowelList.get(i);
            if(casePattern.get(i)){
                vowel = Character.toUpperCase(vowel);
            }
            result[positions.get(i)] = vowel;
        }

        return new String(result);
    }//end scrambleVowelsIn

    public static String scrambleVowelsIn0(String x, int seed){
        String vowels = "aeiouAEIOU";
        java.util.List<Character> vowelList = new java.util.ArrayList<>();
        java.util.List<Integer> positions = new java.util.ArrayList<>();
        java.util.List<Boolean> casePattern = new java.util.ArrayList<>();

        // Extract vowels, their positions, and case pattern
        for(int i = 0; i < x.length(); i++){
            char ch = x.charAt(i);
            if(vowels.indexOf(ch) >= 0){
                vowelList.add(Character.toLowerCase(ch));
                positions.add(i);
                casePattern.add(Character.isUpperCase(ch));
            }
        }

        // If fewer than 2 vowels, return original
        if(vowelList.size() < 2){
            return x;
        }

        // Check if all vowels are the same (case-insensitive)
        char firstVowel = vowelList.get(0);
        boolean allSame = true;
        for(char v : vowelList){
            if(v != firstVowel){
                allSame = false;
                break;
            }
        }
        if(allSame){
            return x;
        }

        // Create seeded Random generator
        java.util.Random rng = (seed == 0) ? new java.util.Random() : new java.util.Random(seed);

        // Fisher-Yates shuffle on vowel list (case pattern stays in original position order)
        for(int i = vowelList.size() - 1; i > 0; i--){
            int j = rng.nextInt(i + 1);
            // Swap vowels only (not case patterns)
            char temp = vowelList.get(i);
            vowelList.set(i, vowelList.get(j));
            vowelList.set(j, temp);
        }

        // Reconstruct string with shuffled vowels and original case pattern
        char[] result = x.toCharArray();
        for(int i = 0; i < positions.size(); i++){
            char vowel = vowelList.get(i);
            if(casePattern.get(i)){
                vowel = Character.toUpperCase(vowel);
            }
            result[positions.get(i)] = vowel;
        }

        return new String(result);
    }//end scrambleVowelsIn0

    // ═══════════════════════════════════════════════════════════════════════════════
    // METHOD 16: scrambleWordVowelsInPhrase(String phrase, int seed)
    // ═══════════════════════════════════════════════════════════════════════════════
    /**
     * Scrambles the vowels in each word of a space-separated phrase independently.
     * A convenience wrapper around scrambleVowelsIn() that demonstrates method composition.
     * Uses the same seed for all words to ensure reproducibility across the entire phrase.
     *
     * @param phrase The input phrase with space-separated words
     * @param seed The seed for the Random number generator (0 = clock-based, non-zero = reproducible)
     * @return A phrase where each word has its vowels independently scrambled
     *
     * @example scrambleWordVowelsInPhrase("hello world", 42) → "hollo world" or similar (hello has e,o which shuffle; world has only o so unchanged)
     * @example scrambleWordVowelsInPhrase("the random number generator", 42) → "the rondam nembur ganoreter"
     * @example scrambleWordVowelsInPhrase("computer", 42) → "cempotur" (single word treated as phrase)
     *
     * @note Algorithm:
     *       1. Split phrase by spaces into words
     *       2. For each word, call scrambleVowelsIn(word, seed) with the SAME seed
     *       3. Join the scrambled words back with spaces
     *
     * @note Important: All words use the SAME seed for reproducibility across the phrase.
     *       This means scrambleWordVowelsInPhrase("hello world", 42) will produce
     *       consistent results when called multiple times with seed 42.
     *
     * @note Pedagogical focus:
     *       - Method composition and wrapper methods
     *       - DRY principle: reusing scrambleVowelsIn() logic
     *       - Phrase-level orchestration
     *       - Understanding that the same seed applied to different inputs produces
     *         reproducible but potentially different outputs for each word
     */
    public static String scrambleWordVowelsInPhrase(String phrase, int seed){
        String[] words = phrase.split(" ");
        for(int i = 0; i < words.length; i++){
            words[i] = scrambleVowelsIn(words[i], seed);
        }
        return String.join(" ", words);
    }//end scrambleWordVowelsInPhrase

    /**
     * Prints a phrase across multiple lines, breaking at word boundaries
     * when single-line output would exceed maxLineLength characters.
     * Uses a greedy line-building algorithm: fit as many words as possible
     * on each line without exceeding the limit.
     *
     * @param phrase the text to print
     * @param maxLineLength the maximum number of characters per line
     *
     * @example
     *   printPhraseWrapped("The quick brown fox jumps over the lazy dog", 20);
     *   // Output (on separate lines):
     *   // The quick brown fox
     *   // jumps over the lazy
     *   // dog
     *
     * @example
     *   printPhraseWrapped("Hello world", 20);
     *   // Output: Hello world (fits on one line)
     *
     * @example
     *   printPhraseWrapped("supercalifragilisticexpialidocious", 20);
     *   // Output: supercalifragilisticexpialidocious (long word on its own line)
     *
     * @note Algorithm: Greedy line building. This is pragmatic, not optimal.
     *       A perfect typesetting algorithm (like Knuth-Plass) would minimize
     *       line-length variance, but would be complex and slow. For most use cases,
     *       greedy word-wrapping is better: simple, fast, readable.
     *
     * @note Lines will vary in length (all under maxLineLength) because we respect
     *       word boundaries. Perfect uniformity isn't possible without breaking words,
     *       which would be awkward and unreadable.
     *
     * @note Pedagogical focus:
     *       - Pragmatism in algorithm design
     *       - Greedy algorithms and their trade-offs
     *       - Tokenization and line-based processing
     *       - Output formatting for readability
     */
    public static void printPhraseWrapped(String phrase, int maxLineLength){
        if(phrase == null || phrase.isEmpty()){
            return;
        }

        String[] tokens = phrase.split("\\s+");
        StringBuilder currentLine = new StringBuilder();

        for(int i = 0; i < tokens.length; i++){
            String token = tokens[i];

            // Check if adding this token would exceed maxLineLength
            int potentialLength = currentLine.length() + (currentLine.length() > 0 ? 1 : 0) + token.length();

            if(potentialLength <= maxLineLength){
                // Add to current line
                if(currentLine.length() > 0){
                    currentLine.append(" ");
                }
                currentLine.append(token);
            } else {
                // Current line would overflow; print it and start a new line
                if(currentLine.length() > 0){
                    System.out.println(currentLine.toString());
                }
                currentLine = new StringBuilder(token);
            }
        }

        // Print any remaining content
        if(currentLine.length() > 0){
            System.out.println(currentLine.toString());
        }
    }//end printPhraseWrapped

    /**
     * Creates a decorated heading string by surrounding a title with repeated symbols.
     * Uses method composition with charString() to generate the decorative borders,
     * demonstrating how utilities can build on each other.
     *
     * @param symbol the character to repeat for decoration
     * @param num the number of repetitions on each side
     * @param title the heading text
     * @return a formatted heading string with decoration on both sides
     *
     * @example
     *   createHeading('=', 5, "Main Menu")
     *   // Returns: "===== Main Menu ====="
     *
     * @example
     *   createHeading('*', 3, "Chapter 1")
     *   // Returns: "*** Chapter 1 ***"
     *
     * @example
     *   createHeading('-', 10, "Results")
     *   // Returns: "---------- Results ----------"
     *
     * @example
     *   createHeading(' ', 5, "Title")
     *   // Returns: "          Title          " (spaces as decoration!)
     *
     * @see #charString(char, int)
     *
     * @note Method Composition: This method demonstrates building on existing utilities
     *       rather than reimplementing. charString() is low-level (repeat a char);
     *       createHeading() is higher-level (create a formatted heading). By composing
     *       them, we follow DRY (Don't Repeat Yourself) principle.
     *
     * @note Benefits of Composition:
     *       - Any improvement to charString() automatically improves createHeading()
     *       - Code is more maintainable: one place to change "repeat a character"
     *       - Utilities can be hierarchical: low-level + low-level = mid-level + mid-level = high-level
     *       - Demonstrates scaling principles in API design
     *
     * @note Pedagogical focus:
     *       - Method composition and building blocks
     *       - DRY principle: leveraging existing utilities
     *       - API design through parameter flexibility
     *       - Creating specialized tools from generic ones
     */
    public static String createHeading(char symbol, int num, String title){
        String decoration = TNTStringManip.charString(symbol, num);
        return decoration + " " + title + " " + decoration;
    }//end createHeading

}//end TNTStringManip class
