Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const world = [["H", "H", "H"], ["H", "I", "H"], ["H", "H", "H"]];
- function getKey(x, y) { return `[${x}, ${y}]`; }
- function makePerson(status, siblings) {
- return { status, siblings, daysSinceInfected: status === "I" ? 1 : 0, }
- }
- function graphPeople(world) {
- const g = {};
- Object.defineProperties(g, {
- "infectSiblings": {
- enumerable: false,
- value: function (siblings) {
- if (this[siblings.right].status === "H") {
- this.infect(siblings.right);
- return true;
- }
- if (this[siblings.top].status === "H") {
- this.infect(siblings.top);
- return true;
- }
- if (this[siblings.left].status === "H") {
- this.infect(siblings.left);
- return true;
- }
- if (this[siblings.bottom].status === "H") {
- this.infect(siblings.bottom);
- return true;
- }
- return false;
- }
- },
- "infect": {
- enumerable: false,
- value: function (x) { this[x].status = "I"; }
- },
- "tryRecover": {
- enumerable: false,
- value: function (x) {
- this[x].daysSinceInfected++;
- if (this[x].daysSinceInfected === 3) {
- this[x].status = "R";
- }
- return this[x].siblings;
- }
- },
- "getInfected": {
- enumerable: false,
- value: function () { return Object.values(this).filter(x => x.status === "I").length }
- },
- "getRecovered": {
- enumerable: false,
- value: function () { return Object.values(this).filter(x => x.status === "R").length }
- },
- "getHealthy": {
- enumerable: false,
- value: function () { return Object.values(this).filter(x => x.status === "H").length }
- }
- })
- for (let i = 0; i < world.length; i++) {
- for (let j = 0; j < world[i].length; j++) {
- const siblings = {}
- if (world[i][j + 1])
- siblings.right = getKey(i, j + 1);
- if (world[i - 1])
- siblings.top = getKey(i - 1, j);
- if (world[i][j - 1])
- siblings.left = getKey(i, j - 1);
- if (world[i + 1])
- siblings.bottom = getKey(i + 1, j);
- g[getKey(i, j)] = makePerson(world[i][j], siblings)
- }
- }
- return new Proxy(g, {
- get(t, p) {
- if (Reflect.has(t, p)) { return Reflect.get(t, p) }
- return { status: undefined }
- }
- });
- }
- // spreads is 2 because we start from second step of infection!
- function calc(people, spreads = 2) {
- let spread = Object.keys(people)
- .filter(x => people[x].status === "I")
- .map(x => people.tryRecover(x))
- .map(x => people.infectSiblings(x))
- .indexOf(true) > -1;
- if (spread) {
- return calc(people, spreads + 1);
- }
- return {
- people,
- daysUntilStopsSpreading: spreads,
- infected: people.getInfected(),
- recovered: people.getRecovered(),
- healthy: people.getHealthy()
- }
- }
- console.log(
- calc(graphPeople(world))
- )
Advertisement
Add Comment
Please, Sign In to add comment