package Uebungen.Uebung5;

import java.util.Scanner;
import java.lang.Character;
import java.util.Arrays;
public class Aufgabe2 {

    public static void main(String[] args){
        // initiate scanner for input
        Scanner scanner = new Scanner(System.in);
        while(true){
            userInterface();
            System.out.print("\n\n Check anoter string? [y/N]: ");
            if(scanner.nextLine().charAt(0)!='y') break;
            System.out.println();
        }
    }
    public static void userInterface() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter desired string: ");
        char[] stringAsCharArr = scanner.nextLine().toCharArray();
        char[] usedCharArr = usedChars2(stringAsCharArr);
        for(char character:usedCharArr) System.out.println(" \""+ character + "\""); // Debug
        // System.out.println(stringAsCharArr.hashCode()); // Get the hashcode of the array
    }

    public static char[] usedChars(char[] charArray){
        char[] workingArray = new char[charArray.length];
        int position = 0; // current position
        for(char currChar:charArray) {
            currChar=Character.toLowerCase(currChar); //normalize
            boolean exists=false;
            for(char targetChar:workingArray) if(targetChar==currChar) exists=true;
            if(!exists){
                workingArray[position]=currChar;
                position++;
            }
        }
        char[] targestArray = new char[position];
        for(int i=0;i<position;i++) targestArray[i] = workingArray[i];
        Arrays.sort(targestArray);
        return targestArray;
    }
    // Improved function: less code, less demanding
    public static char[] usedChars2(char[] workingArray){
        // workingArray gets an new hashcode after modifying, so its okay using it
        // now we remove all characters that occur multiple times
        // we also count how many chars we got
        int counter=0;
        for(int i=0; i<workingArray.length;i++){
            if((int)workingArray[i]!=0) {
                counter++; // found a new one -> increment counter
                // now remove all similar chars from that point till the end of the array
                for (int j = i + 1; j < workingArray.length; j++) {
                    if (workingArray[i] == workingArray[j]) workingArray[j] = (char) 0; // set the char to 	"Null character"
                }
            }
        }
        char[] targetArray = new char[counter]; // create new
        int targetPosition = 0; // initiate counter for the Target Array
        for(char currChar:workingArray){ // seek through all chars
            if((int)currChar!=0){ // if its not a null character it is a new char
                targetArray[targetPosition] = currChar; // add the current char
                targetPosition++; // we added a new char, so we need to increment for the next one
            }
        }
        return targetArray;
    }
}
