Skip to content

Instantly share code, notes, and snippets.

@mukkoo
Last active February 24, 2023 14:34
Show Gist options
  • Save mukkoo/94ee8fb966a5767148e59884b102d6e2 to your computer and use it in GitHub Desktop.
Save mukkoo/94ee8fb966a5767148e59884b102d6e2 to your computer and use it in GitHub Desktop.
import _ from "lodash";
import fs from "fs";
const compareOccurrences = (occurrences) => {
let differences = 0;
for (let key of Object.keys(occurrences)) {
if (occurrences[key] !== 0) differences++;
if (differences > 1) return false;
}
if (differences === 1) return true;
return false;
};
const test = (str, minus = 1) => {
const left = str.slice(0, str.length / 2 + minus).split("");
const right = str.slice(str.length / 2 + minus).split("");
const occurrences = {};
for (let j = 0; j < left.length; j++) {
occurrences[left[j]] ? occurrences[left[j]]-- : (occurrences[left[j]] = -1);
}
for (let j = 0; j < right.length; j++) {
occurrences[right[j]]
? occurrences[right[j]]++
: (occurrences[right[j]] = 1);
if (occurrences[right[j]] > 1) return false;
}
return compareOccurrences(occurrences);
};
const isAlmostBalance = (str) => {
if (str.length % 2 == 0) return false;
return test(str, 0) || test(str, 1);
};
const data = fs
.readFileSync("perfectly_balanced_chapter_1_input.txt")
.toString()
.split("\n");
let nbWords = parseInt(data[0]);
let cursor = 1;
for (let iWord = 0; iWord < nbWords; iWord++) {
const word = data[cursor++];
const nbChecks = data[cursor++];
let nbTrue = 0;
for (let j = 0; j < nbChecks; j++) {
const [start, end] = data[cursor++].split(" ");
const subWord = word.slice(start - 1, end);
if (isAlmostBalance(subWord)) {
nbTrue++;
}
}
console.log(`Case #${iWord + 1}: ${nbTrue}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment