CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12

Hybrid View

  1. #1
    Join Date
    Jan 2018
    Location
    Java 8
    Posts
    16

    Question Counting Vowels in an array of strings

    The problem i am working on now states:

    A method named vowels that accepts a String array named alpha. The method will return the index of the
    String that contains the most vowels. If there is a tie anyone will be good.

    my method i have:

    Code:
    public class ArrayMethods2 {
    	public int vowels (String[] alpha){
    		int[] count = new int[alpha.length];
    		int max = 0;
    		
    		
    		for(int i = 0; i <alpha.length; i++){ //goes through the array to find each string
    			String temp = alpha[i]; //stores the string in a temporary place
    			temp = temp.toLowerCase(); //changes the string to lower case
    			int vowelCount = 0; //resets sum of vowels to zero
    			
    			for(int j =0; j < temp.length(); j++){ //goes through the string to find a vowel
    				if(temp.charAt(j) == 'a' ||
    					temp.charAt(j) == 'e' || 
    					temp.charAt(j) == 'i' || 
    					temp.charAt(j) == 'o' || 
    					temp.charAt(j) == 'u'){
    					count[i] = vowelCount++; //stores the amount of vowels for each string at each index
    				}
    			}
    		}
    		
    		//goes through the count array to find which index had the most vowels
    		for(int i = 0; i<count.length; i++){
    			if(count[i] > max)
    				max = i;
    			else if(count[i] == max)
    				max = i;
    		}
    		
    		return max;
    	}
    and to run it i have:

    Code:
    import java.util.Scanner;
    
    public class RunArray2{
    
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		ArrayMethods2 am2 = new ArrayMethods2();
                   
                    System.out.println("\nMethod \"vowels"+ "\"");
    		System.out.println("How many words will you like to input?");
    		int amount = scan.nextInt();
    		String[] words = new String[amount];
    		
    		System.out.println("Input your words.");
    		for (int i = 0; i < words.length; i++)
    			words[i] = scan.next();
    		
    		System.out.println("The word at index " + am2.vowels(words) + " has the most vowels" );
    	}
    }
    this is what i get as a result:

    Code:
    Method "vowels"
    How many words will you like to input?
    3
    Input your words.
    yankee
    can
    arm
    The word at index 1 has the most vowels
    it should be the word at index 0

    can someone advise me on what i did wrong?
    if i move yankee to index 1 or 2 it'll give me the right answer.
    also if i put in 2 strings for example index 0 = can, index 1 = j. It'll tell me index 0 has the most vowels

  2. #2
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Counting Vowels in an array of strings

    How are you trying to debug the code to see what it is doing?
    Add some print statements that print out the values of variables so you can see what the computer sees when it executes the code.
    Norm

  3. #3
    Join Date
    Jan 2018
    Location
    Java 8
    Posts
    16

    Re: Counting Vowels in an array of strings

    Quote Originally Posted by Norm View Post
    How are you trying to debug the code to see what it is doing?
    Add some print statements that print out the values of variables so you can see what the computer sees when it executes the code.
    i added this print statement to print out the array you input:

    Code:
    System.out.println(Arrays.toString(words));
    and i get this:

    Code:
    Method "vowels"
    How many words will you like to input?
    3
    Input your words.
    yankee
    can
    candle
    [yankee, can, candle]
    The word at index 2 has the most vowels
    so the strings are in the right indices
    Last edited by rcheeks23; February 27th, 2018 at 06:47 PM.

  4. #4
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Counting Vowels in an array of strings

    Ok that's a start. Now add print statements to print the value of temp.charAt(j) and vowelCount inside the loop
    and after the loop print the contents of the count array.
    Norm

  5. #5
    Join Date
    Jan 2018
    Location
    Java 8
    Posts
    16

    Re: Counting Vowels in an array of strings

    Quote Originally Posted by Norm View Post
    Ok that's a start. Now add print statements to print the value of temp.charAt(j) and vowelCount inside the loop
    and after the loop print the contents of the count array.
    so after doing what you told me i saw that i needed to save the vowelCount outside of the if statement. Also added a variable of char x = temp.charAt(j) to make the if statement a little cleaner. So i noticed that something is definitely wrong with my for loop.

    this is my new method with the print statements:


    Code:
    	public int vowels (String[] alpha){
    		int[] count = new int[alpha.length];
    		int max = 0;
    		
    		
    		for(int i = 0; i <alpha.length; i++){ //goes through the array to find each string
    			String temp = alpha[i]; //stores the string in a temporary place
    			temp = temp.toLowerCase(); //changes the string to lower case
    			int vowelCount = 0; //resets sum of vowels to zero
    			
    			for(int j =0; j < temp.length(); j++){ //goes through the string to find a vowel
    				char x = temp.charAt(j);
    				System.out.print(x + " ");
    				
    				if(x == 'a' ||
    					x == 'e' || 
    					x == 'i' || 
    					x == 'o' || 
    					x == 'u'){
    					vowelCount++; //stores the amount of vowels for each string at each index
    				}
    				
    				count[i] = vowelCount;
    			}
    			System.out.println("\nVowel Count = " + vowelCount);
    			System.out.println();
    		}
    		
    		System.out.print("count array: ");
    		for(int i = 0; i<count.length; i++)
    			System.out.print(count[i] + " ");
    		System.out.println("\n");
    			
    		//goes through the count array to find which index had the most vowels
    		for(int i = 0; i<count.length; i++){
    			if(count[i] > max)
    				max = i;
    		}
    		
    		return max;
    	}
    i used the same main method to run it and got this:

    Code:
     
    Method "vowels"
    How many words will you like to input?
    3
    Input your words.
    yankee
    can
    candle
    [yankee, can, candle]
    y a n k e e 
    Vowel Count = 3
    
    c a n 
    Vowel Count = 1
    
    c a n d l e 
    Vowel Count = 2
    
    count array: 3 1 2 
    
    The word at index 2 has the most vowels
    yankees at index 0 but its saying that candle has the most. Did i write my for loop that decided what index has the most wrong?
    Last edited by rcheeks23; February 27th, 2018 at 07:27 PM.

  6. #6
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Counting Vowels in an array of strings

    loop that decided what index has the most
    Add some print statements in that loop that print the value of i, max and count[i] to see what the code is doing.

    Note: For easier testing preload the Scanner's constructor with the input data:
    Code:
    		Scanner scan = new Scanner("3 yankee can arm "); //System.in);
    Norm

  7. #7
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Counting Vowels in an array of strings

    You can simply the algorithm. Basically you currently have an array (count) that you populate with the number of vowels for each of the strings in alpha. You then scan this count array (which has an issue) to find the maximum one. However, why have the array count? What you are interested in is the position in alpha with the string with the maximum vowels. So you only need 2 variables - one to hold the maximum value (eg maxval) and one to hold the index (eg maxindx) both initialised to 0. So after the inner j loop you have vowelCount (number of vowels) and i (index into alpha). You then check vowelCount against maxval. If vowelCount is greater then update maxval with vowelCount and maxindx with i. After the outer i loop then maxval contains the maximum number of vowels and maxindx contains which element of alpha contains this. No further loops are required.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  8. #8
    Join Date
    Jan 2018
    Location
    Java 8
    Posts
    16

    Talking Re: Counting Vowels in an array of strings

    Wow thank you Norm for teaching me how to test and debug better to find exactly where my issue was and thank you 2kaud for explaining a good way of fixing my problem and needing less loops!!

  9. #9
    Join Date
    Feb 2017
    Posts
    677

    Re: Counting Vowels in an array of strings

    Quote Originally Posted by rcheeks23 View Post
    and needing less loops!!
    Here's a functional version with no loops at all!

    Well of course there are loops, only they're hidden which is a big deal in the functional paradigm. I find it hard to warm up to this though. To me the cost seems awfully high in terms of increased complexity. All these crammed complex on-liners must be very hard to understand and maintain, not to mention how difficult it must be to make changes after a while even if one wrote it oneself. But I may be wrong,

    https://www.ibm.com/developerworks/l...-java8idioms1/

    After having tried out functional programming with Java 8 a little I cannot help feeling that Java seems to have put up quite a fight to resist the new functional concepts that have been imposed on it. I think maybe C++ has absorbed the functional approach more gracefully, possibly because it's been a complex language all the time. But even though Java has taken a complexity hit, Java 8 probably was necessary for Java's survival so it had to be.

    Code:
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.function.Function;
    import java.util.stream.IntStream;
    
    public class Main {
    
    	public static void main(String[] args) {
    		String[] words = {"yankee", "can", "aoooorm", "hahahaha"}; // input
    
    		// ---
    		
    		final class Pair { // number of vowels in the word at this index position 
    			Pair(int index, int vowels) {i=index; v=vowels;}
    			int index() {return i;}
    			int vowels() {return v;}
    			private int i, v;
    		}
    		
    		final Set<Character> wovelSet = // set of vowels
    			new HashSet<Character>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));		
    		
    		final Function<String, Integer> countVowels = (String word) -> // count vowels in word
    			(int)word.chars()
    			.filter(ch -> wovelSet.contains((char)ch))
    			.count();
    		
    		final Comparator<Pair> compareByWovels = (Pair o1, Pair o2) -> // which Pair has more vowels ? 
    			((Integer)o1.vowels()).compareTo((Integer)o2.vowels());
    		
    		final int maxIndex = IntStream.range(0, words.length) // find Pair with max vowels and return its index
    			.mapToObj(i -> new Pair(i, countVowels.apply(words[i])))
    			.max(compareByWovels)
    			.map(Pair::index)
    			.orElse(-1); // no input
    	
    		// ---
    		
    		if (maxIndex >=0) {
    			System.out.print("The word '" + words[maxIndex] + "'");
    			System.out.print(" at index position " + maxIndex );
    			System.out.print(" has " + countVowels.apply(words[maxIndex]) + " vowels");
    			System.out.print(" which is the largest number.");
    		} else System.out.print("Input array is empty !!!");
    		System.out.println();
    	}
    }
    I note that IntStream easily can be made parallel. The first line in the expression where IntStream is used (in the code above) would then look like this,
    Code:
    final int maxIndex = IntStream.range(0, words.length).parallel()
    For a sufficiently large input array and a sufficiently large number of processor cores the parallel version will be faster than the sequential. The complexity will be somewhere between O(log N) and O(N). The more cores the closer to O(log N) it will be. To accomplish a parallel version using traditional imperative programming it's probably best to base it on recursion. I found an implementation here,

    https://gist.github.com/pavel-mukhanov/9341630

    Even though this code looks simple you obviously need a lot of expertise to come up with it so being able to just add parallel() to something sequential and it becomes parallel definitely is a major advantage. Also C++ has developed in this direction by allowing for different execution policies of many of its standard functions/algorithms,

    http://en.cppreference.com/w/cpp/algorithm
    Last edited by wolle; March 21st, 2018 at 01:57 AM.

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Counting Vowels in an array of strings

    I find it hard to warm up to this though. To me the cost seems awfully high in terms of increased complexity. All these crammed complex on-liners must be very hard to understand and maintain, not to mention how difficult it must be to make changes after a while even if you wrote it yourself.
    Me too! I'm quite happy to stick with first-class and pure functions. For languages such as c++/java etc I still don't get the requirement for immutable functions - but maybe it's just me and my previous 45+ years of non-functional programming!
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  11. #11
    Join Date
    Aug 2017
    Posts
    36

    Re: Counting Vowels in an array of strings

    Code:
    import java.util.Scanner;
    
    public class Countingvowel {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
    
            char letter;
            String sentence = "";
            System.out.println("Enter a character for which to search");
            letter = in.next().charAt(0);
            System.out.println("Enter the string to search");
            sentence = in.next();
    
            int count = 0;
            for (int i = 0; i < sentence.length(); i++) {
                char ch = sentence.charAt(i);
                if (ch == letter) {
                    count++;
                }
            }
            System.out.printf("There are %d occurrences of %s in %s", count, letter, sentence);
    
        }
    }
    Last edited by 2kaud; April 17th, 2018 at 03:34 AM. Reason: Added code tags

  12. #12
    Join Date
    Dec 2021
    Location
    Vietnam
    Posts
    1

    Re: Counting Vowels in an array of strings

    Algorithm

    - Set counter param 0
    - Loop through string (for(int cnt = 0; cnt < str.length(); cnt++))
    - check each character with vowels in loop interation ((ch == 'a' || ch == 'e' ||
    ch == 'i' || ch == 'o' ||
    ch == 'u'))
    - if condition met increase counter param by one


    Result: Counter will print the number of vowels found in string


    The found article was written for python but can refer to more ways to implement vowel counts

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured