How do you count the number of words that can be collected from the line? Java



  • There's a mass:

    ["anger", "awe", "joy", "love", "grief"]
    

    The user shall insert a line through Scanner which consists of a set of letters.

    The number of words from the body that can be assembled from the letter of the line introduced must be screened.

    Each letter in the line may only be used once for one word, but it may be used for another word (e.g. one letter 'е' may be used to produce 5 words from the body.

    Example of early entry through Scanner:

    "yliausoenvjw" == можно сложить 3 слова 
    "angerw" == можно сложить 2 слова
    "griefgriefgrief" ==  можно сложить 1 слово
    "abcdkasdfvkadf" == можно сложить 0 слов
    
    String[] str = {"anger", "awe", "joy", "love", "grief"};
    char[] convert;
    String input = scanner(); // Метод с вызовом сканера
    char[] letters = input.toCharArray(); // Конвертнул String в char
    

    for (int i = 0; i < str[0].length(); i++) {
    // Цикл конвертирует массив String str в массивы char
    convert = str[i].toCharArray();

    for (int j = 0; j &lt; letters.length; j++) { 
        if (letters[j] == convert[i]) {
        // Как дальше можно правильно написать цикл для подсчета и проверки совпадений букв?
        }
    }
    

    }



    1. Create a frequency map of the letters in the word inserted -- in general, it should be Map<Character, Integer>but in this case, there may be enough mass to remember the frequency of 26 English letters.
    2. To calculate the frequency of each word word in the mass str
    3. Compare frequencies, increase the word counter if all letters are frequencies word less relevant frequency in the inlet

    Implementation Option

    // метод для вычисления частот букв в слове
    static int[] getFreqMap(String word) {
        int[] freq = new int[26];
        for (char c : word.toLowerCase().toCharArray) {
            if (Character.isLetter(c)) {
                freq[c - 'a']++;
            }
        }
        return freq;
    }
    
    int[] inputFreq = getFreqMap(input);
    int count = 0;
    for (String word : str) {
        int[] wordFreq = getFreqMap(word);
        boolean ok = true;
        for (int i = 0; ok && i < inputFreq.length; i++) {
            if (wordFreq[i] > inputFreq[i]) {
                ok = false;
            }
        }
        if (ok) {
            count++;
        }
    }
    System.out.println(count);
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2