Vasily Guzov 1 year ago
parent 022f89a537
commit 120eccaa4b

@ -0,0 +1,36 @@
import { describe, it, expect } from "vitest";
import { compress } from "./compress.ts";
describe("compress", () => {
it(`["a", "a", "b", "b", "c", "c", "c"] => a2b2c3 => 6`, () => {
const arr = ["a", "a", "b", "b", "c", "c", "c"];
expect(compress(arr)).toBe(6);
});
it(`["a"] => a => 1`, () => {
const arr = ["a"];
expect(compress(arr)).toBe(1);
});
it(`["a","b","b","b","b","b","b","b","b","b","b","b","b"] => ab12 => 4`, () => {
const arr = ["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"];
expect(compress(arr)).toBe(4);
});
it(`["a","a","a","b","b","a","a"] => a3b2a2 => 6`, () => {
const arr = ["a", "a", "a", "b", "b", "a", "a"];
expect(compress(arr)).toBe(6);
});
it(`["a","a","a","a","a","b"] => a5b => 3`, () => {
const arr = ["a", "a", "a", "a", "a", "b"];
expect(compress(arr)).toBe(3);
});
it(`["a","a","a","b","b","b","c","c","c"] => a3b3c3 => 6`, () => {
const arr = ["a", "a", "a", "b", "b", "b", "c", "c", "c"];
expect(compress(arr)).toBe(6);
});
});

@ -0,0 +1,70 @@
// export function compress(chars: string[]) {
// let L = 0;
// let R = 1;
// const N = chars.length;
// let result = "";
// let currentCounter = 1;
// while (L <= N && R <= N) {
// const curL = chars[L];
// const curR = chars[R];
// if (curL !== curR || curR === undefined) {
// result += curL;
// if (currentCounter > 1) {
// result += currentCounter;
// currentCounter = 1;
// }
// L = R;
// }
// if (curL === curR) {
// currentCounter++;
// }
// R++
// }
// return result.length;
// };
export function compress(chars: string[]) {
let L = 0;
let R = 1;
const N = chars.length;
let currentCounter = 1;
while (L <= N && R <= N) {
const curL = chars[L];
const curR = chars[R];
if (curL !== curR || curR === undefined) {
if (currentCounter > 1) {
[...("" + currentCounter)].forEach((item, i) => {
chars[L + 1 + i] = item;
});
currentCounter = 1;
}
L = R;
}
if (curL === curR) {
currentCounter++;
chars[R] = "";
}
R++
}
for (let [key, value] of Object.entries(chars)) {
if (value === "") {
chars.splice(+key, 1)
}
}
console.log({ chars })
return chars.filter(item => item).length;
};

@ -0,0 +1,3 @@
import { compress } from "./compress";
export default compress;
Loading…
Cancel
Save