|
| 1 | +/** |
| 2 | + * @file Fixtures - dblLinear |
| 3 | + * @module fixtures/dblLinear |
| 4 | + * @see https://codewars.com/kata/5672682212c8ecf83e000050 |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * Consider a sequence `u` where `u` is defined as follows: |
| 9 | + * |
| 10 | + * 1. The number `u(0) = 1` is the first one in `u` |
| 11 | + * 2. For each `x` in `u`, `y = 2x + 1` and `z = 3x + 1` must be in `u` too |
| 12 | + * 3. There are no other numbers in `u` |
| 13 | + * |
| 14 | + * Given an index, `n`, the function returns the element at `u(n)`. |
| 15 | + * |
| 16 | + * @async |
| 17 | + * |
| 18 | + * @example |
| 19 | + * await dblLinear(0) // 1 |
| 20 | + * @example |
| 21 | + * await dblLinear(10) // 22 |
| 22 | + * @example |
| 23 | + * await dblLinear(100) // 447 |
| 24 | + * @example |
| 25 | + * await dblLinear(7687) // 111718 |
| 26 | + * |
| 27 | + * @param {number} n - Index of element to get |
| 28 | + * @return {Promise<number>} Element at `u(n)` |
| 29 | + */ |
| 30 | +async function dblLinear(n: number): Promise<number> { |
| 31 | + /** @const {number[]} u - Sequence */ |
| 32 | + const u: number[] = [1] |
| 33 | + |
| 34 | + /** @var {number} j - Index of x in {@linkcode u} used to calculate y */ |
| 35 | + let j: number = 0 |
| 36 | + |
| 37 | + /** @var {number} k - Index of x in {@linkcode u} used to calculate z */ |
| 38 | + let k: number = 0 |
| 39 | + |
| 40 | + /* |
| 41 | + * build sequence up to index n (inclusive) |
| 42 | + */ |
| 43 | + for (let i = 1; i <= n; i++) { |
| 44 | + /** @const {number} y - `y` */ |
| 45 | + const y: number = 2 * u[j]! + 1 |
| 46 | + |
| 47 | + /** @const {number} z - `z` */ |
| 48 | + const z: number = 3 * u[k]! + 1 |
| 49 | + |
| 50 | + /* set sequence value to smallest value in [y, z] */ |
| 51 | + u[i] = Math.min(y, z) |
| 52 | + |
| 53 | + // increase of index of x used to calculate y by 1 |
| 54 | + if (u[i] === y) j++ |
| 55 | + |
| 56 | + // increase of index of x used to calculate z by 1 |
| 57 | + if (u[i] === z) k++ |
| 58 | + } |
| 59 | + |
| 60 | + return u[n]! |
| 61 | +} |
| 62 | + |
| 63 | +export default dblLinear |
0 commit comments