Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
My sliding window algorithm
const contains = (str, t) => {
for (const c of t) {
if (!str.includes(c)) {
return false;
}
}
return true;
}
const findWindows = (size, s, t) => {
if (t.length > s.length || s.length < size) return [];
const windows = [];
for (let i = 0; i <= s.length - size; i++) {
const str = s.substr(i, size);
if (contains(str, t)) {
windows.push(str);
}
}
return windows;
}
const findAllWindows = (source, search, maxResults) => {
const s = source, t = search, k = maxResults;
const st = s.replace(/\s/g, '');
const min = t.length;
const max = st.length;
let windows = [];
for (let i = min; i <= max; i++) {
if (windows.length >= k) break;
const foundWindows = findWindows(i, st, t).filter(w => w.length > 0);
windows = windows.concat(foundWindows);
}
windows.sort((a,b) => {
return a.length < b.length;
});
return windows.slice(0, k);
}
@sebringj
Copy link
Author

sebringj commented Apr 9, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment