Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Esthetic_numbers

View file

@ -0,0 +1,38 @@
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.
;E.G.
:* '''12''' is an esthetic number. One and two differ by 1.
:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.
:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
;Task
:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base × 4)''' through index '''(base × 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.
:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.
;Related task:
*   [[Numbers_With_Equal_Rises_and_Falls|numbers with equal rises and falls]]
;See also:
:;*[[oeis:A033075|OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1]]
:;*[http://www.numbersaplenty.com/set/esthetic_number/ Numbers Aplenty - Esthetic numbers]
:;*[https://www.geeksforgeeks.org/stepping-numbers/ Geeks for Geeks - Stepping numbers]
<br><br>

View file

@ -0,0 +1,64 @@
F isEsthetic(=n, b)
I n == 0 {R 0B}
V i = n % b
n I/= b
L n > 0
V j = n % b
I abs(i - j) != 1
R 0B
n I/= b
i = j
R 1B
F listEsths(Int64 n1, n2, m1, m2; perLine, all)
[Int64] esths
F dfs(Int64 n, m, i) -> N
I i C n .. m
@esths.append(i)
I i == 0 | i > m {R}
V d = i % 10
V i1 = i * 10 + d - 1
V i2 = i1 + 2
I d == 0
@dfs(n, m, i2)
E I d == 9
@dfs(n, m, i1)
E
@dfs(n, m, i1)
@dfs(n, m, i2)
L(i) 10
dfs(n2, m2, i)
print(Base 10: esths.len esthetic numbers between n1 and m1:)
I all
L(esth) esths
print(esth, end' I (L.index + 1) % perLine == 0 {"\n"} E )
print()
E
L(i) 0 .< perLine
print(esths[i], end' )
print("\n............")
L(i) esths.len - perLine .< esths.len
print(esths[i], end' )
print()
print()
L(b) 2..16
print(Base b: (4 * b)th to (6 * b)th esthetic numbers:)
V n = Int64(1)
V c = Int64(0)
L c < 6 * b
I isEsthetic(n, b)
c++
I c >= 4 * b
print(String(n, radix' b), end' )
n++
print("\n")
listEsths(1000, 1010, 9999, 9898, 16, 1B)
listEsths(100'000'000, 101'010'101, 130'000'000, 123'456'789, 9, 1B)
listEsths(100'000'000'000, 101'010'101'010, 130'000'000'000, 123'456'789'898, 7, 0B)
listEsths(100'000'000'000'000, 101'010'101'010'101, 130'000'000'000, 123'456'789'898'989, 5, 0B)
listEsths(100'000'000'000'000'000, 101'010'101'010'101'010, 130'000'000'000'000'000, 123'456'789'898'989'898, 4, 0B)

View file

@ -0,0 +1,95 @@
BEGIN # find some esthetic numbers: numbers whose successive digits differ by 1 #
# returns TRUE if n is esthetic in the specified base, FALSE otherwise #
PRIO ISESTHETIC = 1;
OP ISESTHETIC = ( INT n, base )BOOL:
BEGIN
INT v := ABS n;
BOOL is esthetic := TRUE;
INT prev digit := v MOD base;
v OVERAB base;
WHILE v > 0 AND is esthetic
DO
INT next digit := v MOD base;
is esthetic := ABS ( next digit - prev digit ) = 1;
prev digit := next digit;
v OVERAB base
OD;
is esthetic
END # ISESTHETIC # ;
# returns an array of the first n esthetic numbers in the specified base #
PRIO ESTHETIC = 1;
OP ESTHETIC = ( INT n, base )[]INT:
BEGIN
[ 1 : n ]INT result;
INT e count := 0;
FOR i WHILE e count < n DO
IF i ISESTHETIC base THEN result[ e count +:= 1 ] := i FI
OD;
result
END # ESTHETIC # ;
# returns a string erpresentation of n in the specified base, 2 <= base <= 16 must be TRUE #
PRIO TOBASESTRING = 1;
OP TOBASESTRING = ( INT n, base )STRING:
IF base < 2 OR base > 16
THEN # invalid vbase #
"?" + whole( n, 0 ) + ":" + whole( base, 0 ) + "?"
ELSE
INT v := ABS n;
STRING digits = "0123456789abcdef";
STRING result := digits[ ( v MOD base ) + 1 ];
WHILE ( v OVERAB base ) > 0 DO
digits[ ( v MOD base ) + 1 ] +=: result
OD;
IF n < 0 THEN "-" +=: result FI;
result
FI # TOBASESTRING # ;
# sets count to the number of esthetic numbers with length digits in base b less than max #
# also displays the esthetic numbers #
PROC show esthetic = ( INT number, base, length, max, REF INT count )VOID:
IF length = 1
THEN # number is esthetic #
IF number <= max THEN
# number is in the required range #
print( ( " ", whole( number, 0 ) ) );
IF ( count +:= 1 ) MOD 9 = 0 THEN print( ( newline ) ) FI
FI
ELSE
# find the esthetic numbers that start with number #
INT digit = number MOD base;
INT prefix = number * base;
IF digit > 0 THEN # can have a lower digit #
show esthetic( prefix + ( digit - 1 ), base, length - 1, max, count )
FI;
IF digit < base - 1 THEN # can have a higher digit #
show esthetic( prefix + ( digit + 1 ), base, length - 1, max, count )
FI
FI # show esthetic # ;
# task #
# esthetic numbers from base * 4 to base * 6 for bases 2 to 16 #
FOR base FROM 2 TO 16 DO
INT e from = base * 4;
INT e to = base * 6;
print( ( "Esthetic numbers ", whole( e from, 0 ), " to ", whole( e to, 0 ), " in base ", whole( base, 0 ), newline ) );
[]INT e numbers = e to ESTHETIC base;
print( ( " " ) );
FOR n FROM e from TO e to DO
print( ( " ", e numbers[ n ] TOBASESTRING base ) )
OD;
print( ( newline ) )
OD;
# esthetic base 10 numbers between 1000 and 9999 #
print( ( "Base 10 eshetic numbers between 1000 and 9999", newline ) );
INT e count := 0;
FOR i FROM 1000 TO 9999 DO
IF i ISESTHETIC 10 THEN
print( ( " ", whole( i, 0 ) ) );
IF ( e count +:= 1 ) MOD 16 = 0 THEN print( ( newline ) ) FI
FI
OD;
print( ( newline, newline ) );
print( ( "Esthetic numbers between 100 000 000 and 130 000 000:", newline ) );
e count := 0;
show esthetic( 1, 10, 9, 130 000 000, e count );
print( ( newline ) );
print( ( "Found ", whole( e count, 0 ), " esthetic numbers", newline ) )
END

View file

@ -0,0 +1,51 @@
esthetic?: function [n, b][
if n=0 -> return false
k: n % b
l: n / b
while [l>0][
j: l % b
if 1 <> abs k-j -> return false
l: l / b
k: j
]
return true
]
HEX: "0000000000ABCDEF"
getHex: function [ds][
map ds 'd [
(d < 10)? -> to :string d
-> to :string HEX\[d]
]
]
findEsthetics: function [base][
limDown: base * 4
limUp: base * 6
cnt: 0
i: 1
result: new []
while [cnt < limUp][
if esthetic? i base [
cnt: cnt + 1
if cnt >= limDown ->
'result ++ join getHex digits.base: base i
]
i: i + 1
]
print ["Base" base "->" (to :string limDown)++"th" "to" (to :string limUp)++"th" "esthetic numbers:"]
print result
print ""
]
loop 2..16 'bs ->
findEsthetics bs
print "Esthetic numbers between 1000 and 9999:"
loop split.every: 16 select 1000..9999 'num -> esthetic? num 10 'row [
print map to [:string] row 'item -> pad item 4
]

View file

@ -0,0 +1,120 @@
#include <functional>
#include <iostream>
#include <sstream>
#include <vector>
std::string to(int n, int b) {
static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::stringstream ss;
while (n > 0) {
auto rem = n % b;
n = n / b;
ss << BASE[rem];
}
auto fwd = ss.str();
return std::string(fwd.rbegin(), fwd.rend());
}
uint64_t uabs(uint64_t a, uint64_t b) {
if (a < b) {
return b - a;
}
return a - b;
}
bool isEsthetic(uint64_t n, uint64_t b) {
if (n == 0) {
return false;
}
auto i = n % b;
n /= b;
while (n > 0) {
auto j = n % b;
if (uabs(i, j) != 1) {
return false;
}
n /= b;
i = j;
}
return true;
}
void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) {
std::vector<uint64_t> esths;
const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) {
auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) {
if (i >= n && i <= m) {
esths.push_back(i);
}
if (i == 0 || i > m) {
return;
}
auto d = i % 10;
auto i1 = i * 10 + d - 1;
auto i2 = i1 + 2;
if (d == 0) {
dfs_ref(n, m, i2, dfs_ref);
} else if (d == 9) {
dfs_ref(n, m, i1, dfs_ref);
} else {
dfs_ref(n, m, i1, dfs_ref);
dfs_ref(n, m, i2, dfs_ref);
}
};
dfs_impl(n, m, i, dfs_impl);
};
for (int i = 0; i < 10; i++) {
dfs(n2, m2, i);
}
auto le = esths.size();
printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m);
if (all) {
for (size_t c = 0; c < esths.size(); c++) {
auto esth = esths[c];
printf("%llu ", esth);
if ((c + 1) % perLine == 0) {
printf("\n");
}
}
printf("\n");
} else {
for (int c = 0; c < perLine; c++) {
auto esth = esths[c];
printf("%llu ", esth);
}
printf("\n............\n");
for (size_t i = le - perLine; i < le; i++) {
auto esth = esths[i];
printf("%llu ", esth);
}
printf("\n");
}
printf("\n");
}
int main() {
for (int b = 2; b <= 16; b++) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b);
for (int n = 1, c = 0; c < 6 * b; n++) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
std::cout << to(n, b) << ' ';
}
}
}
printf("\n");
}
printf("\n");
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true);
listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false);
listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false);
listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false);
return 0;
}

View file

@ -0,0 +1,118 @@
#include <stdio.h>
#include <string.h>
#include <locale.h>
typedef int bool;
typedef unsigned long long ull;
#define TRUE 1
#define FALSE 0
char as_digit(int d) {
return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a';
}
void revstr(char *str) {
int i, len = strlen(str);
char t;
for (i = 0; i < len/2; ++i) {
t = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = t;
}
}
char* to_base(char s[], ull n, int b) {
int i = 0;
while (n) {
s[i++] = as_digit(n % b);
n /= b;
}
s[i] = '\0';
revstr(s);
return s;
}
ull uabs(ull a, ull b) {
return a > b ? a - b : b - a;
}
bool is_esthetic(ull n, int b) {
int i, j;
if (!n) return FALSE;
i = n % b;
n /= b;
while (n) {
j = n % b;
if (uabs(i, j) != 1) return FALSE;
n /= b;
i = j;
}
return TRUE;
}
ull esths[45000];
int le = 0;
void dfs(ull n, ull m, ull i) {
ull d, i1, i2;
if (i >= n && i <= m) esths[le++] = i;
if (i == 0 || i > m) return;
d = i % 10;
i1 = i * 10 + d - 1;
i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) {
int i;
le = 0;
for (i = 0; i < 10; ++i) {
dfs(n2, m2, i);
}
printf("Base 10: %'d esthetic numbers between %'llu and %'llu:\n", le, n, m);
if (all) {
for (i = 0; i < le; ++i) {
printf("%llu ", esths[i]);
if (!(i+1)%per_line) printf("\n");
}
} else {
for (i = 0; i < per_line; ++i) printf("%llu ", esths[i]);
printf("\n............\n");
for (i = le - per_line; i < le; ++i) printf("%llu ", esths[i]);
}
printf("\n\n");
}
int main() {
ull n;
int b, c;
char ch[15] = {0};
for (b = 2; b <= 16; ++b) {
printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b);
for (n = 1, c = 0; c < 6 * b; ++n) {
if (is_esthetic(n, b)) {
if (++c >= 4 * b) printf("%s ", to_base(ch, n, b));
}
}
printf("\n\n");
}
char *oldLocale = setlocale(LC_NUMERIC, NULL);
setlocale(LC_NUMERIC, "");
// the following all use the obvious range limitations for the numbers in question
list_esths(1000, 1010, 9999, 9898, 16, TRUE);
list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE);
list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE);
list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE);
list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE);
setlocale(LC_NUMERIC, oldLocale);
return 0;
}

