How to resolve the algorithm Self-describing numbers step by step in the Icon and Unicon programming language

Published on 12 May 2024 09:40 PM

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

Source code in the icon programming language

procedure count (test_item, str)
  result := 0
  every item := !str do 
    if test_item == item then result +:= 1
  return result
end

procedure is_self_describing (n)
  ns := string (n) # convert to a string
  every i := 1 to *ns do {
    if count (string(i-1), ns) ~= ns[i] then fail
  }
  return 1 # success
end

# generator for creating self_describing_numbers
procedure self_describing_numbers ()
  n := 1
  repeat {
    if is_self_describing(n) then suspend n
    n +:= 1
  }
end

procedure main ()
  # write the first 4 self-describing numbers
  every write (self_describing_numbers ()\4)
end


procedure is_self_describing (n)
  ns := string (n) # convert to a string
  every i := 1 to *ns do {
      if count (string(i-1), ns) ~= ns[i] then fail
      }
  return n # on success, return the self-described number
end
 
procedure self_describing_numbers ()
  suspend is_self_describing(seq())
end


  

You may also check:How to resolve the algorithm Meissel–Mertens constant step by step in the J programming language
You may also check:How to resolve the algorithm Knapsack problem/Unbounded step by step in the 360 Assembly programming language
You may also check:How to resolve the algorithm Egyptian division step by step in the Ruby programming language
You may also check:How to resolve the algorithm Abstract type step by step in the Oz programming language
You may also check:How to resolve the algorithm Sylvester's sequence step by step in the Sidef programming language