How to resolve the algorithm Self-describing numbers step by step in the Common Lisp programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Self-describing numbers step by step in the Common Lisp programming language
Table of Contents
Problem Statement
There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example, 2020 is a four-digit self describing number:
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Self-describing numbers step by step in the Common Lisp programming language
Source code in the common programming language
(defun to-ascii (str) (mapcar #'char-code (coerce str 'list)))
(defun to-digits (n)
(mapcar #'(lambda(v) (- v 48)) (to-ascii (princ-to-string n))))
(defun count-digits (n)
(do
((counts (make-array '(10) :initial-contents '(0 0 0 0 0 0 0 0 0 0)))
(curlist (to-digits n) (cdr curlist)))
((null curlist) counts)
(setf (aref counts (car curlist)) (+ 1 (aref counts (car curlist)))))))
(defun self-described-p (n)
(if (not (numberp n))
nil
(do ((counts (count-digits n))
(ipos 0 (+ 1 ipos))
(digits (to-digits n) (cdr digits)))
((null digits) t)
(if (not (eql (car digits) (aref counts ipos))) (return nil)))))
(loop for i from 1 to 4000000 do (if (self-described-p i) (print i)))
1210
2020
21200
3211000
NIL
You may also check:How to resolve the algorithm Undefined values step by step in the Fortran programming language
You may also check:How to resolve the algorithm User input/Text step by step in the F# programming language
You may also check:How to resolve the algorithm String matching step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Sorting algorithms/Permutation sort step by step in the C programming language
You may also check:How to resolve the algorithm Special characters step by step in the Z80 Assembly programming language