Implementing a sliding window (java)

13,326

For the sliding window, the simplest would possibly be a counter for the number of the insertion. Like this:

class Window{
    int ct = 0;
    int[] storage; 

    public Window(int size){
         storage = new int[size];
    }

    public void put(int i){
         storage[ct % storage.length] = i;
         ct++;
    }
}

This way, you can use a fixed size array and replace the oldest value by newer ones as soon as the array is filled, without shifting content.

Share:
13,326
Nina Hain
Author by

Nina Hain

Java Newb, here to learn and ease assignment suffering. I like linked lists and hate self-growing arrays. A lot.

Updated on June 05, 2022

Comments

  • Nina Hain
    Nina Hain almost 2 years

    I am fairly new to java (and programming overall) and have received the task to implement a Sliding Window object from start to finish. The skeleton code is as follows:

    import java.util.Scanner;
    
    //implement class SlidingWindow
    
    class Main {
    
    // this is the test code for the judge, do not modify
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int windowSize = scanner.nextInt();
        SlidingWindow window = new SlidingWindow(windowSize);
        while (scanner.hasNextInt())
        {
            int value = scanner.nextInt();
            window.Put(value);
            System.out.println("[" + window.Min() + " " + window.Max() + "]");
        }
        scanner.close();
    }
    

    What needs to be done (and the ideas I have had so far towards solving it)

    • Create a sliding window w that can be instantiated with a window size n:

      SlidingWindow w = New SlidingWindow(n) //This is what stumps me the most - is it a self-growing array? A linked list?

    • An input method Put that accepts integer numbers and has no return value:

      public static void Put(int value){ // implementation will depend on SlidingWindow

    • A Max and Min method to return the min and max of the most recent inputs. This I will just do by looking for the min and max.

    • If the number of inputs exceeds the size of the window, the oldest element should be discarded.

    Sorry for the vagueness of the question - we never dealt with windows in class (I am a few weeks in to learning anything about coding) so I am truly stumped. I have looked around online for some resources but have not yet found anything suitable to help me.

    If you have any ideas or advice to offer on how to create SlidingWindow w, I think that will get me on the right track!

    Thanks in advance!