View file

@ -0,0 +1,99 @@
import std.conv;
import std.stdio;
ulong uabs(ulong a, ulong b) {
if (a > b) {
return a - b;
}
return b - a;
}
bool isEsthetic(ulong n, ulong b) {
if (n == 0) {
return false;
}
auto i = n % b;
n /= b;
while (n > 0) {
auto j = n % b;
if (uabs(i, j) != 1) {
return false;
}
n /= b;
i = j;
}
return true;
}
ulong[] esths;
void dfs(ulong n, ulong m, ulong i) {
if (i >= n && i <= m) {
esths ~= i;
}
if (i == 0 || i > m) {
return;
}
auto d = i % 10;
auto i1 = i * 10 + d - 1;
auto i2 = i1 + 2;
if (d == 0) {
dfs(n, m, i2);
} else if (d == 9) {
dfs(n, m, i1);
} else {
dfs(n, m, i1);
dfs(n, m, i2);
}
}
void listEsths(ulong n, ulong n2, ulong m, long m2, int perLine, bool all) {
esths.length = 0;
for (auto i = 0; i < 10; i++) {
dfs(n2, m2, i);
}
auto le = esths.length;
writefln("Base 10: %s esthetic numbers between %s and %s:", le, n, m);
if (all) {
foreach (c, esth; esths) {
write(esth, ' ');
if ((c + 1) % perLine == 0) {
writeln;
}
}
writeln;
} else {
for (auto i = 0; i < perLine; i++) {
write(esths[i], ' ');
}
writeln("\n............");
for (auto i = le - perLine; i < le; i++) {
write(esths[i], ' ');
}
writeln;
}
writeln;
}
void main() {
for (auto b = 2; b <= 16; b++) {
writefln("Base %d: %dth to %dth esthetic numbers:", b, 4 * b, 6 * b);
for (auto n = 1, c = 0; c < 6 * b; n++) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
write(to!string(n, b), ' ');
}
}
}
writeln;
}
writeln;
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths(cast(ulong) 1e8, 101_010_101, 13*cast(ulong) 1e7, 123_456_789, 9, true);
listEsths(cast(ulong) 1e11, 101_010_101_010, 13*cast(ulong) 1e10, 123_456_789_898, 7, false);
listEsths(cast(ulong) 1e14, 101_010_101_010_101, 13*cast(ulong) 1e13, 123_456_789_898_989, 5, false);
listEsths(cast(ulong) 1e17, 101_010_101_010_101_010, 13*cast(ulong) 1e16, 123_456_789_898_989_898, 4, false);
}

View file

