'How can I add new implementation?

I have two classes. The first is the main one, the second is its implementation.

first

import java.util.Arrays;

public class DecrementingCarousel {
    int capacity;
    static int[] elements;
    int size = 0;
    boolean called;

    public DecrementingCarousel(int capacity) {
        this.capacity = capacity;
        elements = new int[capacity];
    }

    public boolean addElement(int element) {
        if (element <= 0 || elements.length == size) {
            return false;
        }
        elements[size++] = element;
        return true;
    }


    public CarouselRun run() {
        if (!called) {
            elements = Arrays.copyOf(elements, size);
            called = true;
            return new CarouselRun();
        } else {
            return null;
        }
    }
}

second

public class CarouselRun {
    int count = 0;
    int[] array = DecrementingCarousel.elements;

    public int next() {
        if (array.length == 0) {
            return -1;
        }

        if (count == array.length) {
            count = 0;
        }

        while (array[count] == 0) {
            count++;

            if (count > array.length - 1) {
                count = 0;
            }

            if (isFinished()) {
                return -1;
            }
        }

        for (int i = 1; i < array.length; i++) {
            if (array[i] == -1) {
                break;
            }
        }

        count++;
        action(count - 1);
        return array[count - 1] + 1;
    }

    public boolean isFinished() {
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        
        return sum == 0;
    }

    public void action(int index) {
        array[index]--;
    }
}

Then I have a new class, let's call it "HalvingCarousel" which extends our first class:

public class HalvingCarousel extends DecrementingCarousel {

    public HalvingCarousel(final int capacity) {
        super(capacity);
    }
    
}

what I should to do so that it does not reduce the element by one but divides it by 2. Need to apply regular integer division, discarding the remainder. For example, 5 / 2 = 2.



Solution 1:[1]

By seeing your code, it can be seen that count is type of int. So if you divide by two, you will get desired result:

int foo = 5 / 2;
System.out.println(foo); // 2

This is simple example of DividingCarousel:

public class DecrementingCarousel
{
    public int Capacity;

    public DecrementingCarousel(int capacity)
    {
        Capacity = capacity;
        Capacity -= 1;
    }
}

and:

public class DivideCarousel extends DecrementingCarousel
{
    public DivideCarousel(int capacity)
    {
        super(capacity);
        Capacity = capacity / 2;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1