这是indexloc提供的服务,不要输入任何密码
Skip to content

4182 - Fibonacci Sequence (🎥 Video Explanation and Solution) #24324

@dimitropoulos

Description

@dimitropoulos

4182 - Fibonacci Sequence

Implementing the Fibonacci sequence in TypeScripts type system... well... this one is a bit of a brain buster. The good news is, though, that if you manage to not crash TypeScript constantly while you develop it, the solutions are pretty fun to explore. I won't fault you for just watching this one instead of trying first, haha.

🎥 Video Explanation

Release Date: 2023-03-05 19:00 UTC

Fibonacci Sequence

🔢 Code

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

type A1 = Fibonacci<1>;
type B1 = 1;
type C1 = Expect<Equal<A1, B1>>;

type A2 = Fibonacci<2>;
type B2 = 1;
type C2 = Expect<Equal<A2, B2>>;

type A3 = Fibonacci<3>;
type B3 = 2;
type C3 = Expect<Equal<A3, B3>>;

type A4 = Fibonacci<8>;
type B4 = 21;
type C4 = Expect<Equal<A4, B4>>;

// Input:  0, 1, 2, 3, 4, 5, 6,  7,  8,  9, 10, 12, ...
// Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

// ============= Your Code Here =============
type Fibonacci<
  T extends number,
  CurrentIndex extends any[] = ['🧮'],
  Prev extends any[] = [],
  Current extends any[] = ['🧮']
> =
  CurrentIndex['length'] extends T
  ? Current['length']
  : Fibonacci<
      T,
      [...CurrentIndex, '🧮'],
      Current,
      [...Prev, ...Current]
    >;

// ============== Alternatives ==============
// credit @NtsDK
type Fibonacci<
  T extends number,
  Result extends '🧮'[][] = [['🧮'], ['🧮']]
> =
  T extends 1 | 2
  ? 1
  : T extends Result['length']
    ? Result[0]['length']
    : Fibonacci<T, [
        [
          ...Result[0],
          ...Result[1]
        ],
        ...Result
      ]>;

type Fibonacci<
  T extends number,
  U extends unknown[] = ['🧮'],
  V extends unknown[] = [],
  W extends unknown[] = ['🧮']
> =
  W['length'] extends T
  ? U['length']
  : Fibonacci<
      T,
      [...U, ...V],
      U,
      ['🧮', ...W]
    >;

// credit: @ethereal-sheep
type Arrayify<N, Acc extends '🧮'[] = []> =
  Acc['length'] extends N
  ? Acc
  : Arrayify<N, ['🧮', ...Acc]>;
type Add<L, R> =
  [...Arrayify<L>, ...Arrayify<R>]['length'];
type Subtract<
  L,
  R,
  Acc extends '🧮'[] = []
> =
  L extends R
  ? Acc['length']
  : Subtract<L, Add<R, 1>, ['🧮', ...Acc]>;
type Fibonacci<T> = 
  T extends 0
  ? 0
  : T extends 1
    ? 1
    : Add<
        Fibonacci<Subtract<T, 2>>,
        Fibonacci<Subtract<T, 1>>
      >;

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    4182answerShare answers/solutions to a questionenin English

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions