0

I've been helped to create a function in Swift, to count an occurrence (2 by 2, 3 by 3, 10 by 10) from an ArrayList<Double>: Swift - Group elements of Array by value (2 by 2, 3 by 3, etc...)

Now I would like to translate it in Java, but I'm not sure for several lines. How can I do that?

Swift version:

func group(_ array: [Int], coef: Int) -> [Int: Int] {
var result:[Int:Int] = [:]

var start = array[0]
var end = start + coef - 1
var arr  = array

while start <= array[array.count - 1] {
   let count = arr.filter({ $0 >= start && $0 <= end}).count

   result[start] = count
   start = end + 1
   end = start + coef - 1
   arr = Array(arr[count...])
}
return result
}

What I tried in Java:

private HashMap<Integer, Integer> group(ArrayList<Double> array, int coef, Double start) {
        Map<Integer, Integer> result = new HashMap<>();

        Double startFrom = start;
        Double end = startFrom + Double.valueOf(coef)  - 0.1;
        ArrayList<Double> arr = array;

        // This line
        while (startFrom <= array[array.size() - 1]) {

            // This line
            int count = arr.filter({ $0 >= start && $0 <= end}).count;

            // This line
            result[Int(start)] = count;
            startFrom = end + 1;
            end = start + Double.valueOf(coef)  - 0.1;
            // this line
            arr = Array(arr[count...])
        }
        return result;
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
KevinB
  • 2,454
  • 3
  • 25
  • 49

1 Answers1

0

In Java it's recommended to use interfaces instead of actual implementation as you are using, an interface provides more flexibility. If you are using implementations and you have to change something, it breaks easily, so your code will be fragile.

private static Map<Integer, Integer> group(List<Double> array, int coef, Double start) {
    Map<Integer, Integer> result = new HashMap<>();

    Double startFrom = start;
    Double finalEnd = startFrom + (double) coef - 1;

    while (startFrom <= array.get(array.size() - 1)) {
        int counter = 0;
        for (Double x : array) {
            if (x >= startFrom && x <= finalEnd) {
                counter++;
            }
        }
        result.put(startFrom.intValue(), counter);
        startFrom = finalEnd + 1;
        finalEnd = startFrom + (double) coef - 1;
    }
    return result;
}
Cristi B.
  • 651
  • 7
  • 17