Sum of the digits of n is substring of n

From Rosetta Code
Sum of the digits of n is substring of n is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

Find and show numbers n with property that the sum of the digits of n is substring of n, where n < 1000

Factor

Works with: Factor version 0.99 2021-02-05

<lang factor>USING: grouping kernel math.text.utils present prettyprint sequences ;

1000 <iota> [ [ 1 digit-groups sum present ] [ present ] bi subseq? ] filter 8 group simple-table.</lang>

Output:
0   1   2   3   4   5   6   7
8   9   10  20  30  40  50  60
70  80  90  100 109 119 129 139
149 159 169 179 189 199 200 300
400 500 600 700 800 900 910 911
912 913 914 915 916 917 918 919

FreeBASIC

<lang freebasic>function is_substring( s as string, j as string ) as boolean

   dim as integer nj = len(j), ns = len(s)
   for i as integer = 1 to ns - nj + 1
       if mid(s,i,nj) = j then return true
   next i
   return false

end function

function sumdig( byval n as integer ) as integer

   dim as integer sum
   do
       sum += n mod 10
       n \= 10
   loop until n = 0
   return sum

end function

for i as uinteger = 0 to 999

   if is_substring( str(i), str(sumdig(i))) then print i;" ";

next i : print : end</lang>

Output:
0 1 2 3 4 5 6 7 8 9 10 20 30 40 50 60 70 80 90 100 109 119 129 139 149 159 169 179 189 199 200 300 400 500 600 700 800 900 910 911 912 913 914 915 916 917 918 919


Go

Translation of: Wren
Library: Go-rcu

<lang go>package main

import (

   "fmt"
   "rcu"
   "strings"

)

func main() {

   var numbers []int
   for n := 0; n < 1000; n++ {
       ns := fmt.Sprintf("%d", n)
       ds := fmt.Sprintf("%d", rcu.DigitSum(n, 10))
       if strings.Contains(ns, ds) {
           numbers = append(numbers, n)
       }
   }
   fmt.Println("Numbers under 1,000 whose sum of digits is a substring of themselves:")
   rcu.PrintTable(numbers, 8, 3, false)
   fmt.Println()
   fmt.Println(len(numbers), "such numbers found.")

}</lang>

Output:
Numbers under 1,000 whose sum of digits is a substring of themselves:
  0   1   2   3   4   5   6   7 
  8   9  10  20  30  40  50  60 
 70  80  90 100 109 119 129 139 
149 159 169 179 189 199 200 300 
400 500 600 700 800 900 910 911 
912 913 914 915 916 917 918 919 

48 such numbers found.

Julia

<lang julia>issumsub(n, base=10) = occursin(string(sum(digits(n, base=base)), base=base), string(n, base=base))

foreach(p -> print(rpad(p[2], 4), p[1] % 10 == 0 ? "\n" : ""), enumerate(filter(issumsub, 0:999)))

</lang>

Output:
0   1   2   3   4   5   6   7   8   9
10  20  30  40  50  60  70  80  90  100
109 119 129 139 149 159 169 179 189 199
200 300 400 500 600 700 800 900 910 911
912 913 914 915 916 917 918 919

Python

Just using the command line:

<lang python>Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)] >>> len(x) 48 >>> for i in range(0, len(x), (stride:= 10)): print(str(x[i:i+stride])[1:-1])

0, 1, 2, 3, 4, 5, 6, 7, 8, 9 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 109, 119, 129, 139, 149, 159, 169, 179, 189, 199 200, 300, 400, 500, 600, 700, 800, 900, 910, 911 912, 913, 914, 915, 916, 917, 918, 919 >>> </lang>


or as a full script, taking an alternative route, and slightly reducing the number of str conversions required:

<lang python>Sum of the digits of n is substring of n

from functools import reduce


  1. digitSumIsSubString :: String -> Bool

def digitSumIsSubString(s):

   True if the sum of the decimal digits in s
      matches any contiguous substring of s.
   
   return str(
       reduce(lambda a, c: a + int(c), s, 0)
   ) in s


  1. ------------------------- TEST -------------------------
  2. main :: IO ()

def main():

   Matches in [0..999]
   limit = 1000
   xs = list(
       filter(
           digitSumIsSubString,
           (str(n) for n in range(0, limit))
       )
   )
   w = len(xs[-1])
   print(f'{len(xs)} matches < {limit}:\n')
   print(
       '\n'.join(
           ' '.join(cell.rjust(w, ' ') for cell in row)
           for row in chunksOf(10)(xs)
       )
   )


  1. ----------------------- GENERIC ------------------------
  1. chunksOf :: Int -> [a] -> a

def chunksOf(n):

   A series of lists of length n, subdividing the
      contents of xs. Where the length of xs is not evenly
      divible, the final list will be shorter than n.
   
   def go(xs):
       return (
           xs[i:n + i] for i in range(0, len(xs), n)
       ) if 0 < n else None
   return go


  1. MAIN ---

if __name__ == '__main__':

   main()