@ -0,0 +1,107 @@
type TIntArray = array of integer;
function GetRadixString(L: Integer; Radix: Byte): string;
{Converts integer a string of any radix}
const HexChars: array[0..15] Of char =
('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
var I: integer;
var S: string;
var Sign: string[1];
begin
Result:='';
If (L < 0) then
begin
Sign:='-';
L:=Abs(L);
end
else Sign:='';
S:='';
repeat
begin
I:=L mod Radix;
S:=HexChars[I] + S;
L:=L div Radix;
end
until L = 0;
Result:=Sign + S;
end;
procedure StrToInts(S: string; var IA: TIntArray);
{Convert numerical string of any radix and convert to numbers}
var I: integer;
begin
for I:=1 to Length(S) do
begin
SetLength(IA,Length(IA)+1);
if S[I]<#$40 then IA[High(IA)]:=Byte(S[I])-$30
else IA[High(IA)]:=(Byte(S[I])-$41)+10;
end;
end;
function IsEsthetic(N: integer; Radix: byte): boolean;
{Check number to see if neighboring digits are no more than one differents.}
var I: integer;
var S: string;
var IA: TIntArray;
begin
Result:=False;
S:=GetRadixString(N,Radix);
StrToInts(S,IA);
for I:=0 to Length(IA)-2 do
if Abs(IA[I+1]-IA[I])<>1 then exit;
Result:=True;
end;
function GetEstheticRange(Memo: TMemo; Range1,Range2,Count1,Count2,Base: integer): integer;
{Find an Esthetic number in the domain of Range and Counts specified}
var I,Cnt: integer;
var S: string;
begin
Cnt:=0; Result:=0;
S:='';
for I:=Range1 to Range2 do
if IsEsthetic(I,Base) then
begin
Inc(Cnt);
if (Cnt>=Count1) and (Cnt<=Count2) then
begin
Inc(Result);
S:=S+' '+GetRadixString(I,Base);
if (Result mod 10)=0 then S:=S+#$0D#$0A;
end;
if Cnt>=Count2 then break;
end;
Memo.Lines.Add(S);
end;
procedure FindEstheticNumbers(Memo: TMemo);
{Find Esthetic numbers for Rosetta Code problem}
var Base,First,Last,Cnt: integer;
begin
for Base:=2 to 16 do
begin
First:=Base*4; Last:=Base*6;
Memo.Lines.Add(Format('Base %2d: %2dth to %2dth esthetic numbers:',[Base,First,Last]));
Cnt:=GetEstheticRange(Memo,0,High(Integer),First,Last,Base);
Memo.Lines.Add('Count: '+IntToStr(Cnt));
Memo.Lines.Add('');
end;
Memo.Lines.Add('Base 10: esthetic numbers between 1000,9999');
Cnt:=GetEstheticRange(Memo,1000,9999,0,High(Integer),10);
Memo.Lines.Add('Count: '+IntToStr(Cnt));
Memo.Lines.Add('');
Memo.Lines.Add('Base 10: esthetic numbers between 100000000,130000000');
Cnt:=GetEstheticRange(Memo,100000000,130000000,0,High(Integer),10);
Memo.Lines.Add('Count: '+IntToStr(Cnt));
Memo.Lines.Add('');
end;

View file

@ -0,0 +1,12 @@
// Generate Esthetic Numbers. Nigel Galloway: March 21st., 2020
let rec fN Σ n g = match g with h::t -> match List.head h with
0 -> fN ((1::h)::Σ) n t
|g when g=n-1 -> fN ((g-1::h)::Σ) n t
|g -> fN ((g-1::h)::(g+1::h)::Σ) n t
|_ -> Σ
let Esthetic n = let Esthetic, g = fN [] n, [1..n-1] |> List.map(fun n->[n])
Seq.unfold(fun n->Some(n,Esthetic(List.rev n)))(g) |> Seq.concat
let EtoS n = let g = "0123456789abcdef".ToCharArray()
n |> List.map(fun n->g.[n]) |> List.rev |> Array.ofList |> System.String

View file

@ -0,0 +1 @@
[2..16]|>List.iter(fun n->printfn "\nBase %d" n; Esthetic n|>Seq.skip(4*n-1)|>Seq.take((6-4)*n+1)|>Seq.iter(EtoS >> printfn "%s"))

View file

@ -0,0 +1 @@
Esthetic 10|>Seq.map(EtoS>>int)|>Seq.skipWhile(fun n->n<1000)|>Seq.takeWhile(fun n->n<9999)|>Seq.iter(printfn "%d");;

View file

@ -0,0 +1 @@
Esthetic 10|>Seq.map(EtoS>>int)|>Seq.skipWhile(fun n->n<100000000)|>Seq.takeWhile(fun n->n< 130000000)|>Seq.iter(printfn "%d")

View file

@ -0,0 +1 @@
Esthetic 10|>Seq.map(EtoS>>int64)|>Seq.skipWhile(fun n->n<100000000000L)|>Seq.takeWhile(fun n->n<130000000000L)|>Seq.iter(printfn "%d")

View file

@ -0,0 +1,54 @@
USING: combinators deques dlists formatting grouping io kernel
locals make math math.order math.parser math.ranges
math.text.english prettyprint sequences sorting strings ;
:: bfs ( from to num base -- )
DL{ } clone :> q
base 1 - :> ld
num q push-front
[ q deque-empty? ]
[
q pop-back :> step-num
step-num from to between? [ step-num , ] when
step-num zero? step-num to > or
[
step-num base mod :> last-digit
step-num base * last-digit 1 - + :> a
step-num base * last-digit 1 + + :> b
last-digit
{
{ 0 [ b q push-front ] }
{ ld [ a q push-front ] }
[ drop a q push-front b q push-front ]
} case
] unless
] until ;
:: esthetics ( from to base -- seq )
[ base <iota> [| num | from to num base bfs ] each ]
{ } make natural-sort ;
: .seq ( seq width -- )
group [ [ dup string? [ write ] [ pprint ] if bl ] each nl ]
each nl ;
:: show ( base -- )
base [ 4 * ] [ 6 * ] bi :> ( from to )
from to [ dup ordinal-suffix ] bi@ base
"%d%s through %d%s esthetic numbers in base %d\n" printf
from to 1 + 0 5000 ! enough for base 16
base esthetics subseq [ base >base ] map 17 .seq ;
2 16 [a,b] [ show ] each
"Base 10 numbers between 1,000 and 9,999:" print
1,000 9,999 10 esthetics 16 .seq
"Base 10 numbers between 100,000,000 and 130,000,000:" print
100,000,000 130,000,000 10 esthetics 9 .seq
"Count of base 10 esthetic numbers between zero and one quadrillion:"
print 0 1e15 10 esthetics length .

View file

@ -0,0 +1,42 @@
\ Returns the next esthetic number in the given base after n, where n is an
\ esthetic number in that base or one less than a power of base.
: next_esthetic_number { n base -- n }
n 1+ base < if n 1+ exit then
n base / dup base mod
dup n base mod 1+ = if dup 1+ base < if 2drop n 2 + exit then then
drop base recurse
dup base mod
dup 0= if 1+ else 1- then
swap base * + ;
: print_esthetic_numbers { min max per_line -- }
." Esthetic numbers in base 10 between " min 1 .r ." and " max 1 .r ." :" cr
0
min 1- 10 next_esthetic_number
begin
dup max <=
while
dup 4 .r
swap 1+ dup per_line mod 0= if cr else space then swap
10 next_esthetic_number
repeat
drop
cr ." count: " . cr ;
: main
17 2 do
i 4 * i 6 * { min max }
." Esthetic numbers in base " i 1 .r ." from index " min 1 .r ." through index " max 1 .r ." :" cr
0
max 1+ 1 do
j next_esthetic_number
i min >= if dup ['] . j base-execute then
loop
drop
cr cr
loop
1000 9999 16 print_esthetic_numbers cr
100000000 130000000 8 print_esthetic_numbers ;
main
bye

View file

@ -0,0 +1,62 @@
dim shared as string*16 digits = "0123456789ABCDEF"
function get_digit( n as uinteger ) as string
return mid(digits, n+1, 1)
end function
function find_digit( s as string ) as integer
for i as uinteger = 1 to len(digits)
if s = mid(digits, i, 1) then return i
next i
return -999
end function
sub make_base( byval n as uinteger, bse as uinteger, byref ret as string )
if n = 0 then ret = "0" else ret = ""
dim as uinteger m
while n > 0
m = n mod bse
ret = mid(digits, m+1, 1) + ret
n = (n - m)/bse
wend
end sub
function is_esthetic( number as string ) as boolean
if number = "0" then return false
if len(number) = 1 then return true
dim as integer curr = find_digit( left(number,1) ), last, i
for i = 2 to len(number)
last = curr
curr = find_digit( mid(number, i, 1) )
if abs( last - curr ) <> 1 then return false
next i
return true
end function
dim as uinteger b, c
dim as ulongint i
dim as string number
for b = 2 to 16
print "BASE ";b
i = 0 : c = 0
while c <= 6*b
i += 1
make_base i, b, number
if is_esthetic( number ) then
c += 1
if c >= 4*b then print number;" ";
end if
wend
print
next b
print "BASE TEN"
for i = 1000 to 9999
make_base i, 10, number
if is_esthetic(number) then print number;" ";
next i
print
print "STRETCH GOAL"
for i = 100000000 to 130000000
make_base i, 10, number
if is_esthetic(number) then print number;" ";
next i

View file

@ -0,0 +1,110 @@
package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
}

View file

@ -0,0 +1,36 @@
import Data.List (unfoldr, genericIndex)
import Control.Monad (replicateM, foldM, mzero)
-- a predicate for esthetic numbers
isEsthetic b = all ((== 1) . abs) . differences . toBase b
where
differences lst = zipWith (-) lst (tail lst)
-- Monadic solution, inefficient for small bases.
esthetics_m b =
do differences <- (\n -> replicateM n [-1, 1]) <$> [0..]
firstDigit <- [1..b-1]
differences >>= fromBase b <$> scanl (+) firstDigit
-- Much more efficient iterative solution (translation from Python).
-- Uses simple list as an ersatz queue.
esthetics b = tail $ fst <$> iterate step (undefined, q)
where
q = [(d, d) | d <- [1..b-1]]
step (_, queue) =
let (num, lsd) = head queue
new_lsds = [d | d <- [lsd-1, lsd+1], d < b, d >= 0]
in (num, tail queue ++ [(num*b + d, d) | d <- new_lsds])
-- representation of numbers as digits
fromBase b = foldM f 0
where f r d | d < 0 || d >= b = mzero
| otherwise = pure (r*b + d)
toBase b = reverse . unfoldr f
where
f 0 = Nothing
f n = let (q, r) = divMod n b in Just (r, q)
showInBase b = foldMap (pure . digit) . toBase b
where digit = genericIndex (['0'..'9'] <> ['a'..'z'])

View file

@ -0,0 +1,4 @@
isesthetic=: 10&$: :(1 */ .=2 |@-/\ #.inv)"0
gen=: {{r=.$k=.1 while.y>#r do. r=.r,k#~u k
k=.1+({:k)+i.2*#k end.y{.r}}

View file

@ -0,0 +1,36 @@
tobase=: (a.{~;48 97(+ i.)each 10 26) {~ #.inv
taskB=: {{;:inv y tobase&.> (<:4*y)}. y&isesthetic gen 6*y}}
taskB 2
10101010 101010101 1010101010 10101010101 101010101010
taskB 3
1210 1212 2101 2121 10101 10121 12101
taskB 4
323 1010 1012 1210 1212 1232 2101 2121 2123
taskB 5
323 343 432 434 1010 1012 1210 1212 1232 1234 2101
taskB 6
343 345 432 434 454 543 545 1010 1012 1210 1212 1232 1234
taskB 7
345 432 434 454 456 543 545 565 654 656 1010 1012 1210 1212 1232
taskB 8
432 434 454 456 543 545 565 567 654 656 676 765 767 1010 1012 1210 1212
taskB 9
434 454 456 543 545 565 567 654 656 676 678 765 767 787 876 878 1010 1012 1210
taskB 10
454 456 543 545 565 567 654 656 676 678 765 767 787 789 876 878 898 987 989 1010 1012
taskB 11
456 543 545 565 567 654 656 676 678 765 767 787 789 876 878 898 89a 987 989 9a9 a98 a9a 1010
taskB 12
543 545 565 567 654 656 676 678 765 767 787 789 876 878 898 89a 987 989 9a9 9ab a98 a9a aba ba9 bab
taskB 13
545 565 567 654 656 676 678 765 767 787 789 876 878 898 89a 987 989 9a9 9ab a98 a9a aba abc ba9 bab bcb cba
taskB 14
565 567 654 656 676 678 765 767 787 789 876 878 898 89a 987 989 9a9 9ab a98 a9a aba abc ba9 bab bcb bcd cba cbc cdc
taskB 15
567 654 656 676 678 765 767 787 789 876 878 898 89a 987 989 9a9 9ab a98 a9a aba abc ba9 bab bcb bcd cba cbc cdc cde dcb dcd
taskB 16
654 656 676 678 765 767 787 789 876 878 898 89a 987 989 9a9 9ab a98 a9a aba abc ba9 bab bcb bcd cba cbc cdc cde dcb dcd ded def edc
(#~ isesthetic) 1000+i.1000
1010 1012 1210 1212 1232 1234

View file

@ -0,0 +1,4 @@
$e=: x: (#~ isesthetic) 1e8+i.1+3e7
126
q:126
2 3 3 7

View file

@ -0,0 +1,22 @@
graph=: </./|:0 1,10 10#:(#~ isesthetic)10+i.90
next=: [:; (0 10#.],.graph {::~10|])each
next^:3]1
1010 1012 1210 1212 1232 1234
$next^:8]1
126
14 9$next^:8]1
101010101 101010121 101010123 101012101 101012121 101012123 101012321 101012323 101012343
101012345 101210101 101210121 101210123 101212101 101212121 101212123 101212321 101212323
101212343 101212345 101232101 101232121 101232123 101232321 101232323 101232343 101232345
101234321 101234323 101234343 101234345 101234543 101234545 101234565 101234567 121010101
121010121 121010123 121012101 121012121 121012123 121012321 121012323 121012343 121012345
121210101 121210121 121210123 121212101 121212121 121212123 121212321 121212323 121212343
121212345 121232101 121232121 121232123 121232321 121232323 121232343 121232345 121234321
121234323 121234343 121234345 121234543 121234545 121234565 121234567 123210101 123210121
123210123 123212101 123212121 123212123 123212321 123212323 123212343 123212345 123232101
123232121 123232123 123232321 123232323 123232343 123232345 123234321 123234323 123234343
123234345 123234543 123234545 123234565 123234567 123432101 123432121 123432123 123432321
123432323 123432343 123432345 123434321 123434323 123434343 123434345 123434543 123434545
123434565 123434567 123454321 123454323 123454343 123454345 123454543 123454545 123454565
123454567 123456543 123456545 123456565 123456567 123456765 123456767 123456787 123456789

View file

@ -0,0 +1,106 @@
import java.util.ArrayList;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class EstheticNumbers {
interface RecTriConsumer<A, B, C> {
void accept(RecTriConsumer<A, B, C> f, A a, B b, C c);
}
private static boolean isEsthetic(long n, long b) {
if (n == 0) {
return false;
}
var i = n % b;
var n2 = n / b;
while (n2 > 0) {
var j = n2 % b;
if (Math.abs(i - j) != 1) {
return false;
}
n2 /= b;
i = j;
}
return true;
}
private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) {
var esths = new ArrayList<Long>();
var dfs = new RecTriConsumer<Long, Long, Long>() {
public void accept(Long n, Long m, Long i) {
accept(this, n, m, i);
}
@Override
public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) {
if (n <= i && i <= m) {
esths.add(i);
}
if (i == 0 || i > m) {
return;
}
var d = i % 10;
var i1 = i * 10 + d - 1;
var i2 = i1 + 2;
if (d == 0) {
f.accept(f, n, m, i2);
} else if (d == 9) {
f.accept(f, n, m, i1);
} else {
f.accept(f, n, m, i1);
f.accept(f, n, m, i2);
}
}
};
LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i));
var le = esths.size();
System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m);
if (all) {
for (int i = 0; i < esths.size(); i++) {
System.out.printf("%d ", esths.get(i));
if ((i + 1) % perLine == 0) {
System.out.println();
}
}
} else {
for (int i = 0; i < perLine; i++) {
System.out.printf("%d ", esths.get(i));
}
System.out.println();
System.out.println("............");
for (int i = le - perLine; i < le; i++) {
System.out.printf("%d ", esths.get(i));
}
}
System.out.println();
System.out.println();
}
public static void main(String[] args) {
IntStream.rangeClosed(2, 16).forEach(b -> {
System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b);
var n = 1L;
var c = 0L;
while (c < 6 * b) {
if (isEsthetic(n, b)) {
c++;
if (c >= 4 * b) {
System.out.printf("%s ", Long.toString(n, b));
}
}
n++;
}
System.out.println();
});
System.out.println();
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true);
listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false);
listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false);
listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false);
}
}

View file

@ -0,0 +1,39 @@
function isEsthetic(inp, base = 10) {
let arr = inp.toString(base).split('');
if (arr.length == 1) return false;
for (let i = 0; i < arr.length; i++)
arr[i] = parseInt(arr[i], base);
for (i = 0; i < arr.length-1; i++)
if (Math.abs(arr[i]-arr[i+1]) !== 1) return false;
return true;
}
function collectEsthetics(base, range) {
let out = [], x;
if (range) {
for (x = range[0]; x < range[1]; x++)
if (isEsthetic(x)) out.push(x);
return out;
} else {
x = 1;
while (out.length < base*6) {
s = x.toString(base);
if (isEsthetic(s, base)) out.push(s.toUpperCase());
x++;
}
return out.slice(base*4);
}
}
// main
let d = new Date();
for (let x = 2; x <= 36; x++) { // we put b17 .. b36 on top, because we can
console.log(`${x}:`);
console.log( collectEsthetics(x),
(new Date() - d) / 1000 + ' s');
}
console.log( collectEsthetics(10, [1000, 9999]),
(new Date() - d) / 1000 + ' s' );
console.log( collectEsthetics(10, [1e8, 1.3e8]),
(new Date() - d) / 1000 + ' s' );

View file

