Sliding window

슬라이딩 윈도

Move a contiguous range while reusing its previous total.

···
html
<div class="v"><header><b>SLIDING WINDOW</b><span id="state"></span></header><main><div class="wcells" id="wcells"></div><div class="wsum" id="wsum"></div></main><footer>subtract outgoing · add incoming</footer></div>
css
.v{width:min(92vw,660px);height:min(86vh,310px);box-sizing:border-box;padding:clamp(9px,2.5vmin,18px);border:1px solid var(--line);border-radius:14px;background:var(--surface);display:flex;flex-direction:column;gap:7px;color:var(--fg);font:500 clamp(15px,4.5vmin,19px)/1.25 var(--font-sans, sans-serif)}.v header,.v footer{display:flex;justify-content:space-between;align-items:center;gap:8px;white-space:nowrap}.v header b{color:var(--accent);font-size:.9em}.v header span,.v footer{color:var(--muted);font-size:.82em}.v main{flex:1;min-height:0;position:relative;overflow:hidden}.v .mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}.v .active{background:var(--accent)!important;color:var(--bg)!important;border-color:var(--accent)!important}.v .muted{opacity:.45} .wcells{height:68%;display:flex;align-items:center;justify-content:center;gap:3px}.wcells b{flex:1;max-width:48px;height:clamp(25px,8vmin,45px);border:1px solid var(--line);border-radius:5px;display:grid;place-items:center;font:700 .85em ui-monospace,monospace}.wsum{text-align:center;color:var(--accent);font:600 .77em ui-monospace,monospace}
js
const values=[2,4,1,5,3,6],size=3;let start=0;function draw(){const slice=values.slice(start,start+size),sum=slice.reduce((a,b)=>a+b,0);document.getElementById("wcells").innerHTML=values.map((v,i)=>"<b class='"+(i>=start&&i<start+size?"active":"")+"'>"+v+"</b>").join("");document.getElementById("wsum").textContent=start?"previous − "+values[start-1]+" + "+values[start+size-1]+" = "+sum:"initial sum = "+sum;document.getElementById("state").textContent="window "+(start+1)+" / 4";start=(start+1)%4}draw();setInterval(draw,950)

A fixed-size sliding window computes its first total, then shifts right by subtracting the outgoing value and adding the incoming value. It avoids summing the whole range again.

A variable-size window moves its ends according to a condition. Rules such as expanding when a sum is too small need assumptions like nonnegative input to be correct.

When to use

Use it for repeated totals or extrema over contiguous time ranges.

Open as page ↗