How to resolve the algorithm Self-describing numbers step by step in the Delphi programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Self-describing numbers step by step in the Delphi 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 Delphi programming language

Source code in the delphi programming language

{This routine would normally be in a library. It is shown here for clarity.}


procedure GetDigitsRev(N: integer; var IA: TIntegerDynArray);
{Get an array of the integers in a number}
{Numbers returned from most to least significant}
var T,I,DC: integer;
begin
DC:=Trunc(Log10(N))+1;
SetLength(IA,DC);
for I:=DC-1 downto 0 do
	begin
	T:=N mod 10;
	N:=N div 10;
	IA[I]:=T;
	end;
end;



function IsSelfDescribing(N: integer): boolean;
var IA: TIntegerDynArray;
var CA: array [0..9] of integer;
var I: integer;
begin
{Get digits, High-low order}
GetDigitsRev(N,IA);
for I:=0 to High(CA) do CA[I]:=0;
{Count number of each digit 0..9}
for I:=0 to High(IA) do
	begin
	CA[IA[I]]:=CA[IA[I]]+1;
	end;
Result:=False;
{Compare original number with counts}
for I:=0 to High(IA) do
 if IA[I]<>CA[I] then exit;
Result:=True;
end;


procedure SelfDescribingNumbers(Memo: TMemo);
var I: integer;
begin
for I:=0 to 100000000-1 do
 if IsSelfDescribing(I) then
	begin
	Memo.Lines.Add(IntToStr(I));
	end;
end;


  

You may also check:How to resolve the algorithm Classes step by step in the Oz programming language
You may also check:How to resolve the algorithm Factors of an integer step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Hex words step by step in the C++ programming language
You may also check:How to resolve the algorithm Magic squares of odd order step by step in the Raku programming language
You may also check:How to resolve the algorithm Unicode strings step by step in the 8th programming language