@ -0,0 +1,282 @@
(() => {
"use strict";
// -------- ESTHETIC NUMBERS IN A GIVEN BASE ---------
// estheticNumbersInBase :: Int -> [Int]
const estheticNumbersInBase = b =>
// An infinite sequence of numbers which
// are esthetic in the given base.
tail(fmapGen(x => x[0])(
iterate(([, queue]) => {
const [num, lsd] = queue[0];
const
newDigits = [lsd - 1, lsd + 1]
.flatMap(
d => (d < b && d >= 0) ? (
[d]
) : []
);
return Tuple(num)(
queue.slice(1).concat(
newDigits.flatMap(d => [
Tuple((num * b) + d)(d)
])
)
);
})(
Tuple()(
enumFromTo(1)(b - 1).flatMap(
d => [Tuple(d)(d)]
)
)
)
));
// ---------------------- TESTS ----------------------
const main = () => {
const samples = b => {
const
i = b * 4,
j = b * 6;
return unlines([
`Esthetics [${i}..${j}] for base ${b}:`,
...chunksOf(10)(
compose(drop(i - 1), take(j))(
estheticNumbersInBase(b)
).map(n => n.toString(b))
)
.map(unwords)
]);
};
const takeInRange = ([a, b]) =>
compose(
dropWhile(x => x < a),
takeWhileGen(x => x <= b)
);
return [
enumFromTo(2)(16)
.map(samples)
.join("\n\n"),
[
Tuple(1000)(9999),
Tuple(100000000)(130000000)
]
.map(
([lo, hi]) => unlines([
`Base 10 Esthetics in range [${lo}..${hi}]:`,
unlines(
chunksOf(6)(
takeInRange([lo, hi])(
estheticNumbersInBase(10)
)
)
.map(unwords)
)
])
).join("\n\n")
].join("\n\n");
};
// --------------------- GENERIC ---------------------
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: "Tuple",
"0": a,
"1": b,
length: 2,
*[Symbol.iterator]() {
for (const k in this) {
if (!isNaN(k)) {
yield this[k];
}
}
}
});
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n => {
// xs split into sublists of length n.
// The last sublist will be short if n
// does not evenly divide the length of xs .
const go = xs => {
const chunk = xs.slice(0, n);
return 0 < chunk.length ? (
[chunk].concat(
go(xs.slice(n))
)
) : [];
};
return go;
};
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// drop :: Int -> [a] -> [a]
// drop :: Int -> Generator [a] -> Generator [a]
// drop :: Int -> String -> String
const drop = n =>
xs => Infinity > length(xs) ? (
xs.slice(n)
) : (take(n)(xs), xs);
// dropWhile :: (a -> Bool) -> [a] -> [a]
// dropWhile :: (Char -> Bool) -> String -> String
const dropWhile = p =>
// The suffix remaining after takeWhile p xs.
xs => {
const n = xs.length;
return xs.slice(
0 < n ? until(
i => n === i || !p(xs[i])
)(i => 1 + i)(0) : 0
);
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
const fmapGen = f =>
// The map of f over a stream of generator values.
function* (gen) {
let v = gen.next();
while (!v.done) {
yield f(v.value);
v = gen.next();
}
};
// iterate :: (a -> a) -> a -> Gen [a]
const iterate = f =>
// An infinite list of repeated
// applications of f to x.
function* (x) {
let v = x;
while (true) {
yield v;
v = f(v);
}
};
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
"GeneratorFunction" !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
// tail :: [a] -> [a]
const tail = xs =>
// A new list consisting of all
// items of xs except the first.
"GeneratorFunction" !== xs.constructor
.constructor.name ? (
(ys => 0 < ys.length ? ys.slice(1) : [])(
xs
)
) : (take(1)(xs), xs);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}).flat();
// takeWhileGen :: (a -> Bool) -> Gen [a] -> [a]
const takeWhileGen = p => xs => {
const ys = [];
let
nxt = xs.next(),
v = nxt.value;
while (!nxt.done && p(v)) {
ys.push(v);
nxt = xs.next();
v = nxt.value;
}
return ys;
};
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join("\n");
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p =>
// The value resulting from repeated applications
// of f to the seed value x, terminating when
// that result returns true for the predicate p.
f => x => {
let v = x;
while (!p(v)) {
v = f(v);
}
return v;
};
// unwords :: [String] -> String
const unwords = xs =>
// A space-separated string derived
// from a list of words.
xs.join(" ");
// MAIN ---
return main();
})();

View file

@ -0,0 +1,87 @@
### Preliminaries
# _nwise/1 is included here for the sake of gojq:
def _nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def tobase($b):
def digit: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[.:.+1];
def mod: . % $b;
def div: ((. - mod) / $b);
def digits: recurse( select(. > 0) | div) | mod ;
# For jq it would be wise to protect against `infinite` as input, but using `isinfinite` confuses gojq
select( (tostring|test("^[0-9]+$")) and 2 <= $b and $b <= 36)
| if . == 0 then "0"
else [digits | digit] | reverse[1:] | add
end;
### Esthetic Numbers
def isEsthetic($b):
if . == 0 then false
else {i: (. % $b), n: ((./$b)|floor) }
| until (.n <= 0;
(.n % $b) as $j
| if (.i - $j)|length != 1 # abs
then .n = -1 #flag
else .n |= ((./$b)|floor)
| .i = $j
end)
| .n != -1
end;
# depth-first search
# input: {esths}
def dfs($n; $m; $i):
if ($i >= $n and $i <= $m) then .esths += [$i] else . end
| if ($i == 0 or $i > $m) then .
else ($i % 10) as $d
| ($i*10 + $d - 1) as $i1
| ($i1 + 2) as $i2
| if $d == 0
then dfs($n; $m; $i2)
elif $d == 9
then dfs($n; $m; $i1)
else dfs($n; $m; $i1) | dfs($n; $m; $i2)
end
end;
### The tasks
def listEsths(n; n2; m; m2; $perLine; $all):
( {esths: []}
| reduce range(0;10) as $i (.; dfs(n2; m2; $i) )
| "Base 10: \(.esths|length) esthetic numbers between \(n) and \(m)",
if $all
then .esths | _nwise($perLine) | join(" ")
else
(.esths[:$perLine] | join(" ")),
"............",
(.esths[-$perLine:] | join(" "))
end ),
"";
def task($maxBase):
range (2; 1+$maxBase) as $b
| "Base \($b): \(4*$b)th to \(6*$b)th esthetic numbers:",
( [{ n: 1, c: 0 }
| while (.c <= 6*$b;
.emit = null
| if (.n|isEsthetic($b))
then .c += 1
| if .c >= 4*$b
then .emit = "\(.n | tobase($b))"
else .
end
else .
end
| .n += 1 )
| select(.emit).emit]
| _nwise(10) | join(" ") ),
"" ;
task(16),
# the following all use the obvious range limitations for the numbers in question
listEsths(1000; 1010; 9999; 9898; 16; true),
listEsths(1e8; 101010101; 13*1e7; 123456789; 9; true),
listEsths(1e11; 101010101010; 13*1e10; 123456789898; 7; false),
listEsths(1e14; 101010101010101; 13*1e13; 123456789898989; 5; false)

View file

@ -0,0 +1,107 @@
using Formatting
import Base.iterate, Base.IteratorSize, Base.IteratorEltype
"""
struct Esthetic
Used for iteration of esthetic numbers
"""
struct Esthetic{T}
lowerlimit::T where T <: Integer
base::T
upperlimit::T
Esthetic{T}(n, bas, m=typemax(T)) where T = new{T}(nextesthetic(n, bas), bas, m)
end
Base.IteratorSize(n::Esthetic) = Base.IsInfinite()
Base.IteratorEltype(n::Esthetic) = Integer
function Base.iterate(es::Esthetic, state=typeof(es.lowerlimit)[])
state = isempty(state) ? digits(es.lowerlimit, base=es.base) : increment!(state, es.base, 1)
n = toInt(state, es.base)
return n <= es.upperlimit ? (n, state) : nothing
end
isesthetic(n, b) = (d = digits(n, base=b); all(i -> abs(d[i] - d[i + 1]) == 1, 1:length(d)-1))
toInt(dig, bas) = foldr((i, j) -> i + bas * j, dig)
nextesthetic(n, b) = for i in n:typemax(typeof(n)) if isesthetic(i, b) return i end; end
""" Fill the digits below pos in vector with the least esthetic number fitting there """
function filldecreasing!(vec, pos)
if pos > 1
n = vec[pos]
for i in pos-1:-1:1
n = (n == 0) ? 1 : n - 1
vec[i] = n
end
end
return vec
end
""" Get the next esthetic number's digits from the previous number's digits """
function increment!(vec, bas, startpos = 1)
len = length(vec)
if len == 1
if vec[1] < bas - 1
vec[1] += 1
else
vec[1] = 0
push!(vec, 1)
end
else
pos = findfirst(i -> vec[i] < vec[i + 1], startpos:len-1)
if pos == nothing
if vec[end] >= bas - 1
push!(vec, 1)
filldecreasing!(vec, len + 1)
else
vec[end] += 1
filldecreasing!(vec, len)
end
else
for i in pos:len
if i == len
if vec[i] < bas - 1
vec[i] += 1
filldecreasing!(vec, i)
else
push!(vec, 1)
filldecreasing!(vec, len + 1)
end
elseif vec[i] < vec[i + 1] && vec[i] < bas - 2
vec[i] += 2
filldecreasing!(vec, i)
break
end
end
end
end
return vec
end
for b in 2:16
println("For base $b, the esthetic numbers indexed from $(4b) to $(6b) are:")
printed = 0
for (i, n) in enumerate(Iterators.take(Esthetic{Int}(1, b), 6b))
if i >= 4b
printed += 1
print(string(n, base=b), printed % 21 == 20 ? "\n" : " ")
end
end
println("\n")
end
for (bottom, top, cols, T) in [[1000, 9999, 16, Int], [100_000_000, 130_000_000, 8, Int],
[101_010_000_000, 130_000_000_000, 6, Int], [101_010_101_010_000_000, 130_000_000_000_000_000, 4, Int],
[101_010_101_010_101_000_000, 130_000_000_000_000_000_000, 4, Int128]]
esth, count = Esthetic{T}(bottom, 10, top), 0
println("\nBase 10 esthetic numbers between $(format(bottom, commas=true)) and $(format(top, commas=true)):")
for n in esth
count += 1
if count == 64
println(" ...")
elseif count < 64
print(format(n, commas=true), count % cols == 0 ? "\n" : " ")
end
end
println("\nTotal esthetic numbers in interval: $count")
end

View file

@ -0,0 +1,98 @@
import kotlin.math.abs
fun isEsthetic(n: Long, b: Long): Boolean {
if (n == 0L) {
return false
}
var i = n % b
var n2 = n / b
while (n2 > 0) {
val j = n2 % b
if (abs(i - j) != 1L) {
return false
}
n2 /= b
i = j
}
return true
}
fun listEsths(n: Long, n2: Long, m: Long, m2: Long, perLine: Int, all: Boolean) {
val esths = mutableListOf<Long>()
fun dfs(n: Long, m: Long, i: Long) {
if (i in n..m) {
esths.add(i)
}
if (i == 0L || i > m) {
return
}
val d = i % 10
val i1 = i * 10 + d - 1
val i2 = i1 + 2
when (d) {
0L -> {
dfs(n, m, i2)
}
9L -> {
dfs(n, m, i1)
}
else -> {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
}
for (i in 0L until 10L) {
dfs(n2, m2, i)
}
val le = esths.size
println("Base 10: $le esthetic numbers between $n and $m:")
if (all) {
for (c_esth in esths.withIndex()) {
print("${c_esth.value} ")
if ((c_esth.index + 1) % perLine == 0) {
println()
}
}
println()
} else {
for (i in 0 until perLine) {
print("${esths[i]} ")
}
println()
println("............")
for (i in le - perLine until le) {
print("${esths[i]} ")
}
println()
}
println()
}
fun main() {
for (b in 2..16) {
println("Base $b: ${4 * b}th to ${6 * b}th esthetic numbers:")
var n = 1L
var c = 0L
while (c < 6 * b) {
if (isEsthetic(n, b.toLong())) {
c++
if (c >= 4 * b) {
print("${n.toString(b)} ")
}
}
n++
}
println()
}
println()
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true);
listEsths(1e8.toLong(), 101_010_101, 13 * 1e7.toLong(), 123_456_789, 9, true);
listEsths(1e11.toLong(), 101_010_101_010, 13 * 1e10.toLong(), 123_456_789_898, 7, false);
listEsths(1e14.toLong(), 101_010_101_010_101, 13 * 1e13.toLong(), 123_456_789_898_989, 5, false);
listEsths(1e17.toLong(), 101_010_101_010_101_010, 13 * 1e16.toLong(), 123_456_789_898_989_898, 4, false);
}

View file

@ -0,0 +1,111 @@
function to(n, b)
local BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n == 0 then
return "0"
end
local ss = ""
while n > 0 do
local idx = (n % b) + 1
n = math.floor(n / b)
ss = ss .. BASE:sub(idx, idx)
end
return string.reverse(ss)
end
function isEsthetic(n, b)
function uabs(a, b)
if a < b then
return b - a
end
return a - b
end
if n == 0 then
return false
end
local i = n % b
n = math.floor(n / b)
while n > 0 do
local j = n % b
if uabs(i, j) ~= 1 then
return false
end
n = math.floor(n / b)
i = j
end
return true
end
function listEsths(n, n2, m, m2, perLine, all)
local esths = {}
function dfs(n, m, i)
if i >= n and i <= m then
table.insert(esths, i)
end
if i == 0 or i > m then
return
end
local d = i % 10
local i1 = 10 * i + d - 1
local i2 = i1 + 2
if d == 0 then
dfs(n, m, i2)
elseif d == 9 then
dfs(n, m, i1)
else
dfs(n, m, i1)
dfs(n, m, i2)
end
end
for i=0,9 do
dfs(n2, m2, i)
end
local le = #esths
print(string.format("Base 10: %s esthetic numbers between %s and %s:", le, math.floor(n), math.floor(m)))
if all then
for c,esth in pairs(esths) do
io.write(esth.." ")
if c % perLine == 0 then
print()
end
end
print()
else
for i=1,perLine do
io.write(esths[i] .. " ")
end
print("\n............")
for i = le - perLine + 1, le do
io.write(esths[i] .. " ")
end
print()
end
print()
end
for b=2,16 do
print(string.format("Base %d: %dth to %dth esthetic numbers:", b, 4 * b, 6 * b))
local n = 1
local c = 0
while c < 6 * b do
if isEsthetic(n, b) then
c = c + 1
if c >= 4 * b then
io.write(to(n, b).." ")
end
end
n = n + 1
end
print()
end
print()
-- the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true)
listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false)
listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false)
listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false)

