Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stairway to heaven #373

Closed
v1valasvegan opened this issue Apr 9, 2020 · 0 comments · Fixed by #388
Closed

Stairway to heaven #373

v1valasvegan opened this issue Apr 9, 2020 · 0 comments · Fixed by #388

Comments

@v1valasvegan
Copy link

v1valasvegan commented Apr 9, 2020

© Powered by Evgen Zaytsev

Stairway to heaven

Task:

100 dicks randomly spread out of 100 stairs, there can be as many dicks as you want on one step. We gotta go down these stairs.
Every time you step on a stair-step with dicks, the brat ratio increases by the number of dicks.
You can go down one or two steps at a time. Write a function to descend the stairs minimizing the brat ratio.
The function receives an array with the number of dicks on each step and returns the minimum brat index.

JS solution:

export default stairs => {
  const { length } = stairs;
  if (length === 1) return stairs[0];
  if (length === 2) return Math.min(stairs[1], stairs[0]);

  const iter = (i, acc1, acc2) => {
    if (i === length) return Math.min(acc1, acc2);
    const newAcc1 = stairs[i] + Math.min(acc1, acc2);
    return iter(i + 1, newAcc1, acc1);
  };

  return iter(2, stairs[1], stairs[0]);
};

Tests:

import calcBratIndex from "./index";

let result;

beforeEach(() => (result = []));

it("test 1s", () => {
  for (let i = 0; i < 100; i += 1) {
    result.push(1);
  }
  expect(calcBratIndex(result)).toEqual(50);
});

it("test 1s & 0s", () => {
  for (let i = 0; i < 100; i += 1) {
    const el = i % 2 === 0 ? 1 : 0;
    result.push(el);
  }
  expect(calcBratIndex(result)).toEqual(0);
});

it("short array", () => {
  result = [1, 0, 3, 5, 10, 0, 11, 1];
  while (result.length < 100) {
    result.push(0);
  }
  expect(calcBratIndex(result)).toEqual(6);
});

codesandbox:

https://codesandbox.io/s/angry-bose-jv7ct?file=/src/index.js:0-383

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant