0

I have a slight problem with a programme im working on, I need to be able to look through an array in Java and find the number of different duplicates in that array, for example if the array have the values 4, 6, 4 I need to be able to display:

There are: 2 words of length 1 (4 characters) 1 word of length 2 (6 characters)

What I've currently got is -

public class wordLength {

public static void main(String[] args) {

    String userInput1 = "Owen Bishop Java ";
    String [] inputArray = userInput1.split(" ");


    for (int i = 0; i < inputArray.length; i++) {
        int length = inputArray[i].length(); 
        int inputArray2 = length;
        System.out.println(inputArray2);        
    }
}

}

This currently will split the string into an array whenever there is a space, and then find and print the length of each of the words in the array, I need to show the amount of words that are the same length.
I'm really new to Java and appreciate this is probably an incredibly easy problem but any help would be hugely appreciated, thanks.

1
  • You could sort the array and then count how many times inputArray[i].length() == inputArray[i+1].length(). Commented Feb 10, 2014 at 17:26

6 Answers 6

2

Without writing the whole thing (or making use of 3rd party libraries - I note you're new to Java so let's not complicate things), I would consider the following.

Make use of a Map<Integer,Integer> which would store the number of words of a particular length. e.g. to populate:

Map<Integer, Integer> counts = new HashMap<Integer, Integer>();    
for (String word : words) {
    Integer current = counts.get(word.length());
    if (current == null) {
       current = 0;
    }
    current++;
    counts.put(word.length(), current);   
}

and then iterate through that to output the number of words per word count. Note that the above makes use of boxing.

The advantage of using a Map is that (unlike your array) you don't need to worry about empty counts (e.g. you won't have an entry if you have no words of length 5). That may/may not be an issue depending on your use case.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this one because it includes explanations, and references to the techniques used.
0

You can create an int array of length 20(or the maximum word length in English) and increase the index value before you print that value.

arr[length]++;

1 Comment

You're assuming that the language will always be English, and that the text being dealt with is comprised only of legitimate words. Neither of those assumptions is supported by the OP's statement.
0
public class wordLength {

    public static void main(String[] args) {

        String userInput1 = "Owen Bishop Java ";
        String [] inputArray = userInput1.split(" ");

        Map<Integer,Integer> wordLengths = new HashMap<Integer,Integer>();

        for (int i = 0; i < inputArray.length; i++) {
            int length = inputArray[i].length(); 
            if (wordLengths.containsKey(length))
                wordLengths.put(length, wordLengths.get(length) + 1);
            else
                wordLengths.put(length, 1);                               
        }

        for (Integer length : new TreeSet<Integer>(wordLengths.keySet()))
            System.out.println("Length: " + length + " Count: " + wordLengths.get(length));
        }
    }
}

Comments

0
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class wordLength {

public static void main(String[] args) {

String userInput1 = "Owen Bishop Java ";
String [] inputArray = userInput1.split(" ");
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();

for (int i = 0; i < inputArray.length; i++) {
    int length = inputArray[i].length(); 
    if(map.get(length)==null){
        map.put(length, 1);
    }
    else map.put(length, map.get(length)+1);
}

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    System.out.println("words of length " +pairs.getKey() + " are " + pairs.getValue());
}

}
}

The output will be:

words of length 4 are 2
words of length 6 are 1

Comments

0

The beginning of your code looks good. What you basically want to keep track of (in my understanding) is a mapping from String length to the number of times this occurred.

public class wordLength {

    public static void main(String[] args) {

        String userInput1 = "Owen Bishop Java ";
        String [] inputArray = userInput1.split(" ");
        Map<Integer, Integer> counter = new HashMap<>();   //please note that I use the 'diamond' notation here, this is for Java 1.7 and higher.

        for (int i = 0; i < inputArray.length; i++) {
            int length = inputArray[i].length(); 
            Integer num = counter.get(length);
            if (num == null) {
                num = 1;
            }
            else {
                num++;
            }
            counter.put(length, num);
            //or counter.put(length, num == null ? 1 : num++); instead of the if-else
        }

        //print the results
        for (Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println("There are " + entry.getValue() + " words with length " + entry.getKey() + ".");
        }
    }  
}

The previous submitted method of arr[length]++; does work, but uses way to many space. Say you have only words of length 20 and beyond, then the first 20 elements of this arr are useless...

Please also note that you can use the map.entrySet() method from the Map interface. It is a better coding practice to use this method than using map.keySet() and after that looking up the associated value. This saves you much look up time. (especially with large user inputs!!!)

Comments

0

I have 2 solutions for above problem

  1. Using extra space i.e. Map to store unique value. Complexity O(n) + Space(N) [N= #unique value]
  2. No extra space. Sorts the input and counts values. Complexity nLog(n) + n

First Solution

  1. Create a map to store each unique value as key and its count as value
  2. Iterate over input array
  3. If value exists as key then increment counter
  4. ELSE if value does exist in map, then put value and set counter as 1

        private static void UniqueValueUsingMap(int[] a){
            //Map with 
            // key: unique values 
            // Value: count as each value (key)
            Map<Integer, Integer> store = new HashMap<Integer, Integer>(); 
            for (int i : a) {
                Integer key = Integer.valueOf(i);
                Integer count = null;
                if(store.containsKey(key)){
                    count = store.get(key);
                }else{
                    count = 0;
                }
                count++;
                store.put(key, count);
            }       
        }
    

Second solution

  1. Sort the given Array nlog(n). All same values will be together after sort.
  2. Iterate over sorted array
  3. Maintain 2 variable i.e. previous value and counter for current value
  4. When value change, print the value/count and reset the counter

Note: : int defaults to 0 inital value. Need to add additional check for it.

        private static void CountValueUsingSort(int[] a){
            //Sort the input array
            Arrays.sort(a);

            int currentValue = 0;
            int counter =0;

            for (int curr : a) {
                if(curr != currentValue){               
                    System.out.println("Value: " + currentValue + " Count:" + counter);
                    //Reset counter
                    counter = 0;
                }
                currentValue = curr;

                //increment Count
                counter++;
            }

        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.