</lang>

Output:
48 matches < 1000:

  0   1   2   3   4   5   6   7   8   9
 10  20  30  40  50  60  70  80  90 100
109 119 129 139 149 159 169 179 189 199
200 300 400 500 600 700 800 900 910 911
912 913 914 915 916 917 918 919

Raku

<lang perl6>say "{+$_} matching numbers\n{.batch(10)».fmt('%3d').join: "\n"}" given (^1000).grep: { .contains: .comb.sum }</lang>

Output:
48 matching numbers
  0   1   2   3   4   5   6   7   8   9
 10  20  30  40  50  60  70  80  90 100
109 119 129 139 149 159 169 179 189 199
200 300 400 500 600 700 800 900 910 911
912 913 914 915 916 917 918 919

REXX

<lang rexx>/*REXX pgm finds integers whose sum of decimal digits is a substring of N, N < 1000. */ parse arg hi cols . /*obtain optional argument from the CL.*/ if hi== | hi=="," then hi= 1000 /*Not specified? Then use the default.*/ if cols== | cols=="," then cols= 10 /* " " " " " " */ w= 10 /*width of a number in any column. */ @sdsN= ' integers whose sum of decimal digis of N is a substring of N, where N < ' ,

                                                                          commas(hi)

if cols>0 then say ' index │'center(@sdsN, 1 + cols*(w+1) ) if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─') finds= 0; idx= 1 /*initialize # of found numbers & index*/ $= /*a list of found integers (so far). */

    do j=0  for hi;     #= sumDigs(j)           /*obtain sum of the decimal digits of J*/
    if pos(#, j)==0     then iterate            /*Sum of dec. digs in J?  No, then skip*/
    finds= finds + 1                            /*bump the number of found integers.   */
    if cols==0          then iterate            /*Build the list  (to be shown later)? */
    $= $  right( commas( commas(j) ),  w)       /*add a found number ──► the  $  list. */
    if finds//cols\==0  then iterate            /*have we populated a line of output?  */
    say center(idx, 7)'│'  substr($, 2);   $=   /*display what we have so far  (cols). */
    idx= idx + cols                             /*bump the  index  count for the output*/
    end   /*j*/

if $\== then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/ if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─') say say 'Found ' commas(finds) @sdsN exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? sumDigs:procedure; parse arg x 1 s 2;do j=2 for length(x)-1;s=s+substr(x,j,1);end;return s</lang>

output   when using the default inputs:
 index │              integers whose sum of decimal digis of  N  is a substring of  N,  where  N  <  1,000
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────
   1   │          0          1          2          3          4          5          6          7          8          9
  11   │         10         20         30         40         50         60         70         80         90        100
  21   │        109        119        129        139        149        159        169        179        189        199
  31   │        200        300        400        500        600        700        800        900        910        911
  41   │        912        913        914        915        916        917        918        919
───────┴───────────────────────────────────────────────────────────────────────────────────────────────────────────────

Found  48  integers whose sum of decimal digis of  N  is a substring of  N,  where  N  <  1,000

Ring

<lang ring> load "stdlib.ring" see "working..." + nl see "Numbers n with property that the sum of the digits of n is substring of n are:" + nl see "p p+2 p+6" + nl row = 0 limit = 1000

for n = 0 to limit-1

   str = 0
   strn = string(n)
   for m = 1 to len(strn)
       str = str + number(strn[m])        
   next
   str = string(str)
   ind = substr(strn,str)
   if ind > 0
      row = row + 1
      see "" + n + " "
      if row%10 = 0
         see nl
      ok
   ok

next

see nl + "Found " + row + " numbers" + nl see "done..." + nl </lang>

Output:
working...
Numbers n with property that the sum of the digits of n is substring of n are:
0 1 2 3 4 5 6 7 8 9 
10 20 30 40 50 60 70 80 90 100 
109 119 129 139 149 159 169 179 189 199 
200 300 400 500 600 700 800 900 910 911 
912 913 914 915 916 917 918 919 
Found 48 numbers
done...

Wren

Library: Wren-math
Library: Wren-seq
Library: Wren-fmt

<lang ecmascript>import "/math" for Int import "/seq" for Lst import "/fmt" for Fmt

var numbers = [] for (n in 0..999) {

   var ns = n.toString
   var ds = Int.digitSum(n).toString
   if (ns.contains(ds)) numbers.add(n)

} System.print("Numbers under 1,000 whose sum of digits is a substring of themselves:") for (chunk in Lst.chunks(numbers, 8)) Fmt.print("$3d", chunk) System.print("\n%(numbers.count) such numbers found.")</lang>

Output:
Numbers under 1,000 whose sum of digits is a substring of themselves:
  0   1   2   3   4   5   6   7
  8   9  10  20  30  40  50  60
 70  80  90 100 109 119 129 139
149 159 169 179 189 199 200 300
400 500 600 700 800 900 910 911
912 913 914 915 916 917 918 919

48 such numbers found.