tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,14 @@
There are several integers numbers called "self-describing" or "[[wp:Self-descriptive number|self-descriptive]]"
Integers with 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.
Position "0" has value 2 and there is two 0 in the number. Position "1" has value 0 because there are not 1's in the number.
Position "2" has value 2 and there is two 2. And the position "3" has value 0 and there are zero 3's.
Self-describing numbers < 100.000.000: 1210 - 2020 - 21200 - 3211000 - 42101000
;Task Description
# Write a function/routine/method/... that will check whether a given positive integer is self-describing.
# As an optional stretch goal - generate and display the set of self-describing numbers.

View file

@ -0,0 +1,17 @@
# syntax: GAWK -f SELF-DESCRIBING_NUMBERS.AWK
BEGIN {
for (n=1; n<=100000000; n++) {
if (is_self_describing(n)) {
print(n)
}
}
exit(0)
}
function is_self_describing(n, i) {
for (i=1; i<=length(n); i++) {
if (substr(n,i,1) != gsub(i-1,"&",n)) {
return(0)
}
}
return(1)
}

View file

@ -0,0 +1,25 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure SelfDesc is
subtype Desc_Int is Long_Integer range 0 .. 10**10-1;
function isDesc (innum : Desc_Int) return Boolean is
subtype S_Int is Natural range 0 .. 10;
type S_Int_Arr is array (0 .. 9) of S_Int;
ref, cnt : S_Int_Arr := (others => 0);
n, digit : S_Int := 0; num : Desc_Int := innum;
begin
loop
digit := S_Int (num mod 10);
ref (9 - n) := digit; cnt (digit) := cnt (digit) + 1;
num := num / 10; exit when num = 0; n := n + 1;
end loop;
return ref (9 - n .. 9) = cnt (0 .. n);
end isDesc;
begin
for i in Desc_Int range 1 .. 100_000_000 loop
if isDesc (i) then
Put_Line (Desc_Int'Image (i));
end if;
end loop;
end SelfDesc;

View file

@ -0,0 +1,23 @@
; The following directives and commands speed up execution:
#NoEnv
SetBatchlines -1
ListLines Off
Process, Priority,, high
MsgBox % 2020 ": " IsSelfDescribing(2020) "`n" 1337 ": " IsSelfDescribing(1337) "`n" 1210 ": " IsSelfDescribing(1210)
Loop 100000000
If IsSelfDescribing(A_Index)
list .= A_Index "`n"
MsgBox % "Self-describing numbers < 100000000 :`n" . list
CountSubstring(fullstring, substring){
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
}
IsSelfDescribing(number){
Loop Parse, number
If Not CountSubString(number, A_Index-1) = A_LoopField
return false
return true
}

View file

@ -0,0 +1,24 @@
Dim x, r, b, c, n, m As Integer
Dim a, d As String
Dim v(10), w(10) As Integer
Cls
For x = 1 To 5000000
a$ = ltrim$(Str$(x))
b = Len(a$)
For c = 1 To b
d$ = Mid$(a$, c, 1)
v(Val(d$)) = v(Val(d$)) + 1
w(c - 1) = Val(d$)
Next c
r = 0
For n = 0 To 10
If v(n) = w(n) Then r = r + 1
v(n) = 0
w(n) = 0
Next n
If r = 11 Then Print x; " Yes,is autodescriptive number"
Next x
Print
Print "End"
sleep
end

View file

@ -0,0 +1,16 @@
FOR N = 1 TO 5E7
IF FNselfdescribing(N) PRINT N
NEXT
END
DEF FNselfdescribing(N%)
LOCAL D%(), I%, L%, O%
DIM D%(9)
O% = N%
L% = LOG(N%)
WHILE N%
I% = N% MOD 10
D%(I%) += 10^(L%-I%)
N% DIV=10
ENDWHILE
= O% = SUM(D%())

View file

@ -0,0 +1,45 @@
#include <stdio.h>
int self_desc(const char *s)
{
unsigned char cnt[10] = {0};
int i;
for (i = 0; s[i] != '\0'; i++) cnt[s[i] - '0']++;
for (i = 0; s[i] != '\0'; i++) if (cnt[i] + '0' != s[i]) return 0;
return 1;
}
void gen(int n)
{
char d[11];
int one, i;
/* one = 0 may be confusing. 'one' is the number of digit 1s */
for (one = 0; one <= 2 && one < n - 2; one++) {
for (i = 0; i <= n; d[i++] = 0);
if ((d[0] = n - 2 - one) != 2) {
d[2] = d[d[0] - 0] = 1;
d[1] = 2;
} else {
d[1] = one ? 1 : 0;
d[2] = 2;
}
for (i = 0; i < n; d[i++] += '0');
if (self_desc(d)) printf("%s\n", d);
}
}
int main()
{
int i;
const char *nums[] = { "1210", "1337", "2020", "21200", "3211000", "42101000", 0};
for (i = 0; nums[i]; i++)
printf("%s is %sself describing\n", nums[i],
self_desc(nums[i]) ? "" : "not ");
printf("\nAll autobiograph numbers:\n");
for (i = 0; i < 11; i++) gen(i);
return 0;
}

View file

@ -0,0 +1,15 @@
1210 is self describing
1337 is not self describing
2020 is self describing
21200 is self describing
3211000 is self describing
42101000 is self describing
All autobiograph numbers:
2020
1210
21200
3211000
42101000
521001000
6210001000

View file

@ -0,0 +1,26 @@
#include <stdio.h>
inline int self_desc(unsigned long long xx)
{
register unsigned int d, x;
unsigned char cnt[10] = {0}, dig[10] = {0};
for (d = 0; xx > ~0U; xx /= 10)
cnt[ dig[d++] = xx % 10 ]++;
for (x = xx; x; x /= 10)
cnt[ dig[d++] = x % 10 ]++;
while(d-- && dig[x++] == cnt[d]);
return d == -1;
}
int main()
{
int i;
for (i = 1; i < 100000000; i++) /* don't handle 0 */
if (self_desc(i)) printf("%d\n", i);
return 0;
}

View file

@ -0,0 +1,5 @@
1210
2020
21200
3211000
42101000

View file

@ -0,0 +1,10 @@
import std.stdio, std.algorithm, std.range, std.conv;
bool isSelfDescribing(in long n) {
auto nu = n.text().map!q{a - '0'}();
return nu.equal( nu.length.iota().map!(a => count(nu, a))() );
}
void main() {
writeln(iota(4_000_000).filter!isSelfDescribing());
}

View file

@ -0,0 +1,42 @@
import std.stdio;
bool isSelfDescribing2(long n) {
if (n <= 0)
return false;
__gshared static uint[10] digits, d;
digits[] = 0;
d[] = 0;
int i;
if (n < uint.max) {
uint nu = cast(uint)n;
for (i = 0; nu > 0 && i < digits.length; nu /= 10, i++) {
d[i] = cast(ubyte)(nu % 10);
digits[d[i]]++;
}
if (nu > 0)
return false;
} else {
for (i = 0; n > 0 && i < digits.length; n /= 10, i++) {
d[i] = cast(ubyte)(n % 10);
digits[d[i]]++;
}
if (n > 0)
return false;
}
foreach (k; 0 .. i)
if (d[k] != digits[i - k - 1])
return false;
return true;
}
void main() {
foreach (x; [1210, 2020, 21200, 3211000,
42101000, 521001000, 6210001000])
assert(isSelfDescribing2(x));
foreach (i; 0 .. 4_000_000)
if (isSelfDescribing2(i))
writeln(i);
}

View file

@ -0,0 +1,2 @@
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)).

