Monthly Archives: February 2011

Three useful or not… Java functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int heavy_decimal_count(int a, int b) {
    int result = 0;
    Hashtable<string, Double> range = new Hashtable<string, Double>();
 
    char[] number;
    double avg;
    for (int i = a; i < = b; i++) {
        number = String.valueOf(i).toCharArray();
 
        avg = 0.0;
	for(int j = 0; j < number.length; j++) {
	    avg += Integer.parseInt(String.valueOf(number[j]));
	}
 
        avg /= number.length;
	if (avg >= 7.25)
	    result++;
 
        range.put(String.copyValueOf(number), Double.valueOf(avg));
    }
 
    return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int dominator(int[] A) {
    int result = -1;
 
    Hashtable<string, Double> occurrence;
    Hashtable<integer, Hashtable<string, Double>> indexes = new Hashtable<integer, Hashtable<string, Double>>();
 
    for (int i = 0; i < A.length; i++) {
        if (indexes.containsKey(Integer.valueOf(A[i]))) {
            occurrence = indexes.get(Integer.valueOf(A[i]));
            occurrence.put("OCCURRENCES", occurrence.get("OCCURRENCES").doubleValue() + 1);
            occurrence.put("DOMINATOR", (occurrence.get("OCCURRENCES").doubleValue() + 1) / A.length);
            occurrence.put("LASTINDEX", Double.valueOf(i));
        } else {
            occurrence = new Hashtable<string, Double>();
            occurrence.put("OCCURRENCES", 1.0);
            occurrence.put("DOMINATOR", 1.0 / A.length);
            occurrence.put("LASTINDEX", Double.valueOf(i));
        }
        indexes.put(Integer.valueOf(A[i]), occurrence);
    }
 
    Iterator<hashtable<string, Double>> it = indexes.values().iterator();
    while (it.hasNext()) {
        occurrence = it.next();
	if (occurrence.get("DOMINATOR").doubleValue() > 0.5) {
            result = occurrence.get("LASTINDEX").intValue();
        }
    }
 
    return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int amplitude(int[] A) {
    int result = -1;
    int newVal = 0;
 
    for (int i = 0; i < A.length ; i++) {
        for (int j = 0; j < A.length; j++) {
            if (j == i)
                continue;
            newVal = Math.abs(A[i] - A[j]);
            if (newVal > result)
                result = newVal;
        }
    }
 
    return result;
}