Search code examples
javahashmaplinkedhashmap

Mapping char array 2 by 2 character


I have a character array like XXYYXYXYXZXZXZXYXX and I want to map it to LinkedHashMap two by two characters as shown below:

public LinkedHashMap<String, Integer> convert(char[] array) {

    LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();

    int[] freq = new int[array.length];
    int i, j;

    for (i = 0; i < array.length; i+=2) {
        freq[i] = 1;
        for (j = i + 2; j < array.length; j+=2) {
            if (array[i] + array[i+1] == array[j] + array[j+1]) {
                freq[i]++;
                array[j] = '0'; //flag to check if it is already printed
                array[j+1] = '0'; //flag to check if it is already printed
            }
        }
    }

    for (i = 0; i < freq.length; i+=2) {
        if (array[i] + array[i+1] != ' ' && array[i] != '0') {                
            String dublex = ""+ array[i] + array[i+1];
            hmap.put(dublex, freq[i]);
        }
    }
    return hmap;
}

Normally it should put the following values: XX: 2 YY: 1 XY: 3 XZ: 3

But it assign the following values: XX: 2 YY: 4 XY: 3 XZ: ? not available

I am doubtful for the following lines and points:

1) I tried to use another loop value like "k" for count freq[] variable and tried to count it between 0-9 as the 18 elements are 9 two characters element: I tried to do this, but does not make sense and throws exception.

2) "0" parts added to the end of the values : I tried to add separate 0 values and check separately e.g. array[i] != '0' && array[i+1] != '0'

So, how to fix the problem?


Solution

  •     public static LinkedHashMap<String, Integer> convert(char[] array) {
            LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
    
            for (int i = 0; i < array.length - 1; i += 2) {
                map.put(array[i] + "" + array[i + 1], map.getOrDefault(array[i] + "" + array[i + 1], 0) + 1);
            }
    
            return map;
        }
    
        public static void main(String[] args) {
            System.out.println(convert("XXYYXYXYXZXZXZXYXX".toCharArray()));
        }
    

    , output

    {XX=2, YY=1, XY=3, XZ=3}