How to resolve the algorithm Hailstone sequence step by step in the Racket programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Hailstone sequence step by step in the Racket programming language

Table of Contents

Problem Statement

The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:

The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.

This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):

The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Hailstone sequence step by step in the Racket programming language

Source code in the racket programming language

#lang racket

(define hailstone
  (let ([t (make-hasheq)])
    (hash-set! t 1 '(1))
    (λ(n) (hash-ref! t n
            (λ() (cons n (hailstone (if (even? n) (/ n 2) (+ (* 3 n) 1)))))))))

(define h27 (hailstone 27))
(printf "h(27) = ~s, ~s items\n"
        `(,@(take h27 4) ... ,@(take-right h27 4))
        (length h27))

(define N 100000)
(define longest
  (for/fold ([m #f]) ([i (in-range 1 (add1 N))])
    (define h (hailstone i))
    (if (and m (> (cdr m) (length h))) m (cons i (length h)))))
(printf "for x<=~s, ~s has the longest sequence with ~s items\n"
        N (car longest) (cdr longest))

  

You may also check:How to resolve the algorithm Cholesky decomposition step by step in the REXX programming language
You may also check:How to resolve the algorithm Anagrams/Deranged anagrams step by step in the Wren programming language
You may also check:How to resolve the algorithm Nested function step by step in the Free Pascal programming language
You may also check:How to resolve the algorithm Elementary cellular automaton step by step in the Action! programming language
You may also check:How to resolve the algorithm Program name step by step in the 68000 Assembly programming language