How to resolve the algorithm Range extraction step by step in the Racket programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Range extraction step by step in the Racket programming language
Table of Contents
Problem Statement
A format for expressing an ordered list of integers is to use a comma separated list of either Example The list of integers: Is accurately expressed by the range expression: (And vice-versa).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Range extraction step by step in the Racket programming language
Source code in the racket programming language
#lang racket
(define (list->ranges xs)
(define (R lo hi)
(if (= lo hi) (~a lo) (~a lo (if (= 1 (- hi lo)) "," "-") hi)))
(let loop ([xs xs] [lo #f] [hi #f] [r '()])
(cond [(null? xs) (string-join (reverse (if lo (cons (R lo hi) r) r)) ",")]
[(not hi) (loop (cdr xs) (car xs) (car xs) r)]
[(= 1 (- (car xs) hi)) (loop (cdr xs) lo (car xs) r)]
[else (loop xs #f #f (cons (R lo hi) r))])))
(list->ranges '(0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23
24 25 27 28 29 30 31 32 33 35 36 37 38 39))
;; -> "0-2,4,6-8,11,12,14-25,27-33,35-39"
You may also check:How to resolve the algorithm Convert decimal number to rational step by step in the Julia programming language
You may also check:How to resolve the algorithm Twin primes step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm I before E except after C step by step in the uBasic/4tH programming language
You may also check:How to resolve the algorithm Strip a set of characters from a string step by step in the 11l programming language
You may also check:How to resolve the algorithm Filter step by step in the Q programming language