Java Arraylist Program Failing Test

Beanie Leung :

I am creating a program that when given a list, returns a new integer list where the first two elements remain the same, and where each element after is the median of the three elements ending in that position in the original list. For example, given the list: [1, 2, 3, 4, 5, 6, 7, 8, 9], the program would return: [1, 2, 2, 3, 4, 5, 6, 7, 8].

This is the code I've written where I'm getting the correct results, but it is failing my tester. I'm not sure if I'm missing an odd case.

Samuel Silver Moos :

Yes you missed some cases: Your code does not calculate the median if one ore more numbers are equal.

Solution whitch will work, based on your Code:

    public static List<Integer> method(List<Integer> items) {
    List<Integer> list = new ArrayList<Integer>();
    int size = items.size();
    if (size == 0) {
        list = Arrays.asList();
    } else if (size == 1) {
        int first = items.get(0);
        list.add(first);
    } else if (size == 2) {
        int first = items.get(0);
        list.add(first);
        int second = items.get(1);
        list.add(second);
    } else {
        int first = items.get(0);
        int second = items.get(1);
        list.add(first);
        list.add(second);
        for (int i = 2; i < size; i++) {
            int med;
            if (items.get(i) <= items.get(i - 1) && items.get(i) >= items.get(i - 2)
                    || items.get(i) >= items.get(i - 1) && items.get(i) <= items.get(i - 2)) {
                med = items.get(i);

            } else if (items.get(i - 1) <= items.get(i) && items.get(i - 1) >= items.get(i - 2)
                    || items.get(i - 1) >= items.get(i) && items.get(i - 1) <= items.get(i - 2)) {
                med = items.get(i - 1);
            } else {
                med = items.get(i - 2);
            }
            list.add(med);
        }
    }
    return list;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=237399&siteId=1