Task: Most frequent k chars distance




Go: package main

import (
    "fmt"
    "sort"
)

type cf struct {
    c rune
    f int
}

func reverseStr(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func indexOfCf(cfs []cf, r rune) int {
    for i, cf := range cfs {
        if cf.c == r {
            return i
        }
    }
    return -1
}

func minOf(i, j int) int {
    if i < j {
        return i
    }
    return j
}

func mostFreqKHashing(input string, k int) string {
    var cfs []cf
    for _, r := range input {
        ix := indexOfCf(cfs, r)
        if ix >= 0 {
            cfs[ix].f++
        } else {
            cfs = append(cfs, cf{r, 1})
        }
    }
    sort.SliceStable(cfs, func(i, j int) bool {
        return cfs[i].f > cfs[j].f 
    })
    acc := ""
    min := minOf(len(cfs), k)
    for _, cf := range cfs[:min] {
        acc += fmt.Sprintf("%c%c", cf.c, cf.f)
    }
    return acc
}

func mostFreqKSimilarity(input1, input2 string) int {
    similarity := 0
    runes1, runes2 := []rune(input1), []rune(input2)
    for i := 0; i < len(runes1); i += 2 {
        for j := 0; j < len(runes2); j += 2 {
            if runes1[i] == runes2[j] {
                freq1, freq2 := runes1[i+1], runes2[j+1]
                if freq1 != freq2 {
                    continue 
                }
                similarity += int(freq1)
            }
        }
    }
    return similarity
}

func mostFreqKSDF(input1, input2 string, k, maxDistance int) {
    fmt.Println("input1 :", input1)
    fmt.Println("input2 :", input2)
    s1 := mostFreqKHashing(input1, k)
    s2 := mostFreqKHashing(input2, k)
    fmt.Printf("mfkh(input1, %d) = ", k)
    for i, c := range s1 {
        if i%2 == 0 {
            fmt.Printf("%c", c)
        } else {
            fmt.Printf("%d", c)
        }
    }
    fmt.Printf("\nmfkh(input2, %d) = ", k)
    for i, c := range s2 {
        if i%2 == 0 {
            fmt.Printf("%c", c)
        } else {
            fmt.Printf("%d", c)
        }
    }
    result := maxDistance - mostFreqKSimilarity(s1, s2)
    fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result)
}

func main() {
    pairs := [][2]string{
        {"research", "seeking"},
        {"night", "nacht"},
        {"my", "a"},
        {"research", "research"},
        {"aaaaabbbb", "ababababa"},
        {"significant", "capabilities"},
    }
    for _, pair := range pairs {
        mostFreqKSDF(pair[0], pair[1], 2, 10)
    }

    s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"
    s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"
    mostFreqKSDF(s1, s2, 2, 100)
    s1 = "abracadabra12121212121abracadabra12121212121"
    s2 = reverseStr(s1)
    mostFreqKSDF(s1, s2, 2, 100)
}


Java: import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class SDF {

    
    public static HashMap<Character, Integer> countElementOcurrences(char[] array) {

        HashMap<Character, Integer> countMap = new HashMap<Character, Integer>();

        for (char element : array) {
            Integer count = countMap.get(element);
            count = (count == null) ? 1 : count + 1;
            countMap.put(element, count);
        }

        return countMap;
    }
    
    
    private static <K, V extends Comparable<? super V>>
            HashMap<K, V> descendingSortByValues(HashMap<K, V> map) { 
	List<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(map.entrySet());
	
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
		public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
		    return o2.getValue().compareTo(o1.getValue());
		}
	    });

	
	
	HashMap<K, V> sortedHashMap = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
	    sortedHashMap.put(entry.getKey(), entry.getValue());
	} 
	return sortedHashMap;
    }
    
    public static String mostOcurrencesElement(char[] array, int k) {
        HashMap<Character, Integer> countMap = countElementOcurrences(array);
        System.out.println(countMap);
        Map<Character, Integer> map = descendingSortByValues(countMap); 
        System.out.println(map);
        int i = 0;
        String output = "";
        for (Map.Entry<Character, Integer> pairs : map.entrySet()) {
	    if (i++ >= k)
		break;
            output += "" + pairs.getKey() + pairs.getValue();
        }
        return output;
    }
    
    public static int getDiff(String str1, String str2, int limit) {
        int similarity = 0;
	int k = 0;
	for (int i = 0; i < str1.length() ; i = k) {
	    k ++;
	    if (Character.isLetter(str1.charAt(i))) {
		int pos = str2.indexOf(str1.charAt(i));
				
		if (pos >= 0) {	
		    String digitStr1 = "";
		    while ( k < str1.length() && !Character.isLetter(str1.charAt(k))) {
			digitStr1 += str1.charAt(k);
			k++;
		    }
					
		    int k2 = pos+1;
		    String digitStr2 = "";
		    while (k2 < str2.length() && !Character.isLetter(str2.charAt(k2)) ) {
			digitStr2 += str2.charAt(k2);
			k2++;
		    }
					
		    similarity += Integer.parseInt(digitStr2)
			+ Integer.parseInt(digitStr1);
					
		} 
	    }
	}
	return Math.abs(limit - similarity);
    }
    
    public static int SDFfunc(String str1, String str2, int limit) {
        return getDiff(mostOcurrencesElement(str1.toCharArray(), 2), mostOcurrencesElement(str2.toCharArray(), 2), limit);
    }

    public static void main(String[] args) {
        String input1 = "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV";
        String input2 = "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG";
        System.out.println(SDF.SDFfunc(input1,input2,100));

    }

}