How to resolve the algorithm Hofstadter Q sequence step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Hofstadter Q sequence step by step in the OCaml programming language

Table of Contents

Problem Statement

It is defined like the Fibonacci sequence, but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.

(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Hofstadter Q sequence step by step in the OCaml programming language

Source code in the ocaml programming language

(* valid results for n in 0..119628 *)
let seq_hofstadter_q n =
  let a = Bigarray.(Array1.create int16_unsigned c_layout n) in
  let () =
    for i = 0 to pred n do
      a.{i} <- if i < 2 then 1 else a.{i - a.{pred i}} + a.{i - a.{i - 2}}
    done
  in
  Seq.init n (Bigarray.Array1.get a)

let () =
  let count_backflip (a, c) b = b, if b < a then succ c else c
  and hq = seq_hofstadter_q 100_000 in
  let () = Seq.(hq |> take 10 |> iter (Printf.printf " %u")) in
  let () = Seq.(hq |> drop 999 |> take 1 |> iter (Printf.printf "\n%u\n")) in
  hq |> Seq.fold_left count_backflip (0, 0) |> snd |> Printf.printf "%u\n"


  

You may also check:How to resolve the algorithm Ascending primes step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Inheritance/Single step by step in the Groovy programming language
You may also check:How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Palindrome detection step by step in the GAP programming language
You may also check:How to resolve the algorithm One-dimensional cellular automata step by step in the Perl programming language