freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-53-combinatoric-sel...

2.0 KiB
Raw Blame History

id challengeType title forumTopicId
5900f3a11000cf542c50feb4 5 Problem 53: Combinatoric selections 302164

Description

There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 In combinatorics, we use the notation, 5C3 = 10. In general,

nCr = n!r!(nr)! ,where r ≤ n, n! = n×(n1)×...×3×2×1, and 0! = 1.

It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066. How many, not necessarily distinct, values of  nCr, for 1 ≤ n ≤ 100, are greater than one-million?

Instructions

Tests

tests:
  - text: <code>combinatoricSelections(1000)</code> should return 4626.
    testString: assert.strictEqual(combinatoricSelections(1000), 4626);
  - text: <code>combinatoricSelections(10000)</code> should return 4431.
    testString: assert.strictEqual(combinatoricSelections(10000), 4431);
  - text: <code>combinatoricSelections(100000)</code> should return 4255.
    testString: assert.strictEqual(combinatoricSelections(100000), 4255);
  - text: <code>combinatoricSelections(1000000)</code> should return 4075.
    testString: assert.strictEqual(combinatoricSelections(1000000), 4075);

Challenge Seed

function combinatoricSelections(limit) {
  // Good luck!
  return 1;
}

combinatoricSelections(1000000);

Solution

function combinatoricSelections(limit) {
    const factorial = n =>
        Array.apply(null, { length: n })
            .map((_, i) => i + 1)
            .reduce((p, c) => p * c, 1);

    let result = 0;
    const nMax = 100;

    for (let n = 1; n <= nMax; n++) {
        for (let r = 0; r <= n; r++) {
            if (factorial(n) / (factorial(r) * factorial(n - r)) >= limit)
                result++;
        }
    }

    return result;
}