View file

@ -0,0 +1,16 @@
\ where unavailable.
: third ( A b c -- A b c A ) >r over r> swap ;
: (.) ( u -- c-addr u ) 0 <# #s #> ;
\ COUNT is a standard word with a very different meaning, so this
\ would typically be beheaded, or given another name, or otherwise
\ given a short lifespan, so to speak.
: count ( c-addr1 u1 c -- c-addr1 u1 c+1 u )
0 2over bounds do
over i c@ = if 1+ then
loop swap 1+ swap ;
: self-descriptive? ( u -- f )
(.) [char] 0 third third bounds ?do
count i c@ [char] 0 - <> if drop 2drop false unloop exit then
loop drop 2drop true ;

View file

@ -0,0 +1,30 @@
package main
import (
"fmt"
"strconv"
"strings"
)
// task 1 requirement
func sdn(n int64) bool {
if n >= 1e10 {
return false
}
s := strconv.FormatInt(n, 10)
for d, p := range s {
if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
return false
}
}
return true
}
// task 2 code (takes a while to run)
func main() {
for n := int64(0); n < 1e10; n++ {
if sdn(n) {
fmt.Println(n)
}
}
}

View file

@ -0,0 +1,16 @@
import Data.Char
count :: Int -> [Int] -> Int
count x = length . filter (x ==)
isSelfDescribing :: Integer -> Bool
isSelfDescribing n =
nu == f where
nu = map digitToInt (show n)
f = map (\a -> count a nu) [0 .. ((length nu)-1)]
main = do
let tests = [1210, 2020, 21200, 3211000,
42101000, 521001000, 6210001000]
print $ map isSelfDescribing tests
print $ filter isSelfDescribing [0 .. 4000000]