View file

@ -0,0 +1,21 @@
ClearAll[EstheticNumbersRangeHelper, EstheticNumbersRange]
EstheticNumbersRangeHelper[power_, mima : {mi_, max_}, b_ : 10] := Module[{steps, cands},
steps = Tuples[{-1, 1}, power - 1];
steps = Accumulate[Prepend[#, 0]] & /@ steps;
cands = Table[Select[# + ConstantArray[s, power] & /@ steps, AllTrue[Between[{0, b - 1}]]], {s, 1, b - 1}];
cands //= Catenate;
cands //= Map[FromDigits[#, b] &];
cands = Select[cands, Between[mima]];
BaseForm[#, b] & /@ cands
]
EstheticNumbersRange[{min_, max_}, b_ : 10] := Module[{mi, ma},
{mi, ma} = Log[b, {min, max}];
mi //= Ceiling;
ma //= Ceiling;
ma = Max[ma, 1];
mi = Max[mi, 1];
Catenate[EstheticNumbersRangeHelper[#, {min, max}, b] & /@ Range[mi, ma]]
]
Table[{b, EstheticNumbersRange[{1, If[b == 2, 100000, If[b == 3, 100000, b^4]]}, b][[4 b ;; 6 b]]}, {b, 2, 16}] // Grid
EstheticNumbersRange[{1000, 9999}]
EstheticNumbersRange[{10^8, 1.3 10^8}]

View file

@ -0,0 +1,82 @@
import strformat
func isEsthetic(n, b: int64): bool =
if n == 0: return false
var i = n mod b
var n = n div b
while n > 0:
let j = n mod b
if abs(i - j) != 1:
return false
n = n div b
i = j
result = true
proc listEsths(n1, n2, m1, m2: int64; perLine: int; all: bool) =
var esths: seq[int64]
func dfs(n, m, i: int64) =
if i in n..m: esths.add i
if i == 0 or i > m: return
let d = i mod 10
let i1 = i * 10 + d - 1
let i2 = i1 + 2
case d
of 0:
dfs(n, m, i2)
of 9:
dfs(n, m, i1)
else:
dfs(n, m, i1)
dfs(n, m, i2)
for i in 0..9:
dfs(n2, m2, i)
echo &"Base 10: {esths.len} esthetic numbers between {n1} and {m1}:"
if all:
for i, esth in esths:
stdout.write esth
stdout.write if (i + 1) mod perLine == 0: '\n' else: ' '
echo()
else:
for i in 0..<perLine:
stdout.write esths[i], ' '
echo "\n............"
for i in esths.len - perLine .. esths.high:
stdout.write esths[i], ' '
echo()
echo()
proc toBase(n, b: int64): string =
const Digits = ['0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
if n == 0: return "0"
var n = n
while n > 0:
result.add Digits[n mod b]
n = n div b
for i in 0..<(result.len div 2):
swap result[i], result[result.high - i]
for b in 2..16:
echo &"Base {b}: {4 * b}th to {6 * b}th esthetic numbers:"
var n = 1i64
var c = 0i64
while c < 6 * b:
if n.isEsthetic(b):
inc c
if c >= 4 * b: stdout.write n.toBase(b), ' '
inc n
echo '\n'
# The following all use the obvious range limitations for the numbers in question.
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(100_000_000, 101_010_101, 130_000_000, 123_456_789, 9, true)
listEsths(100_000_000_000, 101_010_101_010, 130_000_000_000, 123_456_789_898, 7, false)
listEsths(100_000_000_000_000, 101_010_101_010_101, 130_000_000_000, 123_456_789_898_989, 5, false)
listEsths(100_000_000_000_000_000, 101_010_101_010_101_010, 130_000_000_000_000_000, 123_456_789_898_989_898, 4, false)

View file

@ -0,0 +1,200 @@
program Esthetic;
{$IFDEF FPC}
{$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$codealign proc=16}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils,//IntToStr
strutils;//Numb2USA aka commatize
const
ConvBase :array[0..15] of char= '0123456789ABCDEF';
maxBase = 16;
type
tErg = string[63];
tCnt = array[0..maxBase-1] of UInt64;
tDgtcnt = array[0..64] of tCnt;
//global
var
Dgtcnt :tDgtcnt;
procedure CalcDgtCnt(base:NativeInt;var Dgtcnt :tDgtcnt);
var
pCnt0,
pCnt1 : ^tCnt;
i,j,SumCarry: NativeUInt;
begin
fillchar(Dgtcnt,SizeOf(Dgtcnt),#0);
pCnt0 := @Dgtcnt[0];
//building count for every first digit of digitcount:
//example :count numbers starting "1" of lenght 13
For i := 0 to Base-1 do
pCnt0^[i] := 1;
For j := 1 to High(Dgtcnt) do
Begin
pCnt1 := @Dgtcnt[j];
//0 -> followed only by solutions of 1
pCnt1^[0] := pCnt0^[1];
//base-1 -> followed only by solutions of Base-2
pCnt1^[base-1] := pCnt0^[base-2];
//followed by solutions for i-1 and i+1
For i := 1 to base-2 do
pCnt1^[i]:= pCnt0^[i-1]+pCnt0^[i+1];
//next row aka digitcnt
pCnt0:= pCnt1;
end;
//converting to sum up each digit
//example :count numbers starting "1" of lenght 13
//-> count of all est. numbers from 1 to "1" with max lenght 13
//delete leading "0"
For j := 0 to High(Dgtcnt) do //High(Dgtcnt)
Dgtcnt[j,0] := 0;
SumCarry := Uint64(0);
For j := 0 to High(Dgtcnt) do
Begin
pCnt0 := @Dgtcnt[j];
For i := 0 to base-1 do
begin
SumCarry +=pCnt0^[i];
pCnt0^[i] :=SumCarry;
end;
end;
end;
function ConvToBaseStr(n,base:NativeUint):tErg;
var
idx,dgt,rst : Uint64;
Begin
IF n = 0 then
Begin
result := ConvBase[0];
EXIT;
end;
idx := High(result);
repeat
rst := n div base;
dgt := n-rst*base;
result[idx] := ConvBase[dgt];
dec(idx);
n := rst;
until n=0;
rst := High(result)-idx;
move(result[idx+1],result[1],rst);
setlength(result,rst);
end;
function isEsthetic(n,base:Uint64):boolean;
var
lastdgt,
dgt,
rst : Uint64;
Begin
result := true;
IF n >= Base then
Begin
rst := n div base;
Lastdgt := n-rst*base;
n := rst;
repeat
rst := n div base;
dgt := n-rst*base;
IF sqr(lastDgt-dgt)<> 1 then
Begin
result := false;
EXIT;
end;
lastDgt := dgt;
n := rst;
until n = 0;
end;
end;
procedure Task1;
var
i,base,cnt : NativeInt;
Begin
cnt := 0;
For base := 2 to 16 do
Begin
CalcDgtCnt(base,Dgtcnt);
writeln(4*base,'th through ',6*base,'th esthetic numbers in base ',base);
cnt := 0;
i := 0;
repeat
inc(i);
if isEsthetic(i,base) then
inc(cnt);
until cnt >= 4*base;
repeat
if isEsthetic(i,base) then
Begin
write(ConvToBaseStr(i,base),' ');
inc(cnt);
end;
inc(i);
until cnt > 6*base;
writeln;
end;
writeln;
end;
procedure Task2;
var
i : NativeInt;
begin
write(' There are ',Dgtcnt[4][0]-Dgtcnt[3][0],' esthetic numbers');
writeln(' between 1000 and 9999 ');
For i := 1000 to 9999 do
Begin
if isEsthetic(i,10) then
write(i:5);
end;
writeln;writeln;
end;
procedure Task3(Pot10: NativeInt);
//calculating esthetic numbers starting with "1" and Pot10+1 digits
var
i : NativeInt;
begin
write(' There are ',Numb2USA(IntToStr(Dgtcnt[Pot10][1]-Dgtcnt[Pot10][0])):26,' esthetic numbers');
writeln(' between 1e',Pot10,' and 1.3e',Pot10);
if Pot10 = 8 then
Begin
For i := 100*1000*1000 to 110*1000*1000-1 do
Begin
if isEsthetic(i,10) then
write(i:10);
end;
writeln;
//Jump over "11"
For i := 120*1000*1000 to 130*1000*1000-1 do
Begin
if isEsthetic(i,10) then
write(i:10);
end;
writeln;writeln;
end;
end;
var
i:NativeInt;
BEGIN
Task1;
//now only base 10 is used
CalcDgtCnt(10,Dgtcnt);
Task2;
For i := 2 to 20 do
Task3(3*i+2);
writeln;
write(' There are ',Numb2USA(IntToStr(Dgtcnt[64][0])),' esthetic numbers');
writeln(' with max 65 digits ');
writeln;
writeln(' The count of numbers with 64 digits like https://oeis.org/A090994');
writeln(Numb2USA(IntToStr(Dgtcnt[64][0]-Dgtcnt[63][0])):28);
end.

View file

@ -0,0 +1,50 @@
use 5.020;
use warnings;
use experimental qw(signatures);
use ntheory qw(fromdigits todigitstring);
sub generate_esthetic ($root, $upto, $callback, $base = 10) {
my $v = fromdigits($root, $base);
return if ($v > $upto);
$callback->($v);
my $t = $root->[-1];
__SUB__->([@$root, $t + 1], $upto, $callback, $base) if ($t + 1 < $base);
__SUB__->([@$root, $t - 1], $upto, $callback, $base) if ($t - 1 >= 0);
}
sub between_esthetic ($from, $upto, $base = 10) {
my @list;
foreach my $k (1 .. $base - 1) {
generate_esthetic([$k], $upto,
sub($n) { push(@list, $n) if ($n >= $from) }, $base);
}
sort { $a <=> $b } @list;
}
sub first_n_esthetic ($n, $base = 10) {
for (my $m = $n * $n ; 1 ; $m *= $base) {
my @list = between_esthetic(1, $m, $base);
return @list[0 .. $n - 1] if @list >= $n;
}
}
foreach my $base (2 .. 16) {
say "\n$base-esthetic numbers at indices ${\(4*$base)}..${\(6*$base)}:";
my @list = first_n_esthetic(6 * $base, $base);
say join(' ', map { todigitstring($_, $base) } @list[4*$base-1 .. $#list]);
}
say "\nBase 10 esthetic numbers between 1,000 and 9,999:";
for (my @list = between_esthetic(1e3, 1e4) ; @list ;) {
say join(' ', splice(@list, 0, 20));
}
say "\nBase 10 esthetic numbers between 100,000,000 and 130,000,000:";
for (my @list = between_esthetic(1e8, 1.3e8) ; @list ;) {
say join(' ', splice(@list, 0, 9));
}

View file

@ -0,0 +1,71 @@
(phixonline)-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">aleph</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"0123456789ABCDEF"</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">efill</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- min-fill, like 10101 or 54321 or 32101</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ch</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">?</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'9'</span><span style="color: #0000FF;">:</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">):</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ch</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">esthetic</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- generate the next esthetic number after s
-- (nb unpredictable results if s is not esthetic, or "")</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">cp</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span><span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]:</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #000000;">cp</span> <span style="color: #008080;">and</span> <span style="color: #000000;">cp</span><span style="color: #0000FF;"><</span><span style="color: #000000;">aleph</span><span style="color: #0000FF;">[</span><span style="color: #000000;">base</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">efill</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">aleph</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">aleph</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">],</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><</span><span style="color: #000000;">aleph</span><span style="color: #0000FF;">[</span><span style="color: #000000;">base</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">efill</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'9'</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">:</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">efill</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1"</span><span style="color: #0000FF;">&</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">16</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">hi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">*</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">lo</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">*</span><span style="color: #000000;">4</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,{}}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">hi</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">esthetic</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">lo</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"numbers"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</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;">"Base %d esthetic numbers[%d..%d]: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lo</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">efill</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1000"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),{}}</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">esthetic</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"numbers"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</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;">"\nBase 10 esthetic numbers between 1,000 and 9,999: %s\n\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">comma</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">3</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">","</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">7</span> <span style="color: #008080;">to</span> <span style="color: #000000;">19</span> <span style="color: #008080;">by</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"10"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"13"</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">efill</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'1'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),{}}</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">s</span><span style="color: #0000FF;"><</span><span style="color: #000000;">t</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">esthetic</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"numbers"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</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;">"Base 10 esthetic numbers between %s and %s: %s\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">comma</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">),</span><span style="color: #000000;">comma</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">),</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--

View file

@ -0,0 +1,21 @@
(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">count_esthetic</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- a start digit of 0 means sum all 1..9</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">dc</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">),</span><span style="color: #000000;">len</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- nb 0..9 logically</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">len</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">9</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">dc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">0</span><span style="color: #0000FF;">:</span><span style="color: #000000;">dc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">d</span><span style="color: #0000FF;">])</span> <span style="color: #0000FF;">+</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">9</span><span style="color: #0000FF;">?</span><span style="color: #000000;">0</span><span style="color: #0000FF;">:</span><span style="color: #000000;">dc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">][</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
<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: #008080;">if</span> <span style="color: #000000;">start</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">len</span><span style="color: #0000FF;">][</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">9</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (see note)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">dc</span><span style="color: #0000FF;">[</span><span style="color: #000000;">len</span><span style="color: #0000FF;">][</span><span style="color: #000000;">start</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">machine_bits</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">64</span><span style="color: #0000FF;">?</span><span style="color: #000000;">63</span><span style="color: #0000FF;">:</span><span style="color: #000000;">57</span><span style="color: #0000FF;">),</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count_esthetic</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}),</span><span style="color: #000000;">t</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</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;">"There are %,26d %2d-digit esthetic numbers beginning with 1\n"</span><span style="color: #0000FF;">},</span><span style="color: #000000;">r</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">machine_bits</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">64</span> <span style="color: #008080;">then</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;">"There are %,26d 64-digit esthetic numbers\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count_esthetic</span><span style="color: #0000FF;">(</span><span style="color: #000000;">64</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;">"There are %,26d esthetic numbers with max 65 digits\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">64</span><span style="color: #0000FF;">),</span><span style="color: #000000;">count_esthetic</span><span style="color: #0000FF;">))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--

View file

@ -0,0 +1,47 @@
(de esthetic (N Base)
(let Lst
(make
(loop
(yoke (% N Base))
(T (=0 (setq N (/ N Base)))) ) )
(and
(fully
=1
(make
(for (L Lst (cdr L) (cdr L))
(link (abs (- (car L) (cadr L)))) ) ) )
(pack
(mapcar
'((C)
(and (> C 9) (inc 'C 39))
(char (+ C 48)) )
Lst ) ) ) ) )
(de genCount (Num Base)
(let (C 0 N 0)
(tail
(inc (* 2 Base))
(make
(while (>= Num C)
(when (esthetic N Base) (link @) (inc 'C))
(inc 'N) ) ) ) ) )
(de genRange (A B Base)
(make
(while (>= B A)
(when (esthetic A Base) (link @))
(inc 'A) ) ) )
(for (N 2 (>= 16 N) (inc N))
(prin "Base " N ": ")
(mapc '((L) (prin L " ")) (genCount (* 6 N) N))
(prinl) )
(prinl)
(prinl "Base 10: 61 esthetic numbers between 1000 and 9999:")
(let L (genRange 1000 9999 10)
(while (cut 16 'L)
(mapc '((L) (prin L " ")) @)
(prinl) ) )
(prinl)
(prinl "Base 10: 126 esthetic numbers between 100000000 and 130000000:")
(let L (genRange 100000000 130000000 10)
(while (cut 9 'L)
(mapc '((L) (prin L " ")) @)
(prinl) ) )

View file

@ -0,0 +1,54 @@
main:-
forall(between(2, 16, Base),
(Min_index is Base * 4, Max_index is Base * 6,
print_esthetic_numbers1(Base, Min_index, Max_index))),
print_esthetic_numbers2(1000, 9999, 16),
nl,
print_esthetic_numbers2(100000000, 130000000, 8).
print_esthetic_numbers1(Base, Min_index, Max_index):-
swritef(Format, '~%tr ', [Base]),
writef('Esthetic numbers in base %t from index %t through index %t:\n',
[Base, Min_index, Max_index]),
print_esthetic_numbers1(Base, Format, Min_index, Max_index, 0, 1).
print_esthetic_numbers1(Base, Format, Min_index, Max_index, M, I):-
I =< Max_index,
!,
next_esthetic_number(Base, M, N),
(I >= Min_index -> format(Format, [N]) ; true),
J is I + 1,
print_esthetic_numbers1(Base, Format, Min_index, Max_index, N, J).
print_esthetic_numbers1(_, _, _, _, _, _):-
write('\n\n').
print_esthetic_numbers2(Min, Max, Per_line):-
writef('Esthetic numbers in base 10 between %t and %t:\n', [Min, Max]),
M is Min - 1,
print_esthetic_numbers2(Max, Per_line, M, 0).
print_esthetic_numbers2(Max, Per_line, M, Count):-
next_esthetic_number(10, M, N),
N =< Max,
!,
write(N),
Count1 is Count + 1,
(0 is Count1 mod Per_line -> nl ; write(' ')),
print_esthetic_numbers2(Max, Per_line, N, Count1).
print_esthetic_numbers2(_, _, _, Count):-
writef('\nCount: %t\n', [Count]).
next_esthetic_number(Base, M, N):-
N is M + 1,
N < Base,
!.
next_esthetic_number(Base, M, N):-
A is M // Base,
B is A mod Base,
(B is M mod Base + 1, B + 1 < Base ->
N is M + 2
;
next_esthetic_number(Base, A, C),
D is C mod Base,
(D == 0 -> E = 1 ; E is D - 1),
N is C * Base + E).

View file

@ -0,0 +1,86 @@
from collections import deque
from itertools import dropwhile, islice, takewhile
from textwrap import wrap
from typing import Iterable, Iterator
Digits = str # Alias for the return type of to_digits()
def esthetic_nums(base: int) -> Iterator[int]:
"""Generate the esthetic number sequence for a given base
>>> list(islice(esthetic_nums(base=10), 20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65]
"""
queue: deque[tuple[int, int]] = deque()
queue.extendleft((d, d) for d in range(1, base))
while True:
num, lsd = queue.pop()
yield num
new_lsds = (d for d in (lsd - 1, lsd + 1) if 0 <= d < base)
num *= base # Shift num left one digit
queue.extendleft((num + d, d) for d in new_lsds)
def to_digits(num: int, base: int) -> Digits:
"""Return a representation of an integer as digits in a given base
>>> to_digits(0x3def84f0ce, base=16)
'3def84f0ce'
"""
digits: list[str] = []
while num:
num, d = divmod(num, base)
digits.append("0123456789abcdef"[d])
return "".join(reversed(digits)) if digits else "0"
def pprint_it(it: Iterable[str], indent: int = 4, width: int = 80) -> None:
"""Pretty print an iterable which returns strings
>>> pprint_it(map(str, range(20)), indent=0, width=40)
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19
<BLANKLINE>
"""
joined = ", ".join(it)
lines = wrap(joined, width=width - indent)
for line in lines:
print(f"{indent*' '}{line}")
print()
def task_2() -> None:
nums: Iterator[int]
for base in range(2, 16 + 1):
start, stop = 4 * base, 6 * base
nums = esthetic_nums(base)
nums = islice(nums, start - 1, stop) # start and stop are 1-based indices
print(
f"Base-{base} esthetic numbers from "
f"index {start} through index {stop} inclusive:\n"
)
pprint_it(to_digits(num, base) for num in nums)
def task_3(lower: int, upper: int, base: int = 10) -> None:
nums: Iterator[int] = esthetic_nums(base)
nums = dropwhile(lambda num: num < lower, nums)
nums = takewhile(lambda num: num <= upper, nums)
print(
f"Base-{base} esthetic numbers with "
f"magnitude between {lower:,} and {upper:,}:\n"
)
pprint_it(to_digits(num, base) for num in nums)
if __name__ == "__main__":
print("======\nTask 2\n======\n")
task_2()
print("======\nTask 3\n======\n")
task_3(1_000, 9_999)
print("======\nTask 4\n======\n")
task_3(100_000_000, 130_000_000)

View file

@ -0,0 +1,256 @@
'''Esthetic numbers'''
from functools import reduce
from itertools import (
accumulate, chain, count, dropwhile,
islice, product, takewhile
)
from operator import add
from string import digits, ascii_lowercase
from textwrap import wrap
# estheticNumbersInBase :: Int -> [Int]
def estheticNumbersInBase(b):
'''Infinite stream of numbers which are
esthetic in a given base.
'''
return concatMap(
compose(
lambda deltas: concatMap(
lambda headDigit: concatMap(
compose(
fromBaseDigits(b),
scanl(add)(headDigit)
)
)(deltas)
)(range(1, b)),
replicateList([-1, 1])
)
)(count(0))
# ------------------------ TESTS -------------------------
def main():
'''Specified tests'''
def samples(b):
i, j = b * 4, b * 6
return '\n'.join([
f'Esthetics [{i}..{j}] for base {b}:',
unlines(wrap(
unwords([
showInBase(b)(n) for n in compose(
drop(i - 1), take(j)
)(
estheticNumbersInBase(b)
)
]), 60
))
])
def takeInRange(a, b):
return compose(
dropWhile(lambda x: x < a),
takeWhile(lambda x: x <= b)
)
print(
'\n\n'.join([
samples(b) for b in range(2, 1 + 16)
])
)
for (lo, hi) in [(1000, 9999), (100_000_000, 130_000_000)]:
print(f'\nBase 10 Esthetics in range [{lo}..{hi}]:')
print(
unlines(wrap(
unwords(
str(x) for x in takeInRange(lo, hi)(
estheticNumbersInBase(10)
)
), 60
))
)
# ------------------- BASES AND DIGITS -------------------
# fromBaseDigits :: Int -> [Int] -> [Int]
def fromBaseDigits(b):
'''An empty list if any digits are out of range for
the base. Otherwise a list containing an integer.
'''
def go(digitList):
maybeNum = reduce(
lambda r, d: None if r is None or (
0 > d or d >= b
) else r * b + d,
digitList, 0
)
return [] if None is maybeNum else [maybeNum]
return go
# toBaseDigits :: Int -> Int -> [Int]
def toBaseDigits(b):
'''A list of the digits of n in base b.
'''
def f(x):
return None if 0 == x else (
divmod(x, b)[::-1]
)
return lambda n: list(reversed(unfoldr(f)(n)))
# showInBase :: Int -> Int -> String
def showInBase(b):
'''String representation of n in base b.
'''
charSet = digits + ascii_lowercase
return lambda n: ''.join([
charSet[i] for i in toBaseDigits(b)(n)
])
# ----------------------- GENERIC ------------------------
# compose :: ((a -> a), ...) -> (a -> a)
def compose(*fs):
'''Composition, from right to left,
of a series of functions.
'''
def go(f, g):
def fg(x):
return f(g(x))
return fg
return reduce(go, fs, lambda x: x)
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list over which a function has been
mapped.
The list monad can be derived by using a function f
which wraps its output in a list, (using an empty
list to represent computational failure).
'''
def go(xs):
return chain.from_iterable(map(f, xs))
return go
# drop :: Int -> [a] -> [a]
# drop :: Int -> String -> String
def drop(n):
'''The sublist of xs beginning at
(zero-based) index n.
'''
def go(xs):
if isinstance(xs, (list, tuple, str)):
return xs[n:]
else:
take(n)(xs)
return xs
return go
# dropWhile :: (a -> Bool) -> [a] -> [a]
# dropWhile :: (Char -> Bool) -> String -> String
def dropWhile(p):
'''The suffix remainining after takeWhile p xs.
'''
return lambda xs: list(
dropwhile(p, xs)
)
# replicateList :: [a] -> Int -> [[a]]
def replicateList(xs):
'''All distinct lists of length n that
consist of elements drawn from xs.
'''
def rep(n):
def go(x):
return [[]] if 1 > x else [
([a] + b) for (a, b) in product(
xs, go(x - 1)
)
]
return go(n)
return rep
# scanl :: (b -> a -> b) -> b -> [a] -> [b]
def scanl(f):
'''scanl is like reduce, but defines a succession of
intermediate values, building from the left.
'''
def go(a):
def g(xs):
return accumulate(chain([a], xs), f)
return g
return go
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
def go(xs):
return list(islice(xs, n))
return go
# takeWhile :: (a -> Bool) -> [a] -> [a]
# takeWhile :: (Char -> Bool) -> String -> String
def takeWhile(p):
'''The longest (possibly empty) prefix of xs
in which all elements satisfy p.
'''
return lambda xs: list(
takewhile(p, xs)
)
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
'''Dual to reduce or foldr.
Where catamorphism reduces a list to a summary value,
the anamorphic unfoldr builds a list from a seed value.
As long as f returns (a, b) a is prepended to the list,
and the residual b is used as the argument for the next
application of f.
When f returns None, the completed list is returned.
'''
def go(v):
xr = v, v
xs = []
while True:
xr = f(xr[1])
if None is not xr:
xs.append(xr[0])
else:
return xs
return go
# unlines :: [String] -> String
def unlines(xs):
'''A single string formed by the intercalation
of a list of strings with the newline character.
'''
return '\n'.join(xs)
# unwords :: [String] -> String
def unwords(xs):
'''A space-separated string derived
from a list of words.
'''
return ' '.join(xs)
# MAIN ---
if __name__ == '__main__':
main()

View file

@ -0,0 +1,45 @@
[ [] swap
[ base share /mod
rot join swap
dup 0 = until ]
drop ] is digits ( n --> [ )
[ dup 0 = iff
[ drop false ]
done
digits
true swap
behead swap
witheach
[ tuck - abs 1 != if
[ dip not conclude ] ]
drop ] is esthetic ( n --> b )
15 times
[ i^ 2 +
say "Base " dup echo cr
base put
[] 0
[ 1+
dup esthetic if
[ tuck join swap ]
over size
base share 6 * = until ]
drop
base share 4 * 1 - split nip
echo cr cr
base release ]
say "Decimal between 1000 and 9999: "
cr
0 temp put
9000 times
[ i^ 1000 + dup
esthetic iff
[ echo
1 temp tally
temp share
10 mod iff
sp else cr ]
else drop ]
temp release

View file

@ -0,0 +1,61 @@
/*REXX pgm lists a bunch of esthetic numbers in bases 2 ──► 16, & base 10 in two ranges.*/
parse arg baseL baseH range /*obtain optional arguments from the CL*/
if baseL=='' | baseL=="," then baseL= 2 /*Not specified? Then use the default.*/
if baseH=='' | baseH=="," then baseH=16 /* " " " " " " */
if range=='' | range=="," then range=1000..9999 /* " " " " " " */
do radix=baseL to baseH; #= 0; if radix<2 then iterate /*process the bases. */
start= radix * 4; stop = radix * 6
$=; do i=1 until #==stop; y= base(i, radix) /*convert I to base Y*/
if \esthetic(y, radix) then iterate /*not esthetic? Skip*/
#= # + 1; if #<start then iterate /*is # below range?*/
$= $ y /*append # to $ list.*/
end /*i*/
say
say center(' base ' radix", the" th(start) '' th(stop) ,
"esthetic numbers ", max(80, length($) - 1), '')
say strip($)
end /*radix*/
say; g= 25
parse var range start '..' stop
say center(' base 10 esthetic numbers between' start "and" stop '(inclusive) ', g*5-1,"")
#= 0; $=
do k=start to stop; if \esthetic(k, 10) then iterate; #= # + 1; $= $ k
if #//g==0 then do; say strip($); $=; end
end /*k*/
say strip($); say; say # ' esthetic numbers listed.'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
PorA: _= pos(z, @u); p= substr(@u, _-1, 1); a= substr(@u, _+1, 1); return
th: parse arg th; return th || word('th st nd rd', 1+(th//10)*(th//100%10\==1)*(th//10<4))
vv: parse arg v,_; vr= x2d(v) + _; if vr==-1 then vr= r; return d2x(vr)
/*──────────────────────────────────────────────────────────────────────────────────────*/
base: procedure expose @u; arg x 1 #,toB,inB,,y /*Y is assigned a "null" value. */
if tob=='' then tob= 10 /*maybe assign a default for TObase. */
if inb=='' then inb= 10 /* " " " " " INbase. */
@l= '0123456789abcdef'; @u= @l; upper @u /*two versions of hexadecimal digits. */
if inB\==10 then do; #= 0 /*only convert if not base 10. */
do j=1 for length(x) /*convert X: base inB ──► base 10. */
#= # * inB + pos(substr(x, j, 1), @u) -1 /*build new number.*/
end /*j*/ /* [↑] this also verifies digits. */
end
if toB==10 then return # /*if TOB is ten, then simply return #.*/
do while # >= toB /*convert #: base 10 ──► base toB.*/
y= substr(@l, (# // toB) + 1, 1)y /*construct the output number. */
#= # % toB /* ··· and whittle # down also. */
end /*while*/ /* [↑] algorithm may leave a residual.*/
return substr(@l, # + 1, 1)y /*prepend the residual, if any. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
esthetic: procedure expose @u; arg x,r; L= length(x); if L==1 then return 1
if x<2 then return 0
do d=0 to r-1; _= d2x(d); if pos(_ || _, x)\==0 then return 0
end /*d*/ /* [↑] check for a duplicated digits. */
do j=1 for L; @.j= substr(x, j, 1) /*assign (base) digits to stemmed array*/
end /*j*/
if L==2 then do; z= @.1; call PorA; if @.2==p | @.2==a then nop
else return 0
end
do e=2 to L-1; z= @.e; pe= e - 1; ae= e + 1
if (z==vv(@.pe,-1)|z==vv(@.pe,1))&(z==vv(@.ae,-1)|z==vv(@.ae,1)) then iterate
return 0
end /*e*/; return 1

View file

@ -0,0 +1,27 @@
use Lingua::EN::Numbers;
sub esthetic($base = 10) {
my @s = ^$base .map: -> \s {
((s - 1).base($base) if s > 0), ((s + 1).base($base) if s < $base - 1)
}
flat [ (1 .. $base - 1)».base($base) ],
{ [ flat .map: { $_ xx * Z~ flat @s[.comb.tail.parse-base($base)] } ] } *
}
for 2 .. 16 -> $b {
put "\n{(4 × $b).&ordinal-digit} through {(6 × $b).&ordinal-digit} esthetic numbers in base $b";
put esthetic($b)[(4 × $b - 1) .. (6 × $b - 1)]».fmt('%3s').batch(16).join: "\n"
}
my @e10 = esthetic;
put "\nBase 10 esthetic numbers between 1,000 and 9,999:";
put @e10.&between(1000, 9999).batch(20).join: "\n";
put "\nBase 10 esthetic numbers between {1e8.Int.&comma} and {1.3e8.Int.&comma}:";
put @e10.&between(1e8.Int, 1.3e8.Int).batch(9).join: "\n";
sub between (@array, Int $lo, Int $hi) {
my $top = @array.first: * > $hi, :k;
@array[^$top].grep: * > $lo
}

View file

@ -0,0 +1,64 @@
basePlus = []
decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
for base = 2 to 16
see "Base " + base + ": " + (base*4) + "th to " + (base*6) + "th esthetic numbers:" + nl
res = 0
binList = []
for n = 1 to 10000
str = decimaltobase(n,base)
limit1 = base*4
limit2 = base*6
ln = len(str)
flag = 0
for m = 1 to ln-1
nr1 = str[m]
ind1 = find(baseList,nr1)
num1 = decList[ind1]
nr2 = str[m+1]
ind2 = find(baseList,nr2)
num2 = decList[ind2]
num = num1-num2
if num = 1 or num = -1
flag = flag + 1
ok
next
if flag = ln - 1
res = res + 1
if res > (limit1 - 1) and res < (limit2 + 1)
see " " + str
ok
if base = 10 and number(str) > 1000 and number(str) < 9999
add(basePlus,str)
ok
ok
next
see nl + nl
next
see "Base 10: " + len(basePlus) +" esthetic numbers between 1000 and 9999:"
for row = 1 to len(basePlus)
if (row-1) % 16 = 0
see nl
else
see " " + basePlus[row]
ok
next
func decimaltobase(nr,base)
binList = []
binary = 0
remainder = 1
while(nr != 0)
remainder = nr % base
ind = find(decList,remainder)
rem = baseList[ind]
add(binList,rem)
nr = floor(nr/base)
end
binlist = reverse(binList)
binList = list2str(binList)
binList = substr(binList,nl,"")
return binList

View file

@ -0,0 +1,93 @@
def isEsthetic(n, b)
if n == 0 then
return false
end
i = n % b
n2 = (n / b).floor
while n2 > 0
j = n2 % b
if (i - j).abs != 1 then
return false
end
n2 = n2 / b
i = j
end
return true
end
def listEsths(n, n2, m, m2, perLine, all)
esths = Array.new
dfs = lambda {|n, m, i|
if n <= i and i <= m then
esths << i
end
if i == 0 or i > m then
return
end
d = i % 10
i1 = i * 10 + d - 1
i2 = i1 + 2
if d == 0 then
dfs[n, m, i2]
elsif d == 9 then
dfs[n, m, i1]
else
dfs[n, m, i1]
dfs[n, m, i2]
end
}
for i in 0..9
dfs[n2, m2, i]
end
le = esths.length
print "Base 10: %d esthetic numbers between %d and %d:\n" % [le, n, m]
if all then
esths.each_with_index { |esth, idx|
print "%d " % [esth]
if (idx + 1) % perLine == 0 then
print "\n"
end
}
print "\n"
else
for i in 0 .. perLine - 1
print "%d " % [esths[i]]
end
print "\n............\n"
for i in le - perLine .. le - 1
print "%d " % [esths[i]]
end
print "\n"
end
print "\n"
end
def main
for b in 2..16
print "Base %d: %dth to %dth esthetic numbers:\n" % [b, 4 * b, 6 * b]
n = 1
c = 0
while c < 6 * b
if isEsthetic(n, b) then
c = c + 1
if c >= 4 * b then
print "%s " % [n.to_s(b)]
end
end
n = n + 1
end
print "\n"
end
print "\n"
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101010101, 13 * 1e7, 123456789, 9, true)
listEsths(1e11, 101010101010, 13 * 1e10, 123456789898, 7, false)
listEsths(1e14, 101010101010101, 13 * 1e13, 123456789898989, 5, false)
listEsths(1e17, 101010101010101010, 13 * 1e16, 123456789898989898, 4, false)
end
main()

View file

@ -0,0 +1,101 @@
// [dependencies]
// radix_fmt = "1.0"
// Returns the next esthetic number in the given base after n, where n is an
// esthetic number in that base or one less than a power of base.
fn next_esthetic_number(base: u64, n: u64) -> u64 {
if n + 1 < base {
return n + 1;
}
let mut a = n / base;
let mut b = a % base;
if n % base + 1 == b && b + 1 < base {
return n + 2;
}
a = next_esthetic_number(base, a);
b = a % base;
a * base + if b == 0 { 1 } else { b - 1 }
}
fn print_esthetic_numbers(min: u64, max: u64, numbers_per_line: usize) {
let mut numbers = Vec::new();
let mut n = next_esthetic_number(10, min - 1);
while n <= max {
numbers.push(n);
n = next_esthetic_number(10, n);
}
let count = numbers.len();
println!(
"Esthetic numbers in base 10 between {} and {} ({}):",
min, max, count
);
if count > 200 {
for i in 0..numbers_per_line {
if i != 0 {
print!(" ");
}
print!("{}", numbers[i]);
}
println!("\n............\n");
for i in 0..numbers_per_line {
if i != 0 {
print!(" ");
}
print!("{}", numbers[count - numbers_per_line + i]);
}
println!();
} else {
for i in 0..count {
print!("{}", numbers[i]);
if (i + 1) % numbers_per_line == 0 {
println!();
} else {
print!(" ");
}
}
if count % numbers_per_line != 0 {
println!();
}
}
}
fn main() {
for base in 2..=16 {
let min = base * 4;
let max = base * 6;
println!(
"Esthetic numbers in base {} from index {} through index {}:",
base, min, max
);
let mut n = 0;
for index in 1..=max {
n = next_esthetic_number(base, n);
if index >= min {
print!("{} ", radix_fmt::radix(n, base as u8));
}
}
println!("\n");
}
let mut min = 1000;
let mut max = 9999;
print_esthetic_numbers(min, max, 16);
println!();
min = 100000000;
max = 130000000;
print_esthetic_numbers(min, max, 8);
println!();
for i in 0..3 {
min *= 1000;
max *= 1000;
let numbers_per_line = match i {
0 => 7,
1 => 5,
_ => 4,
};
print_esthetic_numbers(min, max, numbers_per_line);
println!();
}
}

View file

@ -0,0 +1,38 @@
func generate_esthetic(root, upto, callback, b=10) {
var v = root.digits2num(b)
return nil if (v > upto)
callback(v)
var t = root.head
__FUNC__([t+1, root...], upto, callback, b) if (t+1 < b)
__FUNC__([t-1, root...], upto, callback, b) if (t-1 >= 0)
}
func between_esthetic(from, upto, b=10) {
gather {
for k in (1..^b) {
generate_esthetic([k], upto, { take(_) if (_ >= from) }, b)
}
}.sort
}
func first_n_esthetic(n, b=10) {
for (var m = n**2; true ; m *= b) {
var list = between_esthetic(1, m, b)
return list.first(n) if (list.len >= n)
}
}
for b in (2..16) {
say "\n#{b}-esthetic numbers with indices #{4*b}..#{6*b}: "
say first_n_esthetic(6*b, b).last(6*b - 4*b + 1).map{.base(b)}.join(' ')
}
say "\nBase 10 esthetic numbers between 1,000 and 9,999:"
between_esthetic(1e3, 1e4).slices(20).each { .join(' ').say }
say "\nBase 10 esthetic numbers between 100,000,000 and 130,000,000:"
between_esthetic(1e8, 13e7).slices(9).each { .join(' ').say }

View file

@ -0,0 +1,132 @@
extension Sequence {
func take(_ n: Int) -> [Element] {
var res = [Element]()
for el in self {
guard res.count != n else {
return res
}
res.append(el)
}
return res
}
}
extension String {
func isEsthetic(base: Int = 10) -> Bool {
zip(dropFirst(0), dropFirst())
.lazy
.allSatisfy({ abs(Int(String($0.0), radix: base)! - Int(String($0.1), radix: base)!) == 1 })
}
}
func getEsthetics(from: Int, to: Int, base: Int = 10) -> [String] {
guard base >= 2, to >= from else {
return []
}
var start = ""
var end = ""
repeat {
if start.count & 1 == 1 {
start += "0"
} else {
start += "1"
}
} while Int(start, radix: base)! < from
let digiMax = String(base - 1, radix: base)
let lessThanDigiMax = String(base - 2, radix: base)
var count = 0
repeat {
if count != base - 1 {
end += String(count + 1, radix: base)
count += 1
} else {
if String(end.last!) == digiMax {
end += lessThanDigiMax
} else {
end += digiMax
}
}
} while Int(end, radix: base)! < to
if Int(start, radix: base)! >= Int(end, radix: base)! {
return []
}
var esthetics = [Int]()
func shimmer(_ n: Int, _ m: Int, _ i: Int) {
if (n...m).contains(i) {
esthetics.append(i)
} else if i == 0 || i > m {
return
}
let d = i % base
let i1 = i &* base &+ d &- 1
let i2 = i1 &+ 2
if (i1 < i || i2 < i) {
// overflow
return
}
switch d {
case 0: shimmer(n, m, i2)
case base-1: shimmer(n, m, i1)
case _:
shimmer(n, m, i1)
shimmer(n, m, i2)
}
}
for digit in 0..<base {
shimmer(Int(start, radix: base)!, Int(end, radix: base)!, digit)
}
return esthetics.filter({ $0 <= to }).map({ String($0, radix: base) })
}
for base in 2...16 {
let esthetics = (0...)
.lazy
.map({ String($0, radix: base) })
.filter({ $0.isEsthetic(base: base) })
.dropFirst(base * 4)
.take((base * 6) - (base * 4) + 1)
print("Base \(base) esthetics from \(base * 4) to \(base * 6)")
print(esthetics)
print()
}
let base10Esthetics = (1000...9999).filter({ String($0).isEsthetic() })
print("\(base10Esthetics.count) esthetics between 1000 and 9999:")
print(base10Esthetics)
print()
func printSlice(of array: [String]) {
print(array.take(5))
print("...")
print(Array(array.lazy.reversed().take(5).reversed()))
print("\(array.count) total\n")
}
print("Esthetics between \(Int(1e8)) and \(13 * Int(1e7)):")
printSlice(of: getEsthetics(from: Int(1e8), to: 13 * Int(1e7)))
print("Esthetics between \(Int(1e11)) and \(13 * Int(1e10))")
printSlice(of: getEsthetics(from: Int(1e11), to: 13 * Int(1e10)))
print("Esthetics between \(Int(1e14)) and \(13 * Int(1e13)):")
printSlice(of: getEsthetics(from: Int(1e14), to: 13 * Int(1e13)))
print("Esthetics between \(Int(1e17)) and \(13 * Int(1e16)):")
printSlice(of: getEsthetics(from: Int(1e17), to: 13 * Int(1e16)))

View file

@ -0,0 +1,73 @@
import "./fmt" for Conv, Fmt
var isEsthetic = Fn.new { |n, b|
if (n == 0) return false
var i = n % b
n = (n/b).floor
while (n > 0) {
var j = n % b
if ((i - j).abs != 1) return false
n = (n/b).floor
i = j
}
return true
}
var esths = []
var dfs // recursive function
dfs = Fn.new { |n, m, i|
if (i >= n && i <= m) esths.add(i)
if (i == 0 || i > m) return
var d = i % 10
var i1 = i*10 + d - 1
var i2 = i1 + 2
if (d == 0) {
dfs.call(n, m, i2)
} else if (d == 9) {
dfs.call(n, m, i1)
} else {
dfs.call(n, m, i1)
dfs.call(n, m, i2)
}
}
var listEsths = Fn.new { |n, n2, m, m2, perLine, all|
esths.clear()
for (i in 0..9) dfs.call(n2, m2, i)
var le = esths.count
Fmt.print("Base 10: $,d esthetic numbers between $,d and $,d", le, n, m)
if (all) {
var c = 0
for (esth in esths) {
System.write("%(esth) ")
if ((c+1)%perLine == 0) System.print()
c = c + 1
}
} else {
for (i in 0...perLine) System.write("%(Conv.dec(esths[i])) ")
System.print("\n............\n")
for (i in le-perLine...le) System.write("%(Conv.dec(esths[i])) ")
}
System.print("\n")
}
for (b in 2..16) {
System.print("Base %(b): %(4*b)th to %(6*b)th esthetic numbers:")
var n = 1
var c = 0
while (c < 6*b) {
if (isEsthetic.call(n, b)) {
c = c + 1
if (c >= 4*b) System.write("%(Conv.itoa(n, b)) ")
}
n = n + 1
}
System.print("\n")
}
// the following all use the obvious range limitations for the numbers in question
listEsths.call(1000, 1010, 9999, 9898, 16, true)
listEsths.call(1e8, 101010101, 13*1e7, 123456789, 9, true)
listEsths.call(1e11, 101010101010, 13*1e10, 123456789898, 7, false)
listEsths.call(1e14, 101010101010101, 13*1e13, 123456789898989, 5, false)

View file

@ -0,0 +1,60 @@
proc NumOut(N); \Display N in the current Base
int N, R;
[N:= N/Base;
R:= rem(0);
if N # 0 then NumOut(N);
if Base <= 10 then
ChOut(0, R+^0)
else
ChOut(0, if R < 10 then R+^0 else R-10+^A);
];
func Esthetic(N); \Return 'true' if adjacent digits differ by 1
int N, D, D0;
[N:= N/Base;
D0:= rem(0);
while N # 0 do
[N:= N/Base;
D:= rem(0);
if D = D0 then return false;
if abs(D-D0) > 1 then return false;
D0:= D;
];
return true;
];
int Count, N;
[for Base:= 2 to 16 do
[Text(0, "Base "); IntOut(0, Base); Text(0, ": ");
Count:= 0; N:= 1;
loop [if Esthetic(N) then
[Count:= Count+1;
if Count >= Base*4 then
[NumOut(N); ChOut(0, ^ )];
if Count >= Base*6 then quit;
];
N:= N+1;
];
CrLf(0);
];
Base:= 10;
Text(0, "Base 10 numbers between 1000 and 9999:^m^j");
Count:= 0;
for N:= 1000 to 9999 do
[if Esthetic(N) then
[Count:= Count+1;
NumOut(N); ChOut(0, ^ );
if rem(Count/16) = 0 then CrLf(0);
];
];
CrLf(0);
Text(0, "Base 10 numbers between 1.0e8 and 1.3e8:^m^j");
Count:= 0;
for N:= 100_000_000 to 130_000_000 do
[if Esthetic(N) then
[Count:= Count+1;
NumOut(N); ChOut(0, ^ );
if rem(Count/9) = 0 then CrLf(0);
];
];
]