1

I have a char array filled by the user (arrayInput[]) with some characters, like {b, d, a, b, f, a, g, a, a, f}, and I need to create a method which returns a new char array with only the first occurrence of the character, but in the order of input. The book also says "A way to solve this problem is to create a boolean array to keep track of the characters to mantain!", but I can't imagine how the boolean array should work with the other arrays.

The main problem is that I can save in a boolean array if arrayInput contains a specific character, and even how many times, but only creating a very long ramified if-else into a for, like

    if ((arrayOutput[i] == 'A') && (arrayControl[0] = false)) {
        arrayControl[0] = true;  }

where arrayOutput is the array I want to return from the method, arrayControl[0] is the value of 'A' in my boolean array I created into the method. A = 0, B = 1, ... Z = 25, a = 26, b = 27, ... 51 = z. For every single character, uppercase and lowercase, I created a place into the array, so I could check everything, but now I can't go any further. I don't know how to save the characters on arrayOutput, how to check if a character is already on arrayOutput and if it's already there, the array passes that specific character and go to the next one.

Also please remember I'm a newbie, so I know very little about Java. Please explain yourself the best you can. Thanks in advance!

2
  • 1
    Hint for using the boolean array: Do not check for false. Instead check for true and remove the character from the array if the value is already true when you're visiting it. Commented May 26, 2015 at 17:52
  • True that! I'll save the tip on the book, thank you! Commented May 26, 2015 at 18:04

5 Answers 5

3

This could work:

public static void main(String[] args) {
    Main main = new Main();
    char[] array = {'e','a','b','a','c','d','b','d','c','e'};
    main.getCharArray(array);
}

private char[] getCharArray(char[] array) {
    String _array = "";
    for(int i = 0; i < array.length; i++) {
        if(_array.indexOf(array[i]) == -1) // check if a char already exist, if not exist then return -1
            _array = _array+array[i];      // add new char
    }
    return _array.toCharArray();
}

Output:

eabcd

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

1 Comment

Does the job but in O(n^2) other solutions offer O(n)
0
 boolean arr[26]; //considering only small letters arrive. otherwise take a larger array.
for( i=0;i<str.length;i++ )
  arr[str[i]-'a']=true;

The ones at last after the loop are true are the actual character. (all duplicates eleminated).

To take into consideration the positions,

int arr[26];
  //initialize all the array elemnts to 0
  for( i=0;i<str.length();i++ )
      if(i>=arr[str[i]-'a'])
            arr[str[i]-'a']=i+1;

//Those greater than 0 are non-duplicated characters. Their poistion of first occurence= (arr[i]-1)

EDIT: I have last used java almost a year ago. The algorithm is shown properly. Sorry for my awkward java code.

3 Comments

This does not take into consideration the order of input.
@AnindyaDutta Okay then we can instead of take an array of ints and the position can be put there.
@AnindyaDutta.: Now check my answer. Hope it helps
0

This might help. Make a separate array and store only non-duplicate characters.

char[] removeDuplicates (char[] arrayInput) {
    boolean exists[]=new boolean[26];
    char arrayOutput[] = new char[26];
    int ctr=0;
    for(int i=0; i<26; i++) {
        exists[i] = false;
    }
    for(int i=0; i<arrayInput.length; i++) {
        if(!exists[arrayInput[i]-97]) {
            exists[arrayInput[i]-97]=true;
            arrayOutput[ctr++]=arrayInput[i];
        }
    }

   return Arrays.copyOfRange(arrayOutput, 0, ctr);

}

4 Comments

In the second for, intially all values are false. Then whenever it encounters a new character, I update the position to true. 'a' represents exists[0]... z represents exists[25]. Then the next time, since it is true, the duplicate character will be skipped.
Oh. Ok. I couldn't even guess it, really. Maybe I'm missing something, but...why -97, and why !exists?
-97 because I want to put a at position 0. The Unicode value for a is 97. So to put a character 97 at position 0, I subtract 97. !exists because if the character already exists in the array, then we are definitely encountering a duplicate at this point and we must not consider it, and hence skip the loop for that character.
OH! Now I get it! And what if I don't want to use "(!exists[arrayInput[i]-97])" but another condition to say the same thing. How can I do? I need to ask this because I should use only what the book gave me, and that's an advanced level for me.
0

If you consider using of collection framework then it would be much easier. Your array of char with duplicate is arrayInput. Now put each char from it to a HashSet like this -

HashSet<Character> uniqueCharSet = new HashSet<Character>();
for(char each : arrayInput){

   uniqueCharSet.add(each);
}   

Now the HashSet uniqueCharSet will contains only the unique characters from the char array arrayInput. Note here all element in uniqueCharSet are wrapper type - Character.

You can convert the HashSet uniqueCharSet to array of Character like this -

Object[] uniqueCharArray = uniqueCharSet.toArray();

And then you can use them like this -

for(Object each : uniqueCharArray){
   Character c = (Character) each;
   System.out.println(c);
}

1 Comment

Thanks for the answer, but sadly I can't use it. I'm allowed to use only for, if-else, while, do-while, arrays, methods, and the really basics of Java. I'm at the first year of university, and that's an exercise from the chapter about Arrays.
0

Here's the method to achieve what you need:

public static void main(String[] args) {
    char[] arr= {'A','B','C','A','B'};

    HashSet<Character> hset=new HashSet<Character>();

    for(int i=0;i<arr.length;i++) {
        hset.add(arr[i]);
        }

    Object[] ObjChar=hset.toArray();

    char[] resultArr = new char[ObjChar.length];

    for(int j=0;j<ObjChar.length;j++) {

    resultArr[j]=(char) ObjChar[j];
    }

    for(char eachChar: resultArr) {

        System.out.println(eachChar);
    }
}

1 Comment

Hello, welcome to Stackoverflow! When you answer a question, you have to explain what your code do. Thank you for your contribution.

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.