View file

@ -0,0 +1,21 @@
import Data.Char (intToDigit)
import Control.Monad (replicateM, forM_)
count :: Int -> [Int] -> Int
count x = length . filter (x ==)
-- all the combinations of n digits of base n
-- a base-n number are represented as a list of ints, one per digit
allBaseNNumsOfLength :: Int -> [[Int]]
allBaseNNumsOfLength n = replicateM n [0..n-1]
isSelfDescribing :: [Int] -> Bool
isSelfDescribing num =
all (\(i,x) -> x == count i num) $ zip [0..] num
-- translate it back into an integer in base-10
decimalize :: [Int] -> Int
decimalize = read . map intToDigit
main = forM_ [1..7] $
print . map decimalize . filter isSelfDescribing . allBaseNNumsOfLength

View file

@ -0,0 +1,28 @@
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

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,3 @@
digits =: 10&#.^:_1
counts =: _1 + [: #/.~ i.@:# , ]
selfdesc =: = counts&.digits"0 NB. Note use of "under"

View file

@ -0,0 +1,2 @@
selfdesc 2020 1210 21200 3211000 43101000 42101000
1 1 1 1 0 1

View file

@ -0,0 +1,2 @@
I.@:selfdesc i. 1e6
1210 2020 21200

View file

@ -0,0 +1,27 @@
public class SelfDescribingNumbers{
public static boolean isSelfDescribing(int a){
String s = Integer.toString(a);
for(int i = 0; i < s.length(); i++){
String s0 = s.charAt(i) + "";
int b = Integer.parseInt(s0); // number of times i-th digit must occur for it to be a self describing number
int count = 0;
for(int j = 0; j < s.length(); j++){
int temp = Integer.parseInt(s.charAt(j) + "");
if(temp == i){
count++;
}
if (count > b) return false;
}
if(count != b) return false;
}
return true;
}
public static void main(String[] args){
for(int i = 0; i < 100000000; i++){
if(isSelfDescribing(i)){
System.out.println(i);
}
}
}
}

View file

@ -0,0 +1,28 @@
function is_self_describing(n) {
var digits = Number(n).toString().split("").map(function(elem) {return Number(elem)});
var len = digits.length;
var count = digits.map(function(x){return 0});
digits.forEach(function(digit, idx, ary) {
if (digit >= count.length)
return false
count[digit] ++;
});
return digits.equals(count);
}
Array.prototype.equals = function(other) {
if (this === other)
return true; // same object
if (this.length != other.length)
return false;
for (idx in this)
if (this[idx] !== other[idx])
return false;
return true;
}
for (var i=1; i<=3300000; i++)
if (is_self_describing(i))
print(i);

View file

@ -0,0 +1,11 @@
julia> function selfie(x)
y = string(x)
return all([string(i[2]) == string(mapreduce(x->string(x)==string(i[1]-1),+,y)) for i in enumerate(y)])
end
# method added to generic function selfie
julia> selfie(2020)
true
julia> selfie(2021)
false

View file

@ -0,0 +1,6 @@
sdn: {n~+/'n=/:!#n:0$'$x}'
sdn 1210 2020 2121 21200 3211000 42101000
1 1 0 1 1 1
&sdn@!:1e6
1210 2020 21200

View file

@ -0,0 +1,19 @@
'adapted from BASIC solution
FOR x = 1 TO 5000000
a$ = TRIM$(STR$(x))
b = LEN(a$)
FOR c = 1 TO b
d$ = MID$(a$, c, 1)
v(VAL(d$)) = v(VAL(d$)) + 1
w(c - 1) = VAL(d$)
NEXT c
r = 0
FOR n = 0 TO 10
IF v(n) = w(n) THEN r = r + 1
v(n) = 0
w(n) = 0
NEXT n
IF r = 11 THEN PRINT x; " is a self-describing number"
NEXT x
PRINT
PRINT "End"

View file

@ -0,0 +1,26 @@
TO XX
BT
MAKE "AA (ARRAY 10 0)
MAKE "BB (ARRAY 10 0)
FOR [Z 0 9][SETITEM :Z :AA "0 SETITEM :Z :BB "0 ]
FOR [A 1 50000][
MAKE "B COUNT :A
MAKE "Y 0
MAKE "X 0
MAKE "R 0
MAKE "J 0
MAKE "K 0
FOR [C 1 :B][MAKE "D ITEM :C :A
SETITEM :C - 1 :AA :D
MAKE "X ITEM :D :BB
MAKE "Y :X + 1
SETITEM :D :BB :Y
MAKE "R 0]
FOR [Z 0 9][MAKE "J ITEM :Z :AA
MAKE "K ITEM :Z :BB
IF :J = :K [MAKE "R :R + 1]]
IF :R = 10 [PR :A]
FOR [Z 0 9][SETITEM :Z :AA "0 SETITEM :Z :BB "0 ]]
PR [END]
END

View file

@ -0,0 +1,21 @@
function Is_self_describing( n )
local s = tostring( n )
local t = {}
for i = 0, 9 do t[i] = 0 end
for i = 1, s:len() do
local idx = tonumber( s:sub(i,i) )
t[idx] = t[idx] + 1
end
for i = 1, s:len() do
if t[i-1] ~= tonumber( s:sub(i,i) ) then return false end
end
return true
end
for i = 1, 999999999 do
print( Is_self_describing( i ) )
end

View file

@ -0,0 +1,5 @@
function z = isSelfDescribing(n)
s = int2str(n)-'0'; % convert to vector of digits
y = hist(s,0:9);
z = all(y(1:length(s))==s);
end;

View file

@ -0,0 +1,5 @@
for k = 1:1e10,
if isSelfDescribing(k),
printf('%i\n',k);
end
end;

View file

@ -0,0 +1 @@
isSelfDescribing[n_Integer] := (RotateRight[DigitCount[n]] == PadRight[IntegerDigits[n], 10])

View file

@ -0,0 +1,2 @@
S=[1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000];
isself(n)=vecsearch(S,n)

View file

@ -0,0 +1,43 @@
Program SelfDescribingNumber;
uses
SysUtils;
function check(number: longint): boolean;
var
i, d: integer;
a: string;
count, w : array [0..9] of integer;
begin
a := intToStr(number);
for i := 0 to 9 do
begin
count[i] := 0;
w[i] := 0;
end;
for i := 1 to length(a) do
begin
d := ord(a[i]) - ord('0');
inc(count[d]);
w[i - 1] := d;
end;
check := true;
i := 0;
while check and (i <= 9) do
begin
check := count[i] = w[i];
inc(i);
end;
end;
var
x: longint;
begin
writeln ('Autodescriptive numbers from 1 to 100000000:');
for x := 1 to 100000000 do
if check(x) then
writeln (' ', x);
writeln('Job done.');
end.

View file

@ -0,0 +1,18 @@
my @values = <1210 2020 21200 3211000
42101000 521001000 6210001000 27 115508>;
for @values -> $test {
say "$test is {$test.&sdn ?? '' !! 'NOT ' }a self describing number.";
}
sub sdn ($num) {
my @digits;
my $chars = $num.chars;
@digits[$_]++ for $num.comb;
return 0 if @digits.elems > $chars;
@digits[$_] //= '0' for ^$chars;
my $string = join '', @digits;
return 1 if $num eq $string;
}
say $_ if $_.&sdn for ^9999999;

View file

@ -0,0 +1,12 @@
sub is_selfdesc
{
local $_ = shift;
my @b = (0) x length;
$b[$_]++ for my @a = split //;
return "@a" eq "@b";
}
# check all numbers from 0 to 100k plus two 'big' ones
for (0 .. 100000, 3211000, 42101000) {
print "$_\n" if is_selfdesc($_);
}

View file

@ -0,0 +1,5 @@
(de selfDescribing (N)
(not
(find '((D I) (<> D (cnt = N (circ I))))
(setq N (mapcar format (chop N)))
(range 0 (length N)) ) ) )

View file

@ -0,0 +1,107 @@
:- use_module(library(clpfd)).
self_describling :-
forall(between(1, 10, I),
(findall(N, self_describling(I,N), L),
format('Len ~w, Numbers ~w~n', [I, L]))).
% search of the self_describling numbers of a given len
self_describling(Len, N) :-
length(L, Len),
Len1 is Len - 1,
L = [H|T],
% the first figure is greater than 0
H in 1..Len1,
% there is a least to figures so the number of these figures
% is at most Len - 2
Len2 is Len - 2,
T ins 0..Len2,
% the sum of the figures is equal to the len of the number
sum(L, #=, Len),
% There is at least one figure corresponding to the number of zeros
H1 #= H+1,
element(H1, L, V),
V #> 0,
% create the list
label(L),
% test the list
msort(L, LNS),
packList(LNS,LNP),
numlist(0, Len1, NumList),
verif(LNP,NumList, L),
% list is OK, create the number
maplist(atom_number, LA, L),
number_chars(N, LA).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% testing a number (not use in this program)
self_describling(N) :-
number_chars(N, L),
maplist(atom_number, L, LN),
msort(LN, LNS),
packList(LNS,LNP), !,
length(L, Len),
Len1 is Len - 1,
numlist(0, Len1, NumList),
verif(LNP,NumList, LN).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% verif(PackList, Order_of_Numeral, Numeral_of_the_nuber_to_test)
% Packlist is of the form [[Number_of_Numeral, Order_of_Numeral]|_]
% Test succeed when
% All lists are empty
verif([], [], []).
% Packlist is empty and all lasting numerals are 0
verif([], [_N|S], [0|T]) :-
verif([], S, T).
% Number of numerals N is V
verif([[V, N]|R], [N|S], [V|T]) :-
verif(R, S, T).
% Number of numerals N is 0
verif([[V, N1]|R], [N|S], [0|T]) :-
N #< N1,
verif([[V,N1]|R], S, T).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ?- packList([a,a,a,b,c,c,c,d,d,e], L).
% L = [[3,a],[1,b],[3,c],[2,d],[1,e]] .
% ?- packList(R, [[3,a],[1,b],[3,c],[2,d],[1,e]]).
% R = [a,a,a,b,c,c,c,d,d,e] .
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
packList([],[]).
packList([X],[[1,X]]) :- !.
packList([X|Rest],[XRun|Packed]):-
run(X,Rest, XRun,RRest),
packList(RRest,Packed).
run(Var,[],[1, Var],[]).
run(Var,[Var|LRest],[N1, Var],RRest):-
N #> 0,
N1 #= N + 1,
run(Var,LRest,[N, Var],RRest).
run(Var,[Other|RRest], [1, Var],[Other|RRest]):-
dif(Var,Other).

View file

@ -0,0 +1,73 @@
Procedure isSelfDescribing(x.q)
;returns 1 if number is self-describing, otherwise it returns 0
Protected digitCount, digit, i, digitSum
Dim digitTally(10)
Dim digitprediction(10)
If x <= 0
ProcedureReturn 0 ;number must be positive and non-zero
EndIf
While x > 0 And i < 10
digit = x % 10
digitSum + digit
If digitSum > 10
ProcedureReturn 0 ;sum of digits' values exceeds maximum possible
EndIf
digitprediction(i) = digit
digitTally(digit) + 1
x / 10
i + 1
Wend
digitCount = i - 1
If digitSum < digitCount Or x > 0
ProcedureReturn 0 ;sum of digits' values is too small or number has more than 10 digits
EndIf
For i = 0 To digitCount
If digitTally(i) <> digitprediction(digitCount - i)
ProcedureReturn 0 ;number is not self-describing
EndIf
Next
ProcedureReturn 1 ;number is self-describing
EndProcedure
Procedure displayAll()
Protected i, j, t
PrintN("Starting search for all self-describing numbers..." + #CRLF$)
For j = 0 To 9
PrintN(#CRLF$ + "Searching possibilites " + Str(j * 1000000000) + " -> " + Str((j + 1) * 1000000000 - 1)+ "...")
t = ElapsedMilliseconds()
For i = 0 To 999999999
If isSelfDescribing(j * 1000000000 + i)
PrintN(Str(j * 1000000000 + i))
EndIf
Next
PrintN("Time to search this range of possibilities: " + Str((ElapsedMilliseconds() - t) / 1000) + "s.")
Next
PrintN(#CRLF$ + "Search complete.")
EndProcedure
If OpenConsole()
DataSection
Data.q 1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000, 3214314
EndDataSection
Define i, x.q
For i = 1 To 8
Read.q x
Print(Str(x) + " is ")
If Not isSelfDescribing(x)
Print("not ")
EndIf
PrintN("selfdescribing.")
Next
PrintN(#CRLF$)
displayAll()
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf

View file

@ -0,0 +1,8 @@
>>> def isSelfDescribing(n):
s = str(n)
return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))
>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(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)]

View file

@ -0,0 +1,11 @@
def impl(d, c, m):
if m < 0: return
if d == c[:len(d)]: print d
for i in range(c[len(d)],m+1):
dd = d+[i]
if i<len(dd) and c[i]==dd[i]: continue
impl(dd,c[:i]+[c[i]+1]+c[i+1:],m-i)
def self(n): impl([], [0]*(n+1), n)
self(10)

View file

@ -0,0 +1,39 @@
/*REXX program checks if a number (base 10) is self-describing, */
/* self-descriptive, */
/* autobiographical, or */
/* a curious number. */
/* */
/* Also see: http://oeis.org/A046043 */
/* and: http://oeis.org/A138480 */
parse arg x y . /*get args from the command line.*/
if x=='' then exit /*if no X, then get out of Dodge.*/
if y=='' then y=x /*if no Y, then use the X value. */
y=min(y,999999999)
w=length(y) /*use Y's width for pretty output*/
/*══════════════════════════════════════test for a single number. */
if x==y then do /*handle the case of a single #. */
noYes=test_sdn(y) /*is it or ain't it? */
say y word("is isn't",noYes+1) 'a self-describing number.'
exit
end
/*══════════════════════════════════════test for a range of numbers. */
do n=x to y
if test_sdn(n) then iterate /*if ¬ self-describing, try again*/
say right(n,w) 'is a self-describing number.' /*is it? */
end /*n*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────TEST_SDN subroutine─────────────────*/
test_sdn: procedure; parse arg ?; L=length(?)
do j=L to 1 by -1 /*backwards is slightly faster. */
if substr(?,j,1)\==L-length(space(translate(?,,j-1),0)) then return 1
end /*j*/
return 0 /*faster if inverted truth table.*/
/* ┌──────────────────────────────────────────────────────────────────┐
The method used above is to TRANSLATE the digit being queried to
blanks, then use the SPACE bif function to remove all blanks,
and then compare the new number's length to the original length.
The difference in length is the number of digits translated.
This method works if there're no imbedded/leading/trailing blanks
(or other whitespace like tabs) in the number.
*/

View file

@ -0,0 +1,21 @@
/*REXX program checks if a number (base 10) is self-describing */
parse arg x y . /*get args from the command line.*/
if x=='' then exit /*if no X, then get out of Dodge.*/
if y=='' then y=x /*if no Y, then use the X value. */
y=min(y,999999999)
w=length(y) /*use Y's width for pretty output*/
/*══════════════════════════════════════test for a single number. */
if x==y then do /*handle the case of a single #. */
noYes=test_sdn(y) /*is it or ain't it? */
say y word("is isn't",noYes+1) 'a self-describing number.'
exit
end
/*══════════════════════════════════════test for a range of numbers. */
do n=x to y
if test_sdn(n) then iterate /*if ¬ self-describing, try again*/
say right(n,w) 'is a self-describing number.' /*is it? */
end /*n*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────TEST_SDN subroutine─────────────────*/
test_sdn: procedure; parse arg ?; if right(?,1)\==0 then return 1
return wordpos(?,'1210 2020 21200 3211000 42101000 521001000 6210001000')==0

View file

@ -0,0 +1,23 @@
/*REXX program checks if a number (base 10) is self-describing */
parse arg x y . /*get args from the command line.*/
if x=='' then exit /*if no X, then get out of Dodge.*/
if y=='' then y=x /*if no Y, then use the X value. */
y=min(y,999999999)
w=length(y) /*use Y's width for pretty output*/
$='1210 2020 21200 3211000 42101000 521001000 6210001000' /*the list.*/
/*══════════════════════════════════════test for a single number. */
if x==y then do /*handle the case of a single #. */
noYes=test_sdn(y) /*is it or ain't it? */
say y word("is isn't",noYes+1) 'a self-describing number.'
exit
end
/*══════════════════════════════════════test for a range of numbers. */
do n=1 for words($) /*look for nums that are in range*/
_=word($,n)
if _<x | _>y then iterate /*if ¬ self-describing, try again*/
say right(_,w) 'is a self-describing number.' /*display it.*/
end /*n*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────TEST_SDN subroutine─────────────────*/
test_sdn: procedure expose $; parse arg ?
if right(?,1)\==0 then return 1; return wordpos(?,$)==0

View file

@ -0,0 +1,14 @@
def is_self_describing?(n)
digits = n.to_s.chars.collect {|digit| digit.to_i}
len = digits.length
count = Array.new(len, 0)
digits.each do |digit|
return false if digit >= len
count[digit] = count[digit] + 1
end
digits.eql?(count)
end
3_300_000.times {|n| puts n if is_self_describing?(n)}

View file

@ -0,0 +1,17 @@
for i = 0 to 50000000 step 10
a$ = str$(i)
for c = 1 TO len(a$)
d = val(mid$(a$, c, 1))
j(d) = j(d) + 1
k(c-1) = d
next c
r = 0
for n = 0 to 10
r = r + (j(n) = k(n))
j(n) = 0
k(n) = 0
next n
if r = 11 then print i
next i
print "== End =="
end

View file

@ -0,0 +1,66 @@
$ include "seed7_05.s7i";
const func boolean: selfDescr (in string: stri) is func
result
var boolean: check is TRUE;
local
var integer: idx is 0;
var array integer: count is [0 .. 9] times 0;
begin
for idx range 1 to length(stri) do
incr(count[ord(stri[idx]) - ord('0')]);
end for;
idx := 1;
while check and idx <= length(stri) do
check := count[pred(idx)] = ord(stri[idx]) - ord('0');
incr(idx);
end while;
end func;
const proc: gen (in integer: n) is func
local
var array integer : digits is 0 times 0;
var string: stri is "";
var integer: numberOfOneDigits is 0;
var integer: idx is 0;
begin
while numberOfOneDigits <= 2 and numberOfOneDigits < n - 2 do
digits := n times 0;
digits[1] := n - 2 - numberOfOneDigits;
if digits[1] <> 2 then
digits[digits[1] + 1] := 1;
digits[2] := 2;
digits[3] := 1;
else
digits[2] := ord(numberOfOneDigits <> 0);
digits[3] := 2;
end if;
stri := "";
for idx range 1 to n do
stri &:= chr(ord(digits[idx]) + ord('0'));
end for;
if selfDescr(stri) then
writeln(stri);
end if;
incr(numberOfOneDigits);
end while;
end func;
const proc: main is func
local
const array integer: nums is [] (1210, 1337, 2020, 21200, 3211000, 42101000);
var integer: number is 0;
begin
for number range nums do
write(number <& " is ");
if not selfDescr(str(number)) then
write("not ");
end if;
writeln("self describing");
end for;
writeln;
writeln("All autobiograph numbers:");
for number range 1 to 10 do
gen(number);
end for;
end func;

View file

@ -0,0 +1,16 @@
package require Tcl 8.5
proc isSelfDescribing num {
set digits [split $num ""]
set len [llength $digits]
set count [lrepeat $len 0]
foreach d $digits {
if {$d >= $len} {return false}
lset count $d [expr {[lindex $count $d] + 1}]
}
foreach d $digits c $count {if {$c != $d} {return false}}
return true
}
for {set i 0} {$i < 100000000} {incr i} {
if {[isSelfDescribing $i]} {puts $i}
}

View file

@ -0,0 +1,35 @@
code ChOut=8, IntOut=11;
func SelfDesc(N); \Returns 'true' if N is self-describing
int N;
int Len, \length = number of digits in N
I, D;
char Digit(10), Count(10);
proc Num2Str(N); \Convert integer N to string in Digit
int N;
int R;
[N:= N/10;
R:= rem(0);
if N then Num2Str(N);
Digit(Len):= R;
Len:= Len+1;
];
[Len:= 0;
Num2Str(N);
for I:= 0 to Len-1 do Count(I):= 0;
for I:= 0 to Len-1 do
[D:= Digit(I);
if D >= Len then return false;
Count(D):= Count(D)+1;
];
for I:= 0 to Len-1 do
if Count(I) # Digit(I) then return false;
return true;
]; \SelfDesc
int N;
for N:= 0 to 100_000_000-1 do
if SelfDesc(N) then [IntOut(0, N); ChOut(0, ^ )]