function countContiguousDistinct(k, arr) {
const res = [];
for (let i = 0; i < arr.length; i++) {
const window = [];
for (let j = i; j < k + i; j++) {
const n = arr[j];
window.push(n);
}
if (window.every(el => el !== undefined)) {
const resNum = filt(window).length;
if (resNum) res.push(resNum);
}
}
function filt(arr) {
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
return arr.filter(onlyUnique);
}
return res;
}
const arr = [2, 4, 20, 6, 0, 30, 28];
const k = 4;
console.log(countContiguousDistinct(k, arr)); // [ 4, 4, 4, 4 ]
function countContiguousDistinct(k, arr) {
const counts = [];
let distinct = 0;
const result = [];
for (let i = 0; i < k; i += 1) {
const val = arr[i];
if (counts[val] === undefined) {
counts[val] = 0;
distinct += 1;
}
counts[val] += 1;
}
result.push(distinct);
for (let i = k; i < arr.length; i += 1) {
const lVal = arr[i - k];
counts[lVal] -= 1;
if (counts[lVal] === 0) {
distinct -= 1;
}
const rVal = arr[i];
if (counts[rVal] === undefined) {
counts[rVal] = 0;
}
if (counts[rVal] === 0) {
distinct += 1;
}
counts[rVal] += 1;
result.push(distinct);
}
return result;
}
function countContiguousDistinct(k, arr) {
let cardinality = 0;
for (let i = 0; i < k; i++) {
if (i === arr.indexOf(arr[i])) cardinality++;
}
const result = [cardinality];
const isNotInWindow = (value, arr, start, finish) => {
for (let j = start; j < finish; j++) {
if (arr[j] === value) return false;
}
return true;
}
for (let i = 0; i < arr.length - k; i++) {
const L = arr[i];
const R = arr[i + k];
if (L !== R) {
if (isNotInWindow(L, arr, i + 1, i + k)) cardinality--;
if (isNotInWindow(R, arr, i + 1, i + k)) cardinality++;
}
result.push(cardinality);
}
return result;
}