Nina Hain
Nina Hain

Reputation: 41

Implementing a sliding window (java)

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)

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!

Upvotes: 1

Views: 15182

Answers (2)

Kaushik Basu
Kaushik Basu

Reputation: 1

I am hereby providing an easy and relatively simple solution. I am giving code of two java files.

The Class:

    public class Window {           
        public void getValue(int[] a, int w){   
            int t = 0;      
            for(int i=0;i<a.length;i++){
                if(i==a.length-w+1){
                    break;
                }else{
                    for(int j=i;j<i+w;j++){
                        if(t<a[j]){
                            t = a[j];
                        }
                    }
                }           
                System.out.println(t);
                t = 0;
            }
        }   
    }

The Main method:

    public class MainMethod {       
        public static void main(String[] args) {
            int[] a = new int[]{1, 3, -1, -3, 5, 3, 6, 7};
            int w = 3;
            Window ob = new Window();
            ob.getValue(a, w);
        }
    }


    Answer: 3 3 5 5 6 7

I only left checking of the length of the window should not be greater than the array.

Upvotes: 0

user4668606
user4668606

Reputation:

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.

Upvotes: 9

Related Questions