4

I have a dilemma on my hands. After much trial and error, I still could not figure out this simple task.

I have one array

String [] array = {anps, anps, anps, bbo, ehllo};

I need to be able to go through the array and find duplicates and print them on the same line. Words with no duplicates should be displayed alone

The output needs to be like this

anps anps anps
bbo
ehllo

I have tried while, for loops but the logic seems impossible.

7
  • 11
    It's not impossible--hang in there. What have you tried? Commented Jun 14, 2012 at 19:55
  • One way would be using a HashMap<String, Integer>, where the key is the word, and the value is the counter. Commented Jun 14, 2012 at 19:57
  • 1
    Trust me, when I say I have tried. Its been 4 hrs since I started. I have tried using a for loop then putting an if statement inside the for loop to check if array[i]==array[i+1], but even if its equal, I can't say string+=array[i] + " " + array[i+1]; Commented Jun 14, 2012 at 19:59
  • ay pacman, its not like am a freeloader; I have tried everything but I still can't do it, I just need a little help. Commented Jun 14, 2012 at 20:01
  • Oh wow, looking at the posts here we are getting a worrying number of incorrect answers. Commented Jun 14, 2012 at 20:05

7 Answers 7

10

Okay, there are a worryingly number of either wrong answers or answers that use HashMap or HashSet for this very simple iteration problem, so here is a correct solution.

Arrays.sort(array);

for (int i = 0; i < array.length; ++i){
    if (i+1 == array.length) {
        System.out.println(array[i]);
    } else if (array[i].equals(array[i+1])) {
        System.out.print(array[i]+" ");
    } else {
        System.out.println(array[i]);
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Good solution...easy and efficient.
Hans in the future to not muck things up too much it's best to just edit your previous answer
@KendallFrey this only works if the array is sorted, the poster didn't specify that the array started off sorted.
@NominSim my previous answer has nothing in common with my current one. I've already deleted my first answer.
Well, it depends what a, b, a should print.
|
2

Sort the array first then

for(int i = 0, i < array.length; i++){
    String temp = array[i];
    System.out.print(temp+" ");
    for(int j = i+1; j < array.length; j++){
        String temp2 = array[j];
        if(temp.compareTo(temp2) == 0){
            System.out.print(temp2+" ");
            i++;
        }
    }
    System.out.println();
}

or something similar...

7 Comments

if I do this on {a, a, a, b} I will print out a a a, a a, a, b
did you actually try it or are you assuming?
I believe you missed my i++ inside the nested for loop
haha I wasn't entirely sure about the syntax behind that...but you still missed my i++
I changed it to compareTo which is what I should have been using to begin with, correct?
|
2

There are multiple ways of achieving this.

  1. Use two for loops, one that loops through the array and picks a value and another inner loop where you go through the array (from the current index) looking for that value
  2. You could have a map that contains the words, you loop through the array and you fill out the map with the number of occurrences corresponding to the value currently fetched from the array

The second way is better. The code is something like:

Map<String, Integer> occurences = new HashMap<String, Integer>();
for(int index=0; index < array.length; index++){
       int nOcc = 1;
       if(occurences.containsKey(array[index]){
         nOcc = occurences.get(array[index]) + 1;
       }
       occurences.remove(array[index]);
       occurences.put(array[index], nOcc);
}

At this point, the map should contain all words (keys) and their corresponding number of occurrences (values)

1 Comment

if I do 1. on {a, b, a, a} I'll get the following: a a a, b, a a, a
1

If you sort the array first, then you can just check if the current index is equal to the next index (bearing in mind that you must account for IndexOutOfBounds), if they are equal do a System.out.print() if they are not equal do a System.Out.println().

String [] array = {"anps", "anps", "anps", "bbo", "ehllo"};
// If you already are assured that the strings in the array are sorted
// then the sort is not necessary. 
Arrays.sort(array);
for(int i = 0; i < array.length; i++){
    if((i+1)==array.length || !array[i].equals(array[(i+1)])){
        System.out.println(array[i]);
    } else {
        System.out.print(array[i]+" ");
    }
}

3 Comments

But what do you mean, do a system.out.print. What is your advise, should I print [i] or [i+1]?
@BobOwuor System.out.print prints the value without the line end, whereas System.out.println adds the line end. I update my answer with code that should work.
@BobOwuor What isn't it doing? This works according to the question AFAIK.
0

Complexity n^2 , just start from first value and go to the end finding the same, if you found print in one line and go to the new line, also you should delete all printed value.

Complexity nlogn + n == nlogn , merge or quick sort, and after this go to the end and pring sequenced values. There are more solutions but I think its enough for you.

Comments

0

Naive Algorithms

  • Create a Map
  • Iterate through all array
  • check if key already exist in map
  • if yes update value +1
  • if no insert
  • print the map as you want

You should be able to do what you're looking for !

Comments

0

Use below logic

import java.util.ArrayList;


public class RepeatStringPrint {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            String[] x = { "anps", "anps", "anps", "bbo", "ehllo" };
            String total[] = new String[50];
            String sTotal[] = null;
            for (int i = 0; i < x.length; i++) {
                total[i] = x[i];
            }
            for (int k = 0; k < total.length; k++) {
                int count = 0;
                if (total[k] != null) {
                    sTotal = new String[50];
                    for (int i = 0; i < total.length; i++) {
                        if (total[k] == total[i]) {
                            count++;
                            if (count <= 1) {
                                sTotal[i] = total[k];
                            }
                        }
                    }
                    if (sTotal[k] != null) {
                        for(int j=0; j<count; j++){
                            System.out.print(sTotal[k]+"\t");
                        }
                        System.out.print("\n");
                    }
                }

            }
        }
        catch (Exception e) {

        }
    }

}

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.