Xyz Abc
Xyz Abc

Reputation: 35

Trying to do sliding window

I am trying to print like sliding window way. I could not make it right. So, while the sliding for window size 1, it should print every element. When the sliding window is 2, it should print two consecutive elements.

0
1
2

01
12

0123

Please check this code:

for(int w = 1; w <= a.length; w++) {    
    System.out.println("Window size : " + w);
    for(int i = 0; i < a.length; i++) {
        for(int j = i; j < w; j++) {
            System.out.println(j);
        }
        System.out.println();
    }
}   

Upvotes: 3

Views: 309

Answers (2)

Avijit Karmakar
Avijit Karmakar

Reputation: 9408

  1. You have not calculated the no. of windows will be appeared for a specific window size.

  2. When you are printing the values of that window you have given the condition that j less than w. It loops for window size times or w times. So, for the window size 1, it will only print 1 element of window size 1. For window size 2 it will print 2 elements of window size 2. But there are also other elements.

Code for your pattern :

public class WindowPattern {

    public static void main(String[] args) {
        /* array of elements */
        int[] a = {0,1,2,3};
        /* window size w */
        for(int w = 1; w <= a.length; w++) { 
            System.out.println("Window size : " + w);
            /* No of elements shown of window size (n) = a.length-w+1 */
            for(int i = 0; i < a.length-w+1; i++) {
                for(int j = i; j < w+i; j++) {
                    System.out.print(a[j]);
                }
                System.out.println();
            }
        }   
    }

}

Upvotes: 6

BLUEPIXY
BLUEPIXY

Reputation: 40145

for(int w = 1; w <= a.length; w++){ 
    System.out.println("Window size : " + w);
    for(int i = 0; i < a.length - w + 1; i++){
        for(int j = i; j < i + w; j++){
                System.out.print(a[j]);
        }
        System.out.println();
    }
}   

Upvotes: 2

Related Questions