src/main/java/com/thiyagu_7/adventofcode/year2021/day7/SolutionDay7Brute.java
private int findOptimalPosition(List<Integer> input, Function<Integer, Integer> computeCost) {
        int max = input.stream()
                .max(Comparator.naturalOrder())
                .orElse(0);
        int fuel = Integer.MAX_VALUE;
        for (int position = 0; position < max; position++) {
            int current = 0;
            for (int j = 0; j < input.size(); j++) {
                int dist = Math.abs(input.get(j) - position);
                current += computeCost.apply(dist);
                if (current >= fuel) {
                    break;
                }
            }
            if (current < fuel) {
                fuel = current;
            }
        }
        return fuel;
    }
/**
     * Private helper method to compute the optimal horizontal position.
     *
     * @param input       The input
     * @param computeCost function which takes the distance and returns the cost.
     * @return optimal position to align on.
     */
Private helper method to compute the optimal horizontal position.
@param input       The input
@param computeCost function which takes the distance and returns the cost.
@return optimal position to align on.
Private helper method to compute the optimal horizontal position . @param input The input @param computeCost function which takes the distance and returns the cost . @return optimal position to align on .
private int findOptimalPosition(List<Integer> input, Function<Integer, Integer> computeCost) {
        int max = input.stream()
                .max(Comparator.naturalOrder())
                .orElse(0);
        int fuel = Integer.MAX_VALUE;
        for (int position = 0; position < max; position++) {
            int current = 0;
            for (int j = 0; j < input.size(); j++) {
                int dist = Math.abs(input.get(j) - position);
                current += computeCost.apply(dist);
                if (current >= fuel) {
                    break;
                }
            }
            if (current < fuel) {
                fuel = current;
            }
        }
        return fuel;
    }
private int findOptimalPosition ( List < Integer > input , Function < Integer , Integer > computeCost ) { int max = input . stream ( ) . max ( Comparator . naturalOrder ( ) ) . orElse ( 0 ) ; int fuel = Integer . MAX_VALUE ; for ( int position = 0 ; position < max ; position ++ ) { int current = 0 ; for ( int j = 0 ; j < input . size ( ) ; j ++ ) { int dist = Math . abs ( input . get ( j ) - position ) ; current += computeCost . apply ( dist ) ; if ( current >= fuel ) { break ; } } if ( current < fuel ) { fuel = current ; } } return fuel ; }
Private helper method to compute the optimal horizontal position.
Private helper method to compute the optimal horizontal position .