John Meehan John Meehan - 3 years ago 131
Java Question

Finding 'distance' between elements in an array

I'm trying to solve an auto-cipher and to find the key length i need to find the 'distance' between all elements in the cipher-text.
I've found the distances between all elements in the array however i now want some way to find the frequency of each jump.
So for example, if i had a string "ababbababba" and wanted to work with a's, the frequency of jumps of 1 is 2 and the frequency of jumps of 2 is 2.

for(int i = 1; i<cipher2.length(); i++ ){
if(cipher2Array[i] == 'f') {
arrayList.add(i);
int jumpDistance = arrayList.get(i) - arrayList.get(i-1);
}
}


So basically from here, with my jumpDistance variable, how would I something like

if(jumpDistance == theSameinAnyOtherPlaceOfArray) {
counter++;
}


And output a type of table with jumpSize, frequency

Answer Source

You would need a HashMap<Integer, Integer>. You can store the jumpSize as a key and the corresponding frequency as value.

Yet again if you want multiple characters to be eveluated at one go, you would need a nested Map ie - a map for each character Map<Character, Map<Integer, Integer>> as suggested by @SAM.

       Map<Integer, Integer> counter = new HashMap<Integer, Integer>();
       for(int i = 1; i<cipher2.length(); i++ ){
            if(cipher2Array[i] == 'f') {
                arrayList.add(i);
                int jumpDistance = arrayList.get(i) - arrayList.get(i-1);
                Integer freq = counter.get(jumpdistance);
                freq = freq == null ? 1 : freq+1;
                counter.put(jumpDistance, freq);
            }
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download