Self-describing numbers: Difference between revisions
Content added Content deleted
(→{{header|Picat}}: Split into subsections.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 31: | Line 31: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F is_self_describing(n) |
||
V s = String(n) |
V s = String(n) |
||
R all(enumerate(Array(s)).map((i, ch) -> @s.count(String(i)) == Int(ch))) |
R all(enumerate(Array(s)).map((i, ch) -> @s.count(String(i)) == Int(ch))) |
||
print((0.<4000000).filter(x -> is_self_describing(x)))</ |
print((0.<4000000).filter(x -> is_self_describing(x)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 43: | Line 43: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">* Self-describing numbers 26/04/2020 |
||
SELFDESC CSECT |
SELFDESC CSECT |
||
USING SELFDESC,R13 base register |
USING SELFDESC,R13 base register |
||
Line 106: | Line 106: | ||
XDEC DS CL12 temp fo xdeco |
XDEC DS CL12 temp fo xdeco |
||
REGEQU |
REGEQU |
||
END SELFDESC </ |
END SELFDESC </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 116: | Line 116: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
||
procedure SelfDesc is |
procedure SelfDesc is |
||
subtype Desc_Int is Long_Integer range 0 .. 10**10-1; |
subtype Desc_Int is Long_Integer range 0 .. 10**10-1; |
||
Line 140: | Line 140: | ||
end if; |
end if; |
||
end loop; |
end loop; |
||
end SelfDesc;</ |
end SelfDesc;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1210 |
<pre>1210 |
||
Line 151: | Line 151: | ||
{{works with|ALGOL 68|Revision 1 - no extensions to language used}} |
{{works with|ALGOL 68|Revision 1 - no extensions to language used}} |
||
{{works with|ALGOL 68G|Any - tested with release 2.6.win32}} |
{{works with|ALGOL 68G|Any - tested with release 2.6.win32}} |
||
< |
<syntaxhighlight lang="algol68">BEGIN |
||
# return TRUE if number is self describing, FALSE otherwise # |
# return TRUE if number is self describing, FALSE otherwise # |
||
Line 196: | Line 196: | ||
) |
) |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 207: | Line 207: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">use AppleScript version "2.4" |
||
use framework "Foundation" |
use framework "Foundation" |
||
use scripting additions |
use scripting additions |
||
Line 400: | Line 400: | ||
set my text item delimiters to dlm |
set my text item delimiters to dlm |
||
s |
s |
||
end unlines</ |
end unlines</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1210 -> true |
<pre>1210 -> true |
||
Line 413: | Line 413: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">selfDescribing?: function [x][ |
||
digs: digits x |
digs: digits x |
||
loop.with:'i digs 'd [ |
loop.with:'i digs 'd [ |
||
Line 422: | Line 422: | ||
] |
] |
||
print select 1..22000 => selfDescribing?</ |
print select 1..22000 => selfDescribing?</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 430: | Line 430: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
Uses CountSubString: [[Count occurrences of a substring#AutoHotkey]] |
Uses CountSubString: [[Count occurrences of a substring#AutoHotkey]] |
||
< |
<syntaxhighlight lang="autohotkey">; The following directives and commands speed up execution: |
||
#NoEnv |
#NoEnv |
||
SetBatchlines -1 |
SetBatchlines -1 |
||
Line 452: | Line 452: | ||
return false |
return false |
||
return true |
return true |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>--------------------------- |
<pre>--------------------------- |
||
Line 469: | Line 469: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk"># syntax: GAWK -f SELF-DESCRIBING_NUMBERS.AWK |
||
BEGIN { |
BEGIN { |
||
for (n=1; n<=100000000; n++) { |
for (n=1; n<=100000000; n++) { |
||
Line 485: | Line 485: | ||
} |
} |
||
return(1) |
return(1) |
||
}</ |
}</syntaxhighlight> |
||
<p>output:</p> |
<p>output:</p> |
||
<pre> |
<pre> |
||
Line 496: | Line 496: | ||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
< |
<syntaxhighlight lang="qbasic">Dim x, r, b, c, n, m As Integer |
||
Dim a, d As String |
Dim a, d As String |
||
Dim v(10), w(10) As Integer |
Dim v(10), w(10) As Integer |
||
Line 519: | Line 519: | ||
Print "End" |
Print "End" |
||
sleep |
sleep |
||
end</ |
end</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> FOR N = 1 TO 5E7 |
||
IF FNselfdescribing(N) PRINT N |
IF FNselfdescribing(N) PRINT N |
||
NEXT |
NEXT |
||
Line 538: | Line 538: | ||
N% DIV=10 |
N% DIV=10 |
||
ENDWHILE |
ENDWHILE |
||
= O% = SUM(D%())</ |
= O% = SUM(D%())</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 553: | Line 553: | ||
Be aware, though, that even with a fast interpreter, it's going to be a very long time before you see the full set of results. |
Be aware, though, that even with a fast interpreter, it's going to be a very long time before you see the full set of results. |
||
< |
<syntaxhighlight lang="befunge">>1+9:0>\#06#:p#-:#1_$v |
||
?v6:%+55:\+1\<<<\0:::< |
?v6:%+55:\+1\<<<\0:::< |
||
#>g1+\6p55+/:#^_001p\v |
#>g1+\6p55+/:#^_001p\v |
||
^_@#!`<<v\+g6g10*+55\< |
^_@#!`<<v\+g6g10*+55\< |
||
>:*:*:*^>>:01g1+:01p`| |
>:*:*:*^>>:01g1+:01p`| |
||
^_\#\:#+.#5\#5,#$:<-$<</ |
^_\#\:#+.#5\#5,#$:<-$<</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 569: | Line 569: | ||
=={{header|C}}== |
=={{header|C}}== |
||
Using integers instead of strings. |
Using integers instead of strings. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
inline int self_desc(unsigned long long xx) |
inline int self_desc(unsigned long long xx) |
||
Line 594: | Line 594: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight>output<syntaxhighlight lang="text">1210 |
||
2020 |
2020 |
||
21200 |
21200 |
||
3211000 |
3211000 |
||
42101000</ |
42101000</syntaxhighlight> |
||
===Backtracking version=== |
===Backtracking version=== |
||
Backtracks on each digit from right to left, takes advantage of constraints "sum of digit values = number of digits" and "sum of (digit index * digit value) = number of digits". It is using as argument the list of allowed digits (example 012345789 to run the program in standard base 10). |
Backtracks on each digit from right to left, takes advantage of constraints "sum of digit values = number of digits" and "sum of (digit index * digit value) = number of digits". It is using as argument the list of allowed digits (example 012345789 to run the program in standard base 10). |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 695: | Line 695: | ||
puts(""); |
puts(""); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output for base 36 |
Output for base 36 |
||
<lang>$ time ./selfdesc.exe 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ |
<syntaxhighlight lang="text">$ time ./selfdesc.exe 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ |
||
1210 |
1210 |
||
2020 |
2020 |
||
Line 735: | Line 735: | ||
real 0m0.094s |
real 0m0.094s |
||
user 0m0.046s |
user 0m0.046s |
||
sys 0m0.030s</ |
sys 0m0.030s</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <iostream> |
#include <iostream> |
||
Line 812: | Line 812: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 827: | Line 827: | ||
Uses C++11. Build with |
Uses C++11. Build with |
||
g++ -std=c++11 sdn.cpp |
g++ -std=c++11 sdn.cpp |
||
< |
<syntaxhighlight lang="cpp">#include <algorithm> |
||
#include <array> |
#include <array> |
||
#include <iostream> |
#include <iostream> |
||
Line 852: | Line 852: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 870: | Line 870: | ||
probably much faster because it wouldn't have to allocate an array and then |
probably much faster because it wouldn't have to allocate an array and then |
||
turn around and "interpret" it back out but I didn't really pursue it. |
turn around and "interpret" it back out but I didn't really pursue it. |
||
< |
<syntaxhighlight lang="lisp">(defun to-ascii (str) (mapcar #'char-code (coerce str 'list))) |
||
(defun to-digits (n) |
(defun to-digits (n) |
||
Line 889: | Line 889: | ||
(digits (to-digits n) (cdr digits))) |
(digits (to-digits n) (cdr digits))) |
||
((null digits) t) |
((null digits) t) |
||
(if (not (eql (car digits) (aref counts ipos))) (return nil)))))</ |
(if (not (eql (car digits) (aref counts ipos))) (return nil)))))</syntaxhighlight> |
||
Output: |
Output: |
||
<lang>(loop for i from 1 to 4000000 do (if (self-described-p i) (print i))) |
<syntaxhighlight lang="text">(loop for i from 1 to 4000000 do (if (self-described-p i) (print i))) |
||
1210 |
1210 |
||
Line 898: | Line 898: | ||
21200 |
21200 |
||
3211000 |
3211000 |
||
NIL</ |
NIL</syntaxhighlight> |
||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="ruby">def self_describing?(n) |
||
digits = n.to_s.chars.map(&.to_i) # 12345 => [1, 2, 3, 4, 5] |
digits = n.to_s.chars.map(&.to_i) # 12345 => [1, 2, 3, 4, 5] |
||
digits.each_with_index.all? { |digit, idx| digits.count(idx) == digit } |
digits.each_with_index.all? { |digit, idx| digits.count(idx) == digit } |
||
Line 909: | Line 909: | ||
t = Time.monotonic |
t = Time.monotonic |
||
600_000_000.times { |n| (puts "#{n} in #{(Time.monotonic - t).total_seconds} secs";\ |
600_000_000.times { |n| (puts "#{n} in #{(Time.monotonic - t).total_seconds} secs";\ |
||
t = Time.monotonic) if self_describing?(n) }</ |
t = Time.monotonic) if self_describing?(n) }</syntaxhighlight> |
||
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35 |
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35 |
||
Compil: $ crystal build selfdescribing.cr --release |
Compil: $ crystal build selfdescribing.cr --release |
||
Line 924: | Line 924: | ||
{{trans|Wren and Go}} |
{{trans|Wren and Go}} |
||
< |
<syntaxhighlight lang="ruby">def selfDesc(n) |
||
ns = n.to_s |
ns = n.to_s |
||
nc = ns.size |
nc = ns.size |
||
Line 973: | Line 973: | ||
end |
end |
||
osecs = (Time.monotonic - start).total_seconds |
osecs = (Time.monotonic - start).total_seconds |
||
print("\nTook #{osecs} secs overall")</ |
print("\nTook #{osecs} secs overall")</syntaxhighlight> |
||
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35 |
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Crystal 0.35 |
||
Line 990: | Line 990: | ||
=={{header|D}}== |
=={{header|D}}== |
||
===Functional Version=== |
===Functional Version=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.conv, std.string; |
||
bool isSelfDescribing(in long n) pure nothrow @safe { |
bool isSelfDescribing(in long n) pure nothrow @safe { |
||
Line 999: | Line 999: | ||
void main() { |
void main() { |
||
4_000_000.iota.filter!isSelfDescribing.writeln; |
4_000_000.iota.filter!isSelfDescribing.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1210, 2020, 21200, 3211000]</pre> |
<pre>[1210, 2020, 21200, 3211000]</pre> |
||
===A Faster Version=== |
===A Faster Version=== |
||
< |
<syntaxhighlight lang="d">bool isSelfDescribing2(ulong n) nothrow @nogc { |
||
if (n <= 0) |
if (n <= 0) |
||
return false; |
return false; |
||
Line 1,046: | Line 1,046: | ||
if (i.isSelfDescribing2) |
if (i.isSelfDescribing2) |
||
i.writeln; |
i.writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1210 |
<pre>1210 |
||
Line 1,063: | Line 1,063: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Self_describing do |
||
def number(n) do |
def number(n) do |
||
digits = Integer.digits(n) |
digits = Integer.digits(n) |
||
Line 1,073: | Line 1,073: | ||
m = 3300000 |
m = 3300000 |
||
Enum.filter(0..m, fn n -> Self_describing.number(n) end)</ |
Enum.filter(0..m, fn n -> Self_describing.number(n) end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,082: | Line 1,082: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang"> |
||
sdn(N) -> lists:map(fun(S)->length(lists:filter(fun(C)->C-$0==S end,N))+$0 end,lists:seq(0,length(N)-1))==N. |
sdn(N) -> lists:map(fun(S)->length(lists:filter(fun(C)->C-$0==S end,N))+$0 end,lists:seq(0,length(N)-1))==N. |
||
gen(M) -> lists:filter(fun(N)->sdn(integer_to_list(N)) end,lists:seq(0,M)). |
gen(M) -> lists:filter(fun(N)->sdn(integer_to_list(N)) end,lists:seq(0,M)). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: kernel math.parser prettyprint sequences ; |
||
IN: rosetta-code.self-describing-numbers |
IN: rosetta-code.self-describing-numbers |
||
Line 1,100: | Line 1,100: | ||
digits dup [ digit-count = ] with map-index [ t = ] all? ; |
digits dup [ digit-count = ] with map-index [ t = ] all? ; |
||
100,000,000 <iota> [ self-describing-number? ] filter .</ |
100,000,000 <iota> [ self-describing-number? ] filter .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,108: | Line 1,108: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">\ where unavailable. |
||
: third ( A b c -- A b c A ) >r over r> swap ; |
: third ( A b c -- A b c A ) >r over r> swap ; |
||
: (.) ( u -- c-addr u ) 0 <# #s #> ; |
: (.) ( u -- c-addr u ) 0 <# #s #> ; |
||
Line 1,123: | Line 1,123: | ||
(.) [char] 0 third third bounds ?do |
(.) [char] 0 third third bounds ?do |
||
count i c@ [char] 0 - <> if drop 2drop false unloop exit then |
count i c@ [char] 0 - <> if drop 2drop false unloop exit then |
||
loop drop 2drop true ;</ |
loop drop 2drop true ;</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Function selfDescribing (n As UInteger) As Boolean |
Function selfDescribing (n As UInteger) As Boolean |
||
Line 1,148: | Line 1,148: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,158: | Line 1,158: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
===Original=== |
===Original=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,187: | Line 1,187: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output produced by above program: |
Output produced by above program: |
||
<pre> |
<pre> |
||
Line 1,201: | Line 1,201: | ||
===Optimized=== |
===Optimized=== |
||
Uses the optimized loop from the Wren entry - 12 times faster than before. |
Uses the optimized loop from the Wren entry - 12 times faster than before. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,256: | Line 1,256: | ||
osecs := time.Since(start).Seconds() |
osecs := time.Since(start).Seconds() |
||
fmt.Printf("\nTook %.1f secs overall\n", osecs) |
fmt.Printf("\nTook %.1f secs overall\n", osecs) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,274: | Line 1,274: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Data.Char |
||
count :: Int -> [Int] -> Int |
count :: Int -> [Int] -> Int |
||
Line 1,290: | Line 1,290: | ||
isSelfDescribing <$> |
isSelfDescribing <$> |
||
[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000] |
[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000] |
||
print $ filter isSelfDescribing [0 .. 4000000]</ |
print $ filter isSelfDescribing [0 .. 4000000]</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>[True,True,True,True,True,True,True] |
<pre>[True,True,True,True,True,True,True] |
||
Line 1,296: | Line 1,296: | ||
Here are functions for generating all the self-describing numbers of a certain length. We capitalize on the fact (from Wikipedia) that a self-describing number of length n is a base-n number (i.e. all digits are 0..n-1). |
Here are functions for generating all the self-describing numbers of a certain length. We capitalize on the fact (from Wikipedia) that a self-describing number of length n is a base-n number (i.e. all digits are 0..n-1). |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (forM_, replicateM) |
||
import Data.Char (intToDigit) |
import Data.Char (intToDigit) |
||
Line 1,325: | Line 1,325: | ||
. filter isSelfDescribing |
. filter isSelfDescribing |
||
. allBaseNNumsOfLength |
. allBaseNNumsOfLength |
||
<$> [1 .. 8]</ |
<$> [1 .. 8]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[1210,2020,21200,3211000,42101000]</pre> |
<pre>[1210,2020,21200,3211000,42101000]</pre> |
||
Line 1,333: | Line 1,333: | ||
The following program contains the procedure <code>is_self_describing</code> to test if a number is a self-describing number, and the procedure <code>self_describing_numbers</code> to generate them. |
The following program contains the procedure <code>is_self_describing</code> to test if a number is a self-describing number, and the procedure <code>self_describing_numbers</code> to generate them. |
||
<syntaxhighlight lang="icon"> |
|||
<lang Icon> |
|||
procedure count (test_item, str) |
procedure count (test_item, str) |
||
result := 0 |
result := 0 |
||
Line 1,362: | Line 1,362: | ||
every write (self_describing_numbers ()\4) |
every write (self_describing_numbers ()\4) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
A slightly more concise solution can be derived from the above by taking |
A slightly more concise solution can be derived from the above by taking |
||
more advantage of Icon's (and Unicon's) automatic goal-directed |
more advantage of Icon's (and Unicon's) automatic goal-directed |
||
evaluation: |
evaluation: |
||
< |
<syntaxhighlight lang="unicon"> |
||
procedure is_self_describing (n) |
procedure is_self_describing (n) |
||
ns := string (n) # convert to a string |
ns := string (n) # convert to a string |
||
Line 1,377: | Line 1,377: | ||
procedure self_describing_numbers () |
procedure self_describing_numbers () |
||
suspend is_self_describing(seq()) |
suspend is_self_describing(seq()) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution''':< |
'''Solution''':<syntaxhighlight lang="j"> digits =: 10&#.^:_1 |
||
counts =: _1 + [: #/.~ i.@:# , ] |
counts =: _1 + [: #/.~ i.@:# , ] |
||
selfdesc =: = counts&.digits"0 NB. Note use of "under"</ |
selfdesc =: = counts&.digits"0 NB. Note use of "under"</syntaxhighlight> |
||
'''Example''':< |
'''Example''':<syntaxhighlight lang="j"> selfdesc 2020 1210 21200 3211000 43101000 42101000 |
||
1 1 1 1 0 1</ |
1 1 1 1 0 1</syntaxhighlight> |
||
'''Extra credit''':< |
'''Extra credit''':<syntaxhighlight lang="j"> I.@:selfdesc i. 1e6 |
||
1210 2020 21200</ |
1210 2020 21200</syntaxhighlight> |
||
'''Discussion''': The use of <tt>&.</tt> here is a great example of its surprisingly broad applicability, and the elegance it can produce. |
'''Discussion''': The use of <tt>&.</tt> here is a great example of its surprisingly broad applicability, and the elegance it can produce. |
||
Line 1,397: | Line 1,397: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">public class SelfDescribingNumbers{ |
||
public static boolean isSelfDescribing(int a){ |
public static boolean isSelfDescribing(int a){ |
||
String s = Integer.toString(a); |
String s = Integer.toString(a); |
||
Line 1,423: | Line 1,423: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
{{works with|SpiderMonkey}} |
{{works with|SpiderMonkey}} |
||
< |
<syntaxhighlight lang="javascript">function is_self_describing(n) { |
||
var digits = Number(n).toString().split("").map(function(elem) {return Number(elem)}); |
var digits = Number(n).toString().split("").map(function(elem) {return Number(elem)}); |
||
var len = digits.length; |
var len = digits.length; |
||
Line 1,455: | Line 1,455: | ||
for (var i=1; i<=3300000; i++) |
for (var i=1; i<=3300000; i++) |
||
if (is_self_describing(i)) |
if (is_self_describing(i)) |
||
print(i);</ |
print(i);</syntaxhighlight> |
||
outputs |
outputs |
||
Line 1,465: | Line 1,465: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
{{works with|jq|1.4}} |
{{works with|jq|1.4}} |
||
< |
<syntaxhighlight lang="jq"># If your jq includes all/2 then comment out the following definition, |
||
# which is slightly less efficient: |
# which is slightly less efficient: |
||
def all(generator; condition): |
def all(generator; condition): |
||
reduce generator as $i (true; if . then $i | condition else . end);</ |
reduce generator as $i (true; if . then $i | condition else . end);</syntaxhighlight> |
||
< |
<syntaxhighlight lang="jq">def selfie: |
||
def count(value): reduce .[] as $i (0; if $i == value then . + 1 else . end); |
def count(value): reduce .[] as $i (0; if $i == value then . + 1 else . end); |
||
def digits: tostring | explode | map(. - 48); |
def digits: tostring | explode | map(. - 48); |
||
Line 1,477: | Line 1,477: | ||
else . as $digits |
else . as $digits |
||
| all ( range(0; length); . as $i | $digits | (.[$i] == count($i)) ) |
| all ( range(0; length); . as $i | $digits | (.[$i] == count($i)) ) |
||
end;</ |
end;</syntaxhighlight> |
||
'''The task:''' |
'''The task:''' |
||
< |
<syntaxhighlight lang="jq">range(0; 100000001) | select(selfie)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="sh">$ jq -n -f Self-describing_numbers.jq |
||
1210 |
1210 |
||
2020 |
2020 |
||
21200 |
21200 |
||
3211000 |
3211000 |
||
42101000</ |
42101000</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">function selfie(x::Integer) |
||
ds = reverse(digits(x)) |
ds = reverse(digits(x)) |
||
if sum(ds) != length(ds) return false end |
if sum(ds) != length(ds) return false end |
||
Line 1,504: | Line 1,504: | ||
selfies(x) = for i in 1:x selfie(i) && println(i) end |
selfies(x) = for i in 1:x selfie(i) && println(i) end |
||
@time selfies(4000000)</ |
@time selfies(4000000)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,514: | Line 1,514: | ||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k"> sdn: {n~+/'n=/:!#n:0$'$x}' |
||
sdn 1210 2020 2121 21200 3211000 42101000 |
sdn 1210 2020 2121 21200 3211000 42101000 |
||
1 1 0 1 1 1 |
1 1 0 1 1 1 |
||
&sdn@!:1e6 |
&sdn@!:1e6 |
||
1210 2020 21200</ |
1210 2020 21200</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun selfDescribing(n: Int): Boolean { |
fun selfDescribing(n: Int): Boolean { |
||
Line 1,542: | Line 1,542: | ||
for (i in 0..99999999) if (selfDescribing(i)) print("$i ") |
for (i in 0..99999999) if (selfDescribing(i)) print("$i ") |
||
println() |
println() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,551: | Line 1,551: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">'adapted from BASIC solution |
||
FOR x = 1 TO 5000000 |
FOR x = 1 TO 5000000 |
||
a$ = TRIM$(STR$(x)) |
a$ = TRIM$(STR$(x)) |
||
Line 1,569: | Line 1,569: | ||
NEXT x |
NEXT x |
||
PRINT |
PRINT |
||
PRINT "End"</ |
PRINT "End"</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">function selfDescNumber n |
||
local tSelfD, tLen |
local tSelfD, tLen |
||
put len(n) into tLen |
put len(n) into tLen |
||
Line 1,582: | Line 1,582: | ||
end repeat |
end repeat |
||
return tSelfD |
return tSelfD |
||
end selfDescNumber</ |
end selfDescNumber</syntaxhighlight> |
||
To list the self-describing numbers to 10 million< |
To list the self-describing numbers to 10 million<syntaxhighlight lang="livecode">on mouseUp |
||
repeat with n = 0 to 10000000 |
repeat with n = 0 to 10000000 |
||
if selfDescNumber(n) then |
if selfDescNumber(n) then |
||
Line 1,591: | Line 1,591: | ||
combine selfNum using comma |
combine selfNum using comma |
||
put selfNum |
put selfNum |
||
end mouseUp</ |
end mouseUp</syntaxhighlight> |
||
Output<lang |
Output<syntaxhighlight lang="livecode">1210,2020,21200,3211000</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">TO XX |
||
BT |
BT |
||
MAKE "AA (ARRAY 10 0) |
MAKE "AA (ARRAY 10 0) |
||
Line 1,620: | Line 1,620: | ||
FOR [Z 0 9][SETITEM :Z :AA "0 SETITEM :Z :BB "0 ]] |
FOR [Z 0 9][SETITEM :Z :AA "0 SETITEM :Z :BB "0 ]] |
||
PR [END] |
PR [END] |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function Is_self_describing( n ) |
||
local s = tostring( n ) |
local s = tostring( n ) |
||
Line 1,643: | Line 1,643: | ||
for i = 1, 999999999 do |
for i = 1, 999999999 do |
||
print( Is_self_describing( i ) ) |
print( Is_self_describing( i ) ) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">isSelfDescribing[n_Integer] := (RotateRight[DigitCount[n]] == PadRight[IntegerDigits[n], 10])</syntaxhighlight> |
||
<pre>Select[Range[10^10 - 1], isSelfDescribing] |
<pre>Select[Range[10^10 - 1], isSelfDescribing] |
||
-> {1210,2020,21200,3211000,42101000,521001000,6210001000}</pre> |
-> {1210,2020,21200,3211000,42101000,521001000,6210001000}</pre> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang="matlab">function z = isSelfDescribing(n) |
||
s = int2str(n)-'0'; % convert to vector of digits |
s = int2str(n)-'0'; % convert to vector of digits |
||
y = hist(s,0:9); |
y = hist(s,0:9); |
||
z = all(y(1:length(s))==s); |
z = all(y(1:length(s))==s); |
||
end;</ |
end;</syntaxhighlight> |
||
Test function: |
Test function: |
||
< |
<syntaxhighlight lang="matlab">for k = 1:1e10, |
||
if isSelfDescribing(k), |
if isSelfDescribing(k), |
||
printf('%i\n',k); |
printf('%i\n',k); |
||
end |
end |
||
end; </ |
end; </syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,672: | Line 1,672: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">numbers = [12, 1210, 1300, 2020, 21200, 5] |
||
occurrences = function(test, values) |
occurrences = function(test, values) |
||
Line 1,697: | Line 1,697: | ||
end if |
end if |
||
end for |
end for |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,711: | Line 1,711: | ||
{{trans|Pascal}} |
{{trans|Pascal}} |
||
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}} |
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}} |
||
< |
<syntaxhighlight lang="modula2"> |
||
MODULE SelfDescribingNumber; |
MODULE SelfDescribingNumber; |
||
Line 1,763: | Line 1,763: | ||
WriteLn; |
WriteLn; |
||
END SelfDescribingNumber. |
END SelfDescribingNumber. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,778: | Line 1,778: | ||
This is a brute-force algorithm. To speed-up, it uses integers instead of strings and the variable “digits” is allocated once, placed in global scope and accessed directly by the two functions (something I generally avoid). We have been able to check until 1_000_000_000. |
This is a brute-force algorithm. To speed-up, it uses integers instead of strings and the variable “digits” is allocated once, placed in global scope and accessed directly by the two functions (something I generally avoid). We have been able to check until 1_000_000_000. |
||
< |
<syntaxhighlight lang="nim">import algorithm, sequtils, std/monotimes, times |
||
type Digit = 0..9 |
type Digit = 0..9 |
||
Line 1,804: | Line 1,804: | ||
echo n, " in ", getMonoTime() - t0 |
echo n, " in ", getMonoTime() - t0 |
||
echo "\nTotal time: ", getMonoTime() - t0</ |
echo "\nTotal time: ", getMonoTime() - t0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,817: | Line 1,817: | ||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
-- REXX program to check if a number (base 10) is self-describing. |
-- REXX program to check if a number (base 10) is self-describing. |
||
parse arg x y . |
parse arg x y . |
||
Line 1,834: | Line 1,834: | ||
say number "is a self describing number" |
say number "is a self describing number" |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''output''' when using the input of: <tt> 0 999999999 </tt> |
'''output''' when using the input of: <tt> 0 999999999 </tt> |
||
<pre style="overflow:scroll"> |
<pre style="overflow:scroll"> |
||
Line 1,848: | Line 1,848: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
This is a finite set... |
This is a finite set... |
||
< |
<syntaxhighlight lang="parigp">S=[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000]; |
||
isself(n)=vecsearch(S,n)</ |
isself(n)=vecsearch(S,n)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program SelfDescribingNumber; |
||
uses |
uses |
||
Line 1,894: | Line 1,894: | ||
writeln (' ', x); |
writeln (' ', x); |
||
writeln('Job done.'); |
writeln('Job done.'); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,911: | Line 1,911: | ||
The number is self-descriptive If the arrays are equal. |
The number is self-descriptive If the arrays are equal. |
||
< |
<syntaxhighlight lang="perl">sub is_selfdesc |
||
{ |
{ |
||
local $_ = shift; |
local $_ = shift; |
||
Line 1,922: | Line 1,922: | ||
for (0 .. 100000, 3211000, 42101000) { |
for (0 .. 100000, 3211000, 42101000) { |
||
print "$_\n" if is_selfdesc($_); |
print "$_\n" if is_selfdesc($_); |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>1210 |
<pre>1210 |
||
Line 1,932: | Line 1,932: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{Trans|Ada}} |
{{Trans|Ada}} |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">self_desc</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">self_desc</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> |
||
Line 1,955: | Line 1,955: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"done (%s)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"done (%s)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,968: | Line 1,968: | ||
{{trans|Python}} |
{{trans|Python}} |
||
Not quite as fast as I hoped it would be, although a bazillion times faster than the above and a good five times faster than Python, the following self(20) completes in just over a second whereas self(24) takes nearly 9s, and it continues getting exponentially slower after that. Curiously, it is the early stages (same output) that slow down, whereas the latter ones always complete fairly quickly. |
Not quite as fast as I hoped it would be, although a bazillion times faster than the above and a good five times faster than Python, the following self(20) completes in just over a second whereas self(24) takes nearly 9s, and it continues getting exponentially slower after that. Curiously, it is the early stages (same output) that slow down, whereas the latter ones always complete fairly quickly. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">procedure</span> <span style="color: #000000;">impl</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">procedure</span> <span style="color: #000000;">impl</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span> |
||
Line 2,001: | Line 2,001: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span> |
||
<span style="color: #000000;">self</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)</span> |
<span style="color: #000000;">self</span><span style="color: #0000FF;">(</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,026: | Line 2,026: | ||
Finishes in less than a tenth of a second |
Finishes in less than a tenth of a second |
||
{{trans|Seed7}} |
{{trans|Seed7}} |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">constant</span> <span style="color: #004080;">string</span> <span style="color: #000000;">aleph</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'9'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'Z'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">constant</span> <span style="color: #004080;">string</span> <span style="color: #000000;">aleph</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'9'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'a'</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'Z'</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">)</span> |
||
Line 2,064: | Line 2,064: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span> |
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
as above plus |
as above plus |
||
Line 2,081: | Line 2,081: | ||
Works with: PHP 5. |
Works with: PHP 5. |
||
< |
<syntaxhighlight lang="php"><?php |
||
function is_describing($number) { |
function is_describing($number) { |
||
Line 2,098: | Line 2,098: | ||
} |
} |
||
?></ |
?></syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,111: | Line 2,111: | ||
===Loop based approach=== |
===Loop based approach=== |
||
< |
<syntaxhighlight lang="picat">self_desc(Num,L) => |
||
L = [ I.to_integer() : I in Num.to_string()], |
L = [ I.to_integer() : I in Num.to_string()], |
||
Len = L.len, |
Len = L.len, |
||
Line 2,123: | Line 2,123: | ||
fail |
fail |
||
end |
end |
||
end.</ |
end.</syntaxhighlight> |
||
===Constraint model 1=== |
===Constraint model 1=== |
||
Check if a number N is a self-describing number |
Check if a number N is a self-describing number |
||
< |
<syntaxhighlight lang="picat">self_desc_cp(Num, Sequence) => |
||
N = length(Num.to_string()), |
N = length(Num.to_string()), |
||
Line 2,139: | Line 2,139: | ||
scalar_product({ I : I in 0..N-1}, Sequence, N), |
scalar_product({ I : I in 0..N-1}, Sequence, N), |
||
solve([ffd,updown], Sequence).</ |
solve([ffd,updown], Sequence).</syntaxhighlight> |
||
===Constraint model 2=== |
===Constraint model 2=== |
||
Same idea as <code>self_desc_cp/2</code> but a different usage: generate all solutions of a specific length Len. |
Same idea as <code>self_desc_cp/2</code> but a different usage: generate all solutions of a specific length Len. |
||
< |
<syntaxhighlight lang="picat">self_desc_cp_len(Len, Num) => |
||
Sequence = new_list(Len), |
Sequence = new_list(Len), |
||
Line 2,160: | Line 2,160: | ||
to_num(List, Base, Num) => |
to_num(List, Base, Num) => |
||
Len = length(List), |
Len = length(List), |
||
Num #= sum([List[I]*Base**(Len-I) : I in 1..Len]).</ |
Num #= sum([List[I]*Base**(Len-I) : I in 1..Len]).</syntaxhighlight> |
||
===Testing=== |
===Testing=== |
||
Testing some numbers using <code>self_desc_cp/2</code>: |
Testing some numbers using <code>self_desc_cp/2</code>: |
||
< |
<syntaxhighlight lang="picat">go => |
||
List = [1210, 2020, 21200, 3211000, 42101000, |
List = [1210, 2020, 21200, 3211000, 42101000, |
||
123456,98,10,-121,0,1, |
123456,98,10,-121,0,1, |
||
Line 2,171: | Line 2,171: | ||
printf("%w: %w\n", N, cond(self_desc_cp(N,_S),"self desc", "not self desc")) |
printf("%w: %w\n", N, cond(self_desc_cp(N,_S),"self desc", "not self desc")) |
||
end, |
end, |
||
nl.</ |
nl.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,189: | Line 2,189: | ||
===Generate all solutions of a specific length=== |
===Generate all solutions of a specific length=== |
||
Using <code>self_desc_cp_len/3</code> to generates all solutions of length 1..13: |
Using <code>self_desc_cp_len/3</code> to generates all solutions of length 1..13: |
||
< |
<syntaxhighlight lang="picat">go2 => |
||
Len :: 1..13, |
Len :: 1..13, |
||
println(findall(Num, (indomain(Len), self_desc_cp_len(Len,Num)))), |
println(findall(Num, (indomain(Len), self_desc_cp_len(Len,Num)))), |
||
nl. |
nl. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,207: | Line 2,207: | ||
Here is one way to model this magic sequence problem. |
Here is one way to model this magic sequence problem. |
||
< |
<syntaxhighlight lang="picat">go3 ?=> |
||
member(N, 4..1000), |
member(N, 4..1000), |
||
magic_sequenceN,Seq), |
magic_sequenceN,Seq), |
||
Line 2,223: | Line 2,223: | ||
sum(Sequence) #= N, |
sum(Sequence) #= N, |
||
sum([I*Sequence[I+1] : I in 0..N-1]) #= N, |
sum([I*Sequence[I+1] : I in 0..N-1]) #= N, |
||
solve([ff,split], Sequence).</ |
solve([ff,split], Sequence).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,267: | Line 2,267: | ||
===Algorithmic approach=== |
===Algorithmic approach=== |
||
Except for the self describing number 2020, these sequences can be found by the following "algorithmic" approach: |
Except for the self describing number 2020, these sequences can be found by the following "algorithmic" approach: |
||
< |
<syntaxhighlight lang="picat">magic_sequence_alg(N, Sequence) => |
||
Sequence = new_list(N,0), |
Sequence = new_list(N,0), |
||
Sequence[1] := N - 4, |
Sequence[1] := N - 4, |
||
Sequence[2] := 2, |
Sequence[2] := 2, |
||
Sequence[3] := 1, |
Sequence[3] := 1, |
||
Sequence[N-3] := 1.</ |
Sequence[N-3] := 1.</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de selfDescribing (N) |
||
(fully '((D I) (= D (cnt = N (circ I)))) |
(fully '((D I) (= D (cnt = N (circ I)))) |
||
(setq N (mapcar format (chop N))) |
(setq N (mapcar format (chop N))) |
||
(range 0 (length N)) ) )</ |
(range 0 (length N)) ) )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>: (filter selfDescribing (range 1 4000000)) |
<pre>: (filter selfDescribing (range 1 4000000)) |
||
Line 2,286: | Line 2,286: | ||
According to the Wiki definition, the sum of the products of the index and the |
According to the Wiki definition, the sum of the products of the index and the |
||
digit contained at the index should equal the number of digits in the number: |
digit contained at the index should equal the number of digits in the number: |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function Test-SelfDescribing ([int]$Number) |
function Test-SelfDescribing ([int]$Number) |
||
{ |
{ |
||
Line 2,299: | Line 2,299: | ||
$sum -eq $digits.Count |
$sum -eq $digits.Count |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
Test-SelfDescribing -Number 2020 |
Test-SelfDescribing -Number 2020 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 2,308: | Line 2,308: | ||
</pre> |
</pre> |
||
It takes a very long while to test 100,000,000 numbers, and since they are already known just test a few: |
It takes a very long while to test 100,000,000 numbers, and since they are already known just test a few: |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
11,2020,21200,321100 | ForEach-Object { |
11,2020,21200,321100 | ForEach-Object { |
||
[PSCustomObject]@{ |
[PSCustomObject]@{ |
||
Line 2,315: | Line 2,315: | ||
} |
} |
||
} | Format-Table -AutoSize |
} | Format-Table -AutoSize |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 2,328: | Line 2,328: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Works with SWI-Prolog and library clpfd written by <b>Markus Triska</b>. |
Works with SWI-Prolog and library clpfd written by <b>Markus Triska</b>. |
||
< |
<syntaxhighlight lang="prolog">:- use_module(library(clpfd)). |
||
self_describling :- |
self_describling :- |
||
Line 2,434: | Line 2,434: | ||
run(Var,[Other|RRest], [1, Var],[Other|RRest]):- |
run(Var,[Other|RRest], [1, Var],[Other|RRest]):- |
||
dif(Var,Other).</ |
dif(Var,Other).</syntaxhighlight> |
||
Output |
Output |
||
Line 2,452: | Line 2,452: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure isSelfDescribing(x.q) |
||
;returns 1 if number is self-describing, otherwise it returns 0 |
;returns 1 if number is self-describing, otherwise it returns 0 |
||
Protected digitCount, digit, i, digitSum |
Protected digitCount, digit, i, digitSum |
||
Line 2,524: | Line 2,524: | ||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre>1210 is selfdescribing. |
<pre>1210 is selfdescribing. |
||
Line 2,579: | Line 2,579: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">>>> def isSelfDescribing(n): |
||
s = str(n) |
s = str(n) |
||
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) |
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s)) |
||
Line 2,586: | Line 2,586: | ||
[1210, 2020, 21200, 3211000] |
[1210, 2020, 21200, 3211000] |
||
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] |
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)] |
||
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]</ |
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]</syntaxhighlight> |
||
===Generator=== |
===Generator=== |
||
From [http://leetm.mingpao.com/cfm/Forum3.cfm?CategoryID=1&TopicID=1545&TopicOrder=Desc&TopicPage=1 here]. |
From [http://leetm.mingpao.com/cfm/Forum3.cfm?CategoryID=1&TopicID=1545&TopicOrder=Desc&TopicPage=1 here]. |
||
< |
<syntaxhighlight lang="python">def impl(d, c, m): |
||
if m < 0: return |
if m < 0: return |
||
if d == c[:len(d)]: print d |
if d == c[:len(d)]: print d |
||
Line 2,599: | Line 2,599: | ||
def self(n): impl([], [0]*(n+1), n) |
def self(n): impl([], [0]*(n+1), n) |
||
self(10)</ |
self(10)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>[] |
<pre>[] |
||
Line 2,612: | Line 2,612: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ tuck over peek |
||
1+ unrot poke ] is item++ ( n [ --> [ ) |
1+ unrot poke ] is item++ ( n [ --> [ ) |
||
Line 2,633: | Line 2,633: | ||
4000000 times |
4000000 times |
||
[ i^ self-desc if |
[ i^ self-desc if |
||
[ i^ echo cr ] ]</ |
[ i^ echo cr ] ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,644: | Line 2,644: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (get-digits number (lst null)) |
(define (get-digits number (lst null)) |
||
(if (zero? number) |
(if (zero? number) |
||
Line 2,657: | Line 2,657: | ||
(and bool |
(and bool |
||
(= (count (lambda (x) (= x i)) digits) |
(= (count (lambda (x) (= x i)) digits) |
||
(list-ref digits i)))))))</ |
(list-ref digits i)))))))</syntaxhighlight> |
||
Sadly, the implementation is too slow for the optional task, taking somewhere around 3 minutes to check all numbers below 100.000.000 |
Sadly, the implementation is too slow for the optional task, taking somewhere around 3 minutes to check all numbers below 100.000.000 |
||
Line 2,663: | Line 2,663: | ||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>my @values = <1210 2020 21200 3211000 |
||
42101000 521001000 6210001000 27 115508>; |
42101000 521001000 6210001000 27 115508>; |
||
Line 2,683: | Line 2,683: | ||
} |
} |
||
.say if .&sdn for ^9999999;</ |
.say if .&sdn for ^9999999;</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,702: | Line 2,702: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="red">Red [] |
||
;;------------------------------------- |
;;------------------------------------- |
||
Line 2,732: | Line 2,732: | ||
repeat i 4000000 [ if isSDN? to-string i [print i] ] |
repeat i 4000000 [ if isSDN? to-string i [print i] ] |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''output''' |
'''output''' |
||
<pre>1210 |
<pre>1210 |
||
Line 2,745: | Line 2,745: | ||
and [http://oeis.org/A138480 OEIS A138480]. |
and [http://oeis.org/A138480 OEIS A138480]. |
||
===digit by digit test=== |
===digit by digit test=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program determines if a number (in base 10) is a self─describing, */ |
||
/*────────────────────────────────────────────────────── self─descriptive, */ |
/*────────────────────────────────────────────────────── self─descriptive, */ |
||
/*────────────────────────────────────────────────────── autobiographical, or a */ |
/*────────────────────────────────────────────────────── autobiographical, or a */ |
||
Line 2,770: | Line 2,770: | ||
if substr(?,j,1)\==L-length(space(translate(?,,j-1),0)) then return 1 |
if substr(?,j,1)\==L-length(space(translate(?,,j-1),0)) then return 1 |
||
end /*j*/ |
end /*j*/ |
||
return 0 /*faster if used inverted truth table. */</ |
return 0 /*faster if used inverted truth table. */</syntaxhighlight> |
||
<pre> |
<pre> |
||
╔══════════════════════════════════════════════════════════════════╗ |
╔══════════════════════════════════════════════════════════════════╗ |
||
Line 2,793: | Line 2,793: | ||
===faster method=== |
===faster method=== |
||
(Uses table lookup.) |
(Uses table lookup.) |
||
< |
<syntaxhighlight lang="rexx">/*REXX program determines if a number (in base 10) is a self-describing number.*/ |
||
parse arg x y . /*obtain optional arguments from the CL*/ |
parse arg x y . /*obtain optional arguments from the CL*/ |
||
if x=='' | x=="," then exit /*Not specified? Then get out of Dodge*/ |
if x=='' | x=="," then exit /*Not specified? Then get out of Dodge*/ |
||
Line 2,811: | Line 2,811: | ||
say right(n,w) 'is a self-describing number.' |
say right(n,w) 'is a self-describing number.' |
||
end /*n*/ |
end /*n*/ |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' is the same as the 1<sup>st</sup> REXX example. |
'''output''' is the same as the 1<sup>st</sup> REXX example. |
||
Line 2,818: | Line 2,818: | ||
(Results are instantaneous.) |
(Results are instantaneous.) |
||
< |
<syntaxhighlight lang="rexx">/*REXX program determines if a number (in base 10) is a self-describing number.*/ |
||
parse arg x y . /*obtain optional arguments from the CL*/ |
parse arg x y . /*obtain optional arguments from the CL*/ |
||
if x=='' | x=="," then exit /*Not specified? Then get out of Dodge*/ |
if x=='' | x=="," then exit /*Not specified? Then get out of Dodge*/ |
||
Line 2,834: | Line 2,834: | ||
if _<x | _>y then iterate /*if not self-describing, try again. */ |
if _<x | _>y then iterate /*if not self-describing, try again. */ |
||
say right(_, w) 'is a self-describing number.' |
say right(_, w) 'is a self-describing number.' |
||
end /*n*/ /*stick a fork in it, we're all done. */</ |
end /*n*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' is the same as the 1<sup>st</sup> REXX example. |
'''output''' is the same as the 1<sup>st</sup> REXX example. |
||
<br><br> |
<br><br> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Self-describing numbers |
# Project : Self-describing numbers |
||
Line 2,864: | Line 2,864: | ||
end |
end |
||
return sum |
return sum |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,875: | Line 2,875: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def self_describing?(n) |
||
digits = n.digits.reverse |
digits = n.digits.reverse |
||
digits.each_with_index.all?{|digit, idx| digits.count(idx) == digit} |
digits.each_with_index.all?{|digit, idx| digits.count(idx) == digit} |
||
end |
end |
||
3_300_000.times {|n| puts n if self_describing?(n)}</ |
3_300_000.times {|n| puts n if self_describing?(n)}</syntaxhighlight> |
||
outputs |
outputs |
||
<pre>1210 |
<pre>1210 |
||
Line 2,888: | Line 2,888: | ||
{{trans|Wren}} |
{{trans|Wren}} |
||
< |
<syntaxhighlight lang="ruby">def selfDesc(n) |
||
ns = n.to_s |
ns = n.to_s |
||
nc = ns.size |
nc = ns.size |
||
Line 2,937: | Line 2,937: | ||
end |
end |
||
osecs = (Time.now - start) |
osecs = (Time.now - start) |
||
print("\nTook #{osecs} secs overall")</ |
print("\nTook #{osecs} secs overall")</syntaxhighlight> |
||
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Ruby 2.7.1 |
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17, Ruby 2.7.1 |
||
Line 2,979: | Line 2,979: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">for i = 0 to 50000000 step 10 |
||
a$ = str$(i) |
a$ = str$(i) |
||
for c = 1 TO len(a$) |
for c = 1 TO len(a$) |
||
Line 2,995: | Line 2,995: | ||
next i |
next i |
||
print "== End ==" |
print "== End ==" |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust"> |
||
fn is_self_desc(xx: u64) -> bool |
fn is_self_desc(xx: u64) -> bool |
||
{ |
{ |
||
Line 3,021: | Line 3,021: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
===Functional Programming=== |
===Functional Programming=== |
||
< |
<syntaxhighlight lang="scala">object SelfDescribingNumbers extends App { |
||
def isSelfDescribing(a: Int): Boolean = { |
def isSelfDescribing(a: Int): Boolean = { |
||
val s = Integer.toString(a) |
val s = Integer.toString(a) |
||
Line 3,038: | Line 3,038: | ||
println("Successfully completed without errors.") |
println("Successfully completed without errors.") |
||
}</ |
}</syntaxhighlight> |
||
See it running in your browser by [https://scastie.scala-lang.org/vQv61PpoSLeWwyVipLUevQ Scastie (JVM)]. |
See it running in your browser by [https://scastie.scala-lang.org/vQv61PpoSLeWwyVipLUevQ Scastie (JVM)]. |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed">$ include "seed7_05.s7i"; |
||
const func boolean: selfDescr (in string: stri) is func |
const func boolean: selfDescr (in string: stri) is func |
||
Line 3,108: | Line 3,108: | ||
gen(number); |
gen(number); |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,131: | Line 3,131: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Raku}} |
{{trans|Raku}} |
||
< |
<syntaxhighlight lang="ruby">func sdn(Number n) { |
||
var b = [0]*n.len |
var b = [0]*n.len |
||
var a = n.digits.flip |
var a = n.digits.flip |
||
Line 3,146: | Line 3,146: | ||
say "\nSelf-descriptive numbers less than 1e5 (in base 10):" |
say "\nSelf-descriptive numbers less than 1e5 (in base 10):" |
||
^1e5 -> each { |i| say i if sdn(i) }</ |
^1e5 -> each { |i| say i if sdn(i) }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,166: | Line 3,166: | ||
'''Extra credit:''' this will generate all the self-describing numbers in bases 7 to 36: |
'''Extra credit:''' this will generate all the self-describing numbers in bases 7 to 36: |
||
< |
<syntaxhighlight lang="ruby">for b in (7 .. 36) { |
||
var n = ((b-4) * b**(b-1) + 2*(b**(b-2)) + b**(b-3) + b**3 -> base(b)) |
var n = ((b-4) * b**(b-1) + 2*(b**(b-2)) + b**(b-3) + b**3 -> base(b)) |
||
say "base #{'%2d' % b}: #{n}" |
say "base #{'%2d' % b}: #{n}" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,206: | Line 3,206: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">import Foundation |
||
extension BinaryInteger { |
extension BinaryInteger { |
||
Line 3,238: | Line 3,238: | ||
} |
} |
||
dispatchMain()</ |
dispatchMain()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,250: | Line 3,250: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc isSelfDescribing num { |
proc isSelfDescribing num { |
||
set digits [split $num ""] |
set digits [split $num ""] |
||
Line 3,265: | Line 3,265: | ||
for {set i 0} {$i < 100000000} {incr i} { |
for {set i 0} {$i < 100000000} {incr i} { |
||
if {[isSelfDescribing $i]} {puts $i} |
if {[isSelfDescribing $i]} {puts $i} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|bash}} |
{{works with|bash}} |
||
Seeking self-describing numbers up to 100,000,000 is very time consuming, so we'll just verify a few numbers. |
Seeking self-describing numbers up to 100,000,000 is very time consuming, so we'll just verify a few numbers. |
||
< |
<syntaxhighlight lang="bash">selfdescribing() { |
||
local n=$1 |
local n=$1 |
||
local count=() |
local count=() |
||
Line 3,289: | Line 3,289: | ||
printf "%d\t%s\n" $n no |
printf "%d\t%s\n" $n no |
||
fi |
fi |
||
done</ |
done</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<pre>0 no |
<pre>0 no |
||
Line 3,304: | Line 3,304: | ||
Takes a very, very long time to check 100M numbers that I have to terminate the script. But the function |
Takes a very, very long time to check 100M numbers that I have to terminate the script. But the function |
||
works. |
works. |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Function IsSelfDescribing(n) |
Function IsSelfDescribing(n) |
||
IsSelfDescribing = False |
IsSelfDescribing = False |
||
Line 3,344: | Line 3,344: | ||
end_time = Now |
end_time = Now |
||
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds" |
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Heavily optimized to complete the search in a reasonable time for a scripting language. |
Heavily optimized to complete the search in a reasonable time for a scripting language. |
||
< |
<syntaxhighlight lang="ecmascript">var selfDesc = Fn.new { |n| |
||
var ns = "%(n)" |
var ns = "%(n)" |
||
var nc = ns.count |
var nc = ns.count |
||
Line 3,397: | Line 3,397: | ||
} |
} |
||
var osecs = ((System.clock - start) * 10).round / 10 |
var osecs = ((System.clock - start) * 10).round / 10 |
||
System.print("\nTook %(osecs) secs overall")</ |
System.print("\nTook %(osecs) secs overall")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,415: | Line 3,415: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code ChOut=8, IntOut=11; |
||
func SelfDesc(N); \Returns 'true' if N is self-describing |
func SelfDesc(N); \Returns 'true' if N is self-describing |
||
Line 3,449: | Line 3,449: | ||
int N; |
int N; |
||
for N:= 0 to 100_000_000-1 do |
for N:= 0 to 100_000_000-1 do |
||
if SelfDesc(N) then [IntOut(0, N); ChOut(0, ^ )]</ |
if SelfDesc(N) then [IntOut(0, N); ChOut(0, ^ )]</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,458: | Line 3,458: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
{{trans|BBC_BASIC}} |
{{trans|BBC_BASIC}} |
||
< |
<syntaxhighlight lang="yabasic">FOR N = 1 TO 5E7 |
||
IF FNselfdescribing(N) PRINT N |
IF FNselfdescribing(N) PRINT N |
||
NEXT |
NEXT |
||
Line 3,477: | Line 3,477: | ||
FOR I = 0 TO 8 : L = L + D(I) : NEXT |
FOR I = 0 TO 8 : L = L + D(I) : NEXT |
||
RETURN O = L |
RETURN O = L |
||
END SUB</ |
END SUB</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn isSelfDescribing(n){ |
||
if (n.bitAnd(1)) return(False); // Wikipedia: last digit must be zero |
if (n.bitAnd(1)) return(False); // Wikipedia: last digit must be zero |
||
nu:= n.toString(); |
nu:= n.toString(); |
||
ns:=["0".."9"].pump(String,nu.inCommon,"len"); //"12233".inCommon("2")-->"22" |
ns:=["0".."9"].pump(String,nu.inCommon,"len"); //"12233".inCommon("2")-->"22" |
||
(nu+"0000000000")[0,10] == ns; //"2020","2020000000" |
(nu+"0000000000")[0,10] == ns; //"2020","2020000000" |
||
}</ |
}</syntaxhighlight> |
||
Since testing a humongous number of numbers is slow, chunk the task into a bunch of threads. Even so, it pegged my 8 way Ivy Bridge Linux box for quite some time (eg the Python & AWK solutions crush this one). |
Since testing a humongous number of numbers is slow, chunk the task into a bunch of threads. Even so, it pegged my 8 way Ivy Bridge Linux box for quite some time (eg the Python & AWK solutions crush this one). |
||
< |
<syntaxhighlight lang="zkl">//[1..0x4_000_000].filter(isSelfDescribing).println(); |
||
const N=0d500_000; |
const N=0d500_000; |
||
[1..0d100_000_000, N] // chunk and thread, 200 in this case |
[1..0d100_000_000, N] // chunk and thread, 200 in this case |
||
.apply(fcn(n){ n.filter(N,isSelfDescribing) }.future) |
.apply(fcn(n){ n.filter(N,isSelfDescribing) }.future) |
||
.filter().apply("noop").println();</ |
.filter().apply("noop").println();</syntaxhighlight> |
||
A future is a thread returning a [delayed] result, future.filter/future.noop will block until the future coughs up the result. Since the results are really sparse for the bigger numbers, filter out the empty results. |
A future is a thread returning a [delayed] result, future.filter/future.noop will block until the future coughs up the result. Since the results are really sparse for the bigger numbers, filter out the empty results. |
||
{{out}} |
{{out}} |