Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to do sliding window

Tags:

java

algorithm

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();
    }
}   
like image 703
Xyz Abc Avatar asked Jul 16 '26 17:07

Xyz Abc


1 Answers

  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();
            }
        }   
    }

}
like image 70
Avijit Karmakar Avatar answered Jul 19 '26 06:07

Avijit Karmakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!