Data update

This commit is contained in:
Ingy dot Net 2024-04-19 16:56:29 -07:00
parent 0df55f9f24
commit aec8ed51b6
1045 changed files with 18889 additions and 2777 deletions

View file

@ -1,20 +0,0 @@
PROC doors = (INT limit)VOID:
(
MODE DOORSTATE = BOOL;
BOOL closed = FALSE;
BOOL open = NOT closed;
MODE DOORLIST = [limit]DOORSTATE;
DOORLIST the doors;
FOR i FROM LWB the doors TO UPB the doors DO the doors[i]:=closed OD;
FOR i FROM LWB the doors TO UPB the doors DO
FOR j FROM LWB the doors BY i TO UPB the doors DO
the doors[j] := NOT the doors[j]
OD
OD;
FOR i FROM LWB the doors TO UPB the doors DO
print((whole(i,-12)," is ",(the doors[i]|"opened"|"closed"),newline))
OD
);
doors(100)

View file

@ -1,7 +0,0 @@
PROC doors optimised = ( INT limit )VOID:
FOR i TO limit DO
REAL num := sqrt(i);
printf(($g" is "gl$,i,(ENTIER num = num |"opened"|"closed") ))
OD
;
doors optimised(limit)

View file

@ -0,0 +1,23 @@
class Main
{
static public function main()
{
findOpenDoors( 100 );
}
static function findOpenDoors( n : Int )
{
var door = [];
for( i in 0...n + 1 ){ door[ i ] = false; }
for( i in 1...n + 1 ){
var j = i;
while( j <= n ){
door[ j ] = ! door[ j ];
j += i;
}
}
for( i in 1...n + 1 ){
if( door[ i ] ){ Sys.print( ' $i' ); }
}
}
}

View file

@ -11,7 +11,7 @@ class RosettaDemo
while((i*i) <= n)
{
Sys.print(i*i + "\n");
Sys.println(i*i);
i++;
}
}

View file

@ -1,4 +1,4 @@
var .doors = [false] x 100
var .doors = [false] * 100
for .i of .doors {
for .j = .i; .j <= len(.doors); .j += .i {

View file

@ -1 +1 @@
writeln foldfrom(f if(.b: .a~[.c]; .a), [], .doors, series 1..len .doors)
writeln foldfrom(fn(.a, .b, .c) if(.b: .a~[.c]; .a), [], .doors, series 1..len .doors)

View file

@ -1 +1 @@
writeln map(f .x ^ 2, series 1..10)
writeln map fn{^2}, 1..10

View file

@ -1 +0,0 @@
writeln map f{^2}, 1..10

View file

@ -1 +1 @@
for i in range(1,101): print("Door %s is open" % i**2)
for i in range(1,11): print("Door %s is open" % i**2)

View file

@ -1,9 +0,0 @@
10 rem loop
20 let i = i + 1
30 print i * i, " open"
40 if i * i < 100 then 10
50 shell "pause"
60 end

View file

@ -0,0 +1,67 @@
import 'dart:math';
int playRandom(int n) {
var rnd = Random();
int pardoned = 0;
List<int> inDrawer = List<int>.generate(100, (i) => i);
List<int> sampler = List<int>.generate(100, (i) => i);
for (int round = 0; round < n; round++) {
inDrawer.shuffle();
bool found = false;
for (int prisoner = 0; prisoner < 100; prisoner++) {
found = false;
sampler.shuffle(rnd);
for (int i = 0; i < 50; i++) {
int reveal = sampler[i];
int card = inDrawer[reveal];
if (card == prisoner) {
found = true;
break;
}
}
if (!found) {
break;
}
}
if (found) {
pardoned++;
}
}
return (pardoned / n * 100).round();
}
int playOptimal(int n) {
var rnd = Random();
int pardoned = 0;
bool found = false;
List<int> inDrawer = List<int>.generate(100, (i) => i);
for (int round = 0; round < n; round++) {
inDrawer.shuffle(rnd);
for (int prisoner = 0; prisoner < 100; prisoner++) {
int reveal = prisoner;
found = false;
for (int go = 0; go < 50; go++) {
int card = inDrawer[reveal];
if (card == prisoner) {
found = true;
break;
}
reveal = card;
}
if (!found) {
break;
}
}
if (found) {
pardoned++;
}
}
return (pardoned / n * 100).round();
}
void main() {
int n = 100000;
print(" Simulation count: $n");
print(" Random play wins: ${playRandom(n).toStringAsFixed(2)}% of simulations");
print("Optimal play wins: ${playOptimal(n).toStringAsFixed(2)}% of simulations");
}

View file

@ -9,7 +9,7 @@ T RPNParse
F op(f)
I .stk.len < 2
X Error(Improperly written expression)
X.throw Error(Improperly written expression)
V b = .stk.pop()
V a = .stk.pop()
.stk.append(f(a, b))
@ -24,11 +24,11 @@ T RPNParse
E I c == * {.op((a, b) -> a * b)}
E I c == / {.op((a, b) -> a / b)}
E I c !=
X Error(Wrong char: c)
X.throw Error(Wrong char: c)
F get_result()
I .stk.len != 1
X Error(Improperly written expression)
X.throw Error(Improperly written expression)
R .stk.last
[Int] digits

View file

@ -0,0 +1,109 @@
BEGIN # play the 24 game - present the user with 4 digits and invite them to #
# enter an expression using the digits that evaluates to 24 #
[ 0 : 9 ]INT expression digits; # the digits entered by the user #
[ 0 : 9 ]INT puzzle digits; # the digits for the puzzle #
PROC eval = ( STRING expr )REAL: # parses and evaluates expr #
BEGIN
# syntax: expression = term ( ( "+" | "-" ) term )* #
# term = factor ( ( "*" | "/" ) factor ) * #
# factor = "0" | "1" | "2" | ... | "9" #
# | "(" expression ")" #
INT x pos := LWB expr - 1;
INT x end := UPB expr;
BOOL ok := TRUE;
PROC error = ( STRING msg )VOID:
IF ok THEN # this is the firstt error #
ok := FALSE;
print( ( msg, newline ) );
x pos := x end + 1
FI # error # ;
PROC curr ch = CHAR: IF x pos > x end THEN REPR 0 ELSE expr[ x pos ] FI;
PROC next ch = VOID: WHILE x pos +:= 1; curr ch = " " DO SKIP OD;
PROC factor = REAL:
IF curr ch >= "0" AND curr ch <= "9" THEN
INT digit = ABS curr ch - ABS "0";
REAL result = digit;
expression digits[ digit ] +:= 1;
next ch;
result
ELIF curr ch = "(" THEN
next ch;
REAL result = expression;
IF curr ch = ")" THEN
next ch
ELSE
error( """)"" expected after sub-expression" )
FI;
result
ELSE
error( "Unexpected """ + curr ch + """" );
0
FI # factor # ;
PROC term = REAL:
BEGIN
REAL result := factor;
WHILE curr ch = "*" OR curr ch = "/" DO
CHAR op = curr ch;
next ch;
IF op = "*" THEN result *:= factor ELSE result /:= factor FI
OD;
result
END # term # ;
PROC expression = REAL:
BEGIN
REAL result := term;
WHILE curr ch = "+" OR curr ch = "-" DO
CHAR op = curr ch;
next ch;
IF op = "+" THEN result +:= term ELSE result -:= term FI
OD;
result
END # expression # ;
next ch;
IF curr ch = REPR 0 THEN
error( "Missing expression" );
0
ELSE
REAL result = expression;
IF curr ch /= REPR 0 THEN
error( "Unexpected text: """ + expr[ x pos : ] + """ after expression" )
FI;
result
FI
END # eval # ;
WHILE
FOR i FROM 0 TO 9 DO # initialise the digit counts #
expression digits[ i ] := 0;
puzzle digits[ i ] := 0
OD;
print( ( "Enter an expression using these digits:" ) );
FOR i TO 4 DO # pick 4 random digits #
INT digit := 1 + ENTIER ( next random * 9 );
IF digit > 9 THEN digit := 9 FI;
puzzle digits[ digit ] +:= 1;
print( ( whole( digit, - 2 ) ) )
OD;
print( ( " that evaluates to 24: " ) );
# get and check the expression #
STRING expr;
read( ( expr, newline ) );
REAL result = eval( expr );
BOOL same := TRUE;
FOR i FROM 0 TO 9 WHILE same := puzzle digits[ i ] = expression digits[ i ] DO SKIP OD;
IF NOT same THEN
print( ( "That expression didn't contain the puzzle digits", newline ) )
ELIF result = 24 THEN
print( ( "Yes! That expression evaluates to 24", newline ) )
ELSE
print( ( "No - that expression evaluates to ", fixed( result, -8, 4 ), newline ) )
FI;
print( ( newline, "Play again [y/n]? " ) );
STRING play again;
read( ( play again, newline ) );
play again = "y" OR play again = "Y" OR play again = ""
DO SKIP OD
END

View file

@ -0,0 +1,2 @@
(let [(a b) (io.read :*number :*number)]
(print (+ a b)))

View file

@ -0,0 +1,5 @@
// N-grams. Nigel Galloway: April 11th., 2024
let fN g=let n,g=g@[0I],0I::g in List.map2(fun n g->n-g) n g
Seq.unfold(fun g->Some(g,fN g))[1I]|>Seq.take 9|>Seq.iteri(fun n g->printfn "%d -> %A" n g); printfn ""
let fG (n::g) l=(n+1I)%l=0I && g|>List.forall(fun n->n%l=0I)
Seq.unfold(fun(n,g)->Some((n,g),(n+1I,fN g)))(0I,[1I])|>Seq.skip 2|>Seq.filter(fun(n,_::g)->fG (List.rev g) n)|>Seq.takeWhile(fun(n,_)->n<100I)|>Seq.iter(fun(n,_)->printf "%A " n); printfn ""

View file

@ -2,7 +2,7 @@ F shortest_abbreviation_length(line, list_size)
V words = line.split( )
V word_count = words.len
I word_count != list_size
X ValueError(Not enough entries, expected #. found #..format(list_size, word_count))
X.throw ValueError(Not enough entries, expected #. found #..format(list_size, word_count))
V abbreviation_length = 1
L

View file

@ -0,0 +1,60 @@
Function Tokenize(text As String, tokens() As String) As Integer
Dim As Integer count = 0, posic = 1, start
While posic <= Len(text)
If Mid(text, posic, 1) <> " " Then
start = posic
While posic <= Len(text) Andalso Mid(text, posic, 1) <> " "
posic += 1
Wend
count += 1
tokens(count) = Mid(text, start, posic - start)
End If
posic += 1
Wend
Return count
End Function
Function Buscar(s As String) As Integer
Dim As Integer n, d, i, j
Dim As Boolean s_flag
Dim As String a, b
Dim As String r(1 To 100) ' Assuming a maximum of 100 tokens
n = Tokenize(s, r())
d = 1
Do
s_flag = True
For i = 1 To n
For j = i + 1 To n
a = Left(r(i), d)
b = Left(r(j), d)
If a = "" Or b = "" Then
s_flag = True
Exit For
Elseif a = b Then
s_flag = False
d += 1
Exit For
End If
Next j
If Not s_flag Then Exit For
Next i
Loop Until s_flag
Return d
End Function
Dim As Integer fileNum = Freefile()
If Open("days_of_week.txt" For Input As #fileNum) = 0 Then
Dim As String s
While Not Eof(fileNum)
Line Input #fileNum, s
Print Buscar(s); " "; s
Wend
Close #fileNum
Else
Print "Error opening file."
End If
Sleep

View file

@ -1,29 +1,44 @@
/*REXX program finds the minimum length abbreviation for a lists of words (from a file).*/
parse arg uw /*obtain optional arguments from the CL*/
iFID= 'ABBREV_A.TAB' /*name of the file that has the table. */
say 'minimum' /*display the first part of the title. */
say 'abbrev' center("days of the week", 80) /*display the title for the output. */
say '' center("", 80, '') /*display separator for the title line.*/
/* [↓] process the file until done. */
do while lines(iFID)\==0; days=linein(iFID) /*read a line (should contain 7 words).*/
minLen= abb(days) /*find the minimum abbreviation length.*/
say right(minLen, 4) ' ' days /*display a somewhat formatted output. */
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
abb: procedure; parse arg x; #=words(x) /*obtain list of words; find how many.*/
if #==0 then return '' /*check for a blank line or null line. */
@.= /*@. is a stemmed array of the words.*/
L=0 /*L is the max length of " " */
do j=1 for #; @.j=word(x, j) /*assign to array for faster processing*/
L.j=length(@.j); L= max(L, L.j) /*find the maximum length of any item. */
end /*L*/
/* [↓] determine minimum abbrev length*/
do m=1 for L; $= /*for all lengths, find a unique abbrev*/
do k=1 to #; a=left(@.k, m) /*get an abbreviation (with length M).*/
if wordpos(a,$)\==0 then iterate M /*test this abbreviation for uniquness.*/
$=$ a /*so far, it's unique; add to the list.*/
end /*k*/
leave m /*a good abbreviation length was found.*/
end /*m*/
return m
/*REXX program finds the minimum length abbreviation for a lists of words (from a file).*/
iFID= 'ABBREV_A.TAB' /*name of the file that has the table. */
Say 'minimum' /*display the first part of the title. */
Say 'abbrev' center('days of the week',80) /*display the title for the output. */
Say '------' center('',80,'-') /*display separator for the title line. */
/* process the file until done. */
Do While lines(iFID)\==0
days=linein(iFID) /* read a line (should contain 7 words).*/
If days='' Then /* check for a blank line or null line. */
Say ''
Else Do
minLen=abb(days) /*find the minimum abbreviation length. */
Say right(minLen,4) ' ' days /*display a somewhat formatted output. */
If minlen='????' Then
Say ' >>> No unique abbreviation found <<<'
End
End
Exit /*stick a fork in it,we're all done. */
/*----------------------------------------------------------------------------------*/
abb: Procedure
Parse Arg daylist /* obtain list of words */
dayn=words(daylist) /* find how many. */
day.='' /*day. is a stemmed array of the words. */
L=0 /*L is the max length of the words. */
Do j=1 for dayn
day.j=word(daylist,j) /*assign to array for faster processing */
L.j=length(day.j)
L= max(L,L.j) /* find the maximum length of any item. */
End
/* [?] determine minimum abbrev length */
Do m=1 To L
abblist='' /* for all lengths,find a unique abbrev */
Do k=1 to dayn
abbrev=strip(left(day.k,m)) /* get an abbreviation (with length M). */
If wordpos(abbrev,abblist)>0 Then /* not unique */
Iterate M /* try next length */
If length(abbrev)>=m Then
abblist=abblist abbrev /* so far,it's unique add to the list. */
End
leave /* a good abbreviation length was found. */
End
If m>L Then /* no unique abbreviation length found */
m='????'
Return m

View file

@ -0,0 +1,70 @@
Dim As String table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " _
+ "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " _
+ "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " _
+ "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " _
+ "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " _
+ "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " _
+ "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"
Function NextWord(Byref posic As Integer, text As String) As String
' skip spaces
While posic <= Len(text) And Mid(text, posic, 1) = " "
posic += 1
Wend
' get the word
Dim word As String = ""
While posic <= Len(text) And Mid(text, posic, 1) <> " "
word += Mid(text, posic, 1)
posic += 1
Wend
Return word
End Function
Function MinABLength(comando As String) As Integer
Dim ab_min As Integer = 1
While ab_min <= Len(comando) And Ucase(Mid(comando, ab_min, 1)) = Mid(comando, ab_min, 1)
ab_min += 1
Wend
Return ab_min - 1
End Function
Function Expand(table As String, word As String) As String
If Len(word) = 0 Then
Return ""
Else
Dim As Integer word_len = Len(word)
Dim As String result = "*error*"
Dim As Integer posic = 1
Do
Dim As String comando = NextWord(posic, table)
If Len(comando) = 0 Then
Exit Do
Elseif word_len < MinABLength(comando) Or word_len > Len(comando) Then
Continue Do
Elseif Ucase(word) = Ucase(Left(comando, word_len)) Then
result = Ucase(comando)
Exit Do
End If
Loop
Return result
End If
End Function
Sub TestExpand(words As String, table As String)
Dim As String word, results = "", separator = ""
Dim As Integer posic = 1
Do
word = NextWord(posic, words)
If Len(word) = 0 Then Exit Do
results += separator + Expand(table, word)
separator = " "
Loop
Print "Input: "; words
Print "Output: "; results
End Sub
' task test cases
TestExpand("riG rePEAT copies put mo rest types fup. 6 poweRin", table)
TestExpand("", table)
Sleep

View file

@ -1,27 +1,41 @@
/*REXX program validates a user "word" against a "command table" with abbreviations.*/
parse arg uw /*obtain optional arguments from the CL*/
if uw='' then uw= 'riG rePEAT copies put mo rest types fup. 6 poweRin'
say 'user words: ' uw
@= 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy' ,
'COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find' ,
'NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput' ,
'Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO' ,
'MErge MOve MODify MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT' ,
'READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT' ,
'RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'
say 'full words: ' validate(uw) /*display the result(s) to the terminal*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
validate: procedure expose @; arg x; upper @ /*ARG capitalizes all the X words. */
$= /*initialize the return string to null.*/
do j=1 to words(x); _=word(x, j) /*obtain a word from the X list. */
do k=1 to words(@); a=word(@, k) /*get a legitimate command name from @.*/
L=verify(_, 'abcdefghijklmnopqrstuvwxyz', "M") /*maybe get abbrev's len.*/
if L==0 then L=length(_) /*0? Command name can't be abbreviated*/
if abbrev(a, _, L) then do; $=$ a; iterate j; end /*is valid abbrev?*/
end /*k*/
$=$ '*error*' /*processed the whole list, not valid. */
end /*j*/
return strip($) /*elide the superfluous leading blank. */
/*REXX program validates user words against a "command table" with abbreviations.*/
Parse Arg userwords /*obtain optional arguments from the command line */
If userwords='' Then /* nothing specified, use default list from task */
userwords= 'riG rePEAT copies put mo rest types fup. 6 poweRin'
Say 'user words: ' userwords
keyws='Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy',
'COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find',
'NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput',
'Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO',
'MErge MOve MODify MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT',
'READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT',
'RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'
Say 'full words: ' validate(userwords) /*display the result(s) To the terminal*/
Exit /*stick a fork in it, we're all Done. */
/*----------------------------------------------------------------------------------*/
validate: Procedure Expose keyws
Arg userwords /* Arg = Parse Upper Arg get userwords in uppercase */
res='' /* initialize the return string To null */
Do j=1 To words(userwords) /* loop through userwords */
uword=word(userwords,j) /* get next userword */
Do k=1 To words(keyws) /* loop through all keywords */
keyw=word(keyws,k)
L=verify(keyw,'abcdefghijklmnopqrstuvwxyz','M') /* pos. of first lowercase ch*/
If L==0 Then /* keyword is all uppercase */
L=length(keyw) /* we need L characters for a match */
Else
L=L-1 /* number of uppercase characters */
If abbrev(translate(keyw),uword,L) Then Do /* uword is an abbreviation */
res=res keyw /* add the matching keyword To the result string */
iterate j /* and proceed with the next userword if any */
End
End
res=res '*error*' /* no match found. indicate error */
End
Return strip(res) /* get rid of leading böank */
syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
user words: riG rePEAT copies put mo rest types fup. 6 poweRin
full words: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
</pre>

View file

@ -1,29 +1,38 @@
/*REXX program validates a user "word" against a "command table" with abbreviations.*/
parse arg uw /*obtain optional arguments from the CL*/
if uw='' then uw= 'riG rePEAT copies put mo rest types fup. 6 poweRin'
say 'user words: ' uw
Parse Arg uw /*obtain optional arguments from the CL*/
If uw='' Then uw= 'riG rePEAT copies put mo rest types fup. 6 poweRin'
Say 'user words: ' uw
@= 'add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3',
keyws= 'add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3',
'compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate',
'3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2',
'forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load',
'locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2',
'msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3',
'msg next 1 overlay 1 Parse preserve 4 purge 3 put putD query 1 quit read recover 3',
'refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left',
'2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1'
say 'full words: ' validate(uw) /*display the result(s) to the terminal*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
validate: procedure expose @; arg x; upper @ /*ARG capitalizes all the X words. */
$= /*initialize the return string to null.*/
do j=1 to words(x); _=word(x, j) /*obtain a word from the X list. */
do k=1 to words(@); a=word(@, k) /*get a legitmate command name from @.*/
L=word(@, k+1) /*··· and maybe get it's abbrev length.*/
if datatype(L, 'W') then k=k + 1 /*yuppers, it's an abbrev length.*/
else L=length(a) /*nope, it can't be abbreviated.*/
if abbrev(a, _, L) then do; $=$ a; iterate j; end /*is valid abbrev?*/
end /*k*/
$=$ '*error*' /*processed the whole list, not valid. */
end /*j*/
return strip($) /*elide the superfluous leading blank. */
Say 'full words: ' validate(uw) /*display the result(s) to the terminal*/
Exit /*stick a fork in it, we're all done. */
/*--------------------------------------------------------------------------------------*/
validate: Procedure Expose keyws
keyws=translate(keyws)
Arg userwords /*ARG capitalizes all the userwords. */
res='' /*initialize the Return string to null.*/
Do j=1 to words(userwords) /* loop over userwords */
uword=word(userwords,j) /*obtain a word from the userword list.*/
Do k=1 to words(keyws) /* loop over keywords */
kw=word(keyws,k) /*get a legitmate command name from keyws.*/
L=word(keyws,k+1) /*··· and maybe get its abbrev length.*/
If datatype(L,'W') Then /* it's a number - an abbrev length. */
k=k + 1 /* skip it for next kw */
Else /* otherwise */
L=length(kw) /* it can't be abbreviated. */
If abbrev(kw,uword,L) Then Do /* is valid abbreviation */
res=res kw /* add to result string */
Iterate j /* proceed with next userword */
End
End
res=res '*error*' /*processed the whole list, not valid */
End
Return strip(res) /* elide superfluous leading blank. */

View file

@ -37,7 +37,7 @@ grid[32][32] = 64 * 64
simulate(&grid)
V ppm = File(sand_pile.ppm, w)
V ppm = File(sand_pile.ppm, WRITE)
ppm.write_bytes(("P6\n#. #.\n255\n".format(grid.len, grid.len)).encode())
V colors = [[Byte(0), 0, 0],
[Byte(255), 0, 0],

View file

@ -34,7 +34,7 @@ BEGIN # model Abelian sandpiles #
OP MAX = ( [,]INT s )INT:
BEGIN
INT result := s[ 1 LWB s, 2 LWB s ];
FOR i FROM 1 LWB s TO 2 UPB s DO
FOR i FROM 1 LWB s TO 1 UPB s DO
FOR j FROM 2 LWB s TO 2 UPB s DO
IF s[ i, j ] > result THEN result := s[ i, j ] FI
OD

View file

@ -1,40 +1,51 @@
/*REXX pgm displays abundant odd numbers: 1st 25, one─thousandth, first > 1 billion. */
/*REXX pgm displays abundant odd numbers: 1st 25, one-thousandth, first > 1 billion. */
parse arg Nlow Nuno Novr . /*obtain optional arguments from the CL*/
if Nlow=='' | Nlow=="," then Nlow= 25 /*Not specified? Then use the default.*/
if Nuno=='' | Nuno=="," then Nuno= 1000 /* " " " " " " */
if Novr=='' | Novr=="," then Novr= 1000000000 /* " " " " " " */
numeric digits max(9, length(Novr) ) /*ensure enough decimal digits for // */
@= 'odd abundant number' /*variable for annotating the output. */
#= 0 /*count of odd abundant numbers so far.*/
do j=3 by 2 until #>=Nlow; $= sigO(j) /*get the sigma for an odd integer. */
if $<=j then iterate /*sigma ≤ J ? Then ignore it. */
#= # + 1 /*bump the counter for abundant odd #'s*/
say rt(th(#)) @ 'is:'rt(commas(j), 8) rt("sigma=") rt(commas($), 9)
end /*j*/
if Nlow=='' | Nlow==',' then Nlow= 25 /*Not specified? Then use the default.*/
if Nuno=='' | Nuno==',' then Nuno= 1000 /* ' ' ' ' ' ' */
if Novr=='' | Novr==',' then Novr= 1000000000 /* ' ' ' ' ' ' */
numeric digits max(9,length(Novr)) /*ensure enough decimal digits for // */
a= 'odd abundant number' /*variable for annotating the output. */
n= 0 /*count of odd abundant numbers so far.*/
do j=3 by 2 until n>=Nlow; /*get the sigma for an odd integer. */
d=sigO(j)
if d>j then Do /*sigma = J ? Then ignore it. */
n= n + 1 /*bump the counter for abundant odd n's*/
say rt(th(n)) a 'is:'rt(commas(j),8) rt('sigma=') rt(commas(d),9)
End
end /*j*/
say
#= 0 /*count of odd abundant numbers so far.*/
do j=3 by 2; $= sigO(j) /*get the sigma for an odd integer. */
if $<=j then iterate /*sigma ≤ J ? Then ignore it. */
#= # + 1 /*bump the counter for abundant odd #'s*/
if #<Nuno then iterate /*Odd abundant# count<Nuno? Then skip.*/
say rt(th(#)) @ 'is:'rt(commas(j), 8) rt("sigma=") rt(commas($), 9)
n= 0 /*count of odd abundant numbers so far.*/
do j=3 by 2; /*get the sigma for an odd integer. */
d= sigO(j)
if d>j then do /*sigma = J ? Then ignore it. */
n= n + 1 /*bump the counter for abundant odd n's*/
if n>=Nuno then do /*Odd abundantn count<Nuno? Then skip.*/
say rt(th(n)) a 'is:'rt(commas(j),8) rt('sigma=') rt(commas(d),9)
leave /*we're finished displaying NUNOth num.*/
end /*j*/
End
End
end /*j*/
say
do j=1+Novr%2*2 by 2; $= sigO(j) /*get sigma for an odd integer > Novr. */
if $<=j then iterate /*sigma ≤ J ? Then ignore it. */
say rt(th(1)) @ 'over' commas(Novr) "is: " commas(j) rt('sigma=') commas($)
leave /*we're finished displaying NOVRth num.*/
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas:parse arg _; do c_=length(_)-3 to 1 by -3; _=insert(',', _, c_); end; return _
rt: procedure; parse arg #,len; if len=='' then len= 20; return right(#, len)
th: parse arg th; return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4))
/*──────────────────────────────────────────────────────────────────────────────────────*/
sigO: parse arg x; s= 1 /*sigma for odd integers. ___*/
do k=3 by 2 while k*k<x /*divide by all odd integers up to √ x */
if x//k==0 then s= s + k + x%k /*add the two divisors to (sigma) sum. */
end /*k*/ /* ___*/
if k*k==x then return s + k /*Was X a square? If so, add √ x */
return s /*return (sigma) sum of the divisors. */
do j=1+Novr%2*2 by 2; /*get sigma for an odd integer > Novr. */
d= sigO(j)
if d>j then Do /*sigma = J ? Then ignore it. */
say rt(th(1)) a 'over' commas(Novr) 'is: ' commas(j) rt('sigma=') commas(d)
Leave /*we're finished displaying NOVRth num.*/
End
end /*j*/
exit
/*--------------------------------------------------------------------------------------*/
commas:parse arg _; do c_=length(_)-3 to 1 by -3; _=insert(',',_,c_); end; return _
rt: procedure; parse arg n,len; if len=='' then len=20; return right(n,len)
th: parse arg th; return th||word('th st nd rd',1+(th//10)*(th//100%10\==1)*(th//10<4))
/*--------------------------------------------------------------------------------------*/
sigO: parse arg x; /*sigma for odd integers. ___*/
s=1
do k=3 by 2 while k*k<x /*divide by all odd integers up to v x */
if x//k==0 then
s= s + k + x%k /*add the two divisors to (sigma) sum. */
end /*k*/ /* ___*/
if k*k==x then
return s + k /*Was X a square? If so,add v x */
return s /*return (sigma) sum of the divisors. */

View file

@ -0,0 +1,90 @@
# Require $n > 0
def nwise($n):
def _n: if length <= $n then . else .[:$n] , (.[$n:] | _n) end;
if $n <= 0 then "nwise: argument should be non-negative" else _n end;
### Part 1 - generic functions
# Ensure $x is in the input sorted array
def ensure($x):
bsearch($x) as $i
| if $i >= 0 then .
else (-1-$i) as $i
| .[:$i] + [$x] + .[$i:]
end ;
def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .;
def table($wide; $pad):
nwise($wide) | map(lpad($pad)) | join(" ");
def count(s): reduce s as $x (0; .+1);
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
# jq optimizes the recursive call of _gcd in the following:
def gcd($a;$b):
def _gcd:
if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end;
[$a,$b] | _gcd ;
def totient:
. as $n
| count( range(0; .) | select( gcd($n; .) == 1) );
# Emit a sorted array
def getPerfectPowers( $maxExp ):
(10 | power($maxExp)) as $upper
| reduce range( 2; 1 + ($upper|sqrt|floor)) as $i ({pps: []};
.p = $i * $i
| until (.p >= $upper;
.pps += [ .p ]
| .p *= $i) )
| .pps
| sort;
# Input: a sufficiently long array of perfect powers in order
def getAchilles($minExp; $maxExp):
def cbrt: pow(.; 1/3);
. as $pps
| (10 | power($minExp)) as $lower
| (10 | power($maxExp)) as $upper
| ($upper | sqrt | floor) as $sqrtupper
| reduce range(1; 1 + ($upper|cbrt|floor)) as $b ({achilles: []};
($b | .*.*.) as $b3
| .done = false
| .a = 1
| until(.done or (.a > $sqrtupper);
($b3 * .a * .a) as $p
| if $p >= $upper then .done = true
elif $p >= $lower and ($pps | bsearch($p) < 0)
then .achilles |= ensure($p)
end
| .a += 1 ) )
| .achilles;
def task($maxDigits):
getPerfectPowers($maxDigits)
| . as $perfectPowers
| getAchilles(1; 5)
| . as $achilles
| "First 50 Achilles numbers:",
(.[:50] | table(10;5)),
"\nFirst 30 strong Achilles numbers:",
({ strongAchilles:[], count:0, n:0 }
| until (.count >= 30;
$achilles[.n] as $a
| ($a | totient) as $tot
| if ($achilles | bsearch($tot)) >= 0
then .strongAchilles |= ensure($a)
| .count += 1
end
| .n += 1 )
| (.strongAchilles | table(10;5) ),
"\nNumber of Achilles numbers with:",
( range(2; 1+$maxDigits) as $d
| ($perfectPowers|getAchilles($d-1; $d)|length) as $ac
| "\($d) digits: \($ac)" ) )
;
task(10)

View file

@ -0,0 +1,35 @@
#Include "win\winldap.bi"
Dim ldap As LDAP Ptr
Dim hostname As String
Dim port As Integer
Dim username As String
Dim password As String
Dim result As Integer
hostname = "ldap.example.com"
port = 389 ' Standard port for LDAP. Use 636 for LDAPS.
username = "cn=username,dc=example,dc=com"
password = "password"
' Initialize the LDAP connection
ldap = ldap_init(hostname, port)
If ldap = NULL Then
Print "Error initializing LDAP connection"
Sleep
End 1
End If
' Authenticate with the LDAP server
result = ldap_simple_bind_s(ldap, username, password)
If result <> LDAP_SUCCESS Then
Print "Error authenticating with LDAP server: "; ldap_err2string(result)
Sleep
End 1
End If
' Here you can perform LDAP operations
'...
' We close the connection when finished
ldap_unbind(ldap)

View file

@ -1,7 +1,7 @@
val .isPrime = f .i == 2 or .i > 2 and
not any f(.x) .i div .x, pseries 2 .. .i ^/ 2
val .isPrime = fn(.i) .i == 2 or .i > 2 and
not any fn(.x) .i div .x, pseries 2 .. .i ^/ 2
val .sumDigits = f fold f{+}, s2n toString .i
val .sumDigits = fn(.i) fold fn{+}, s2n string .i
writeln "Additive primes less than 500:"
@ -9,10 +9,10 @@ var .count = 0
for .i in [2] ~ series(3..500, 2) {
if .isPrime(.i) and .isPrime(.sumDigits(.i)) {
write $"\.i:3; "
write $"\{.i:3} "
.count += 1
if .count div 10: writeln()
}
}
writeln $"\n\n\.count; additive primes found.\n"
writeln $"\n\n\{.count} additive primes found.\n"

View file

@ -0,0 +1,21 @@
main :: [sys_message]
main = [Stdout (table 5 10 nums), Stdout countmsg]
where nums = filter additive_prime [1..500]
countmsg = "Found " ++ show (#nums) ++ " additive primes < 500\n"
table :: num->num->[num]->[char]
table w c ls = lay [concat (map (rjustify w . show) l) | l <- split c ls]
split :: num->[*]->[[*]]
split n ls = [ls], if #ls < n
= take n ls:split n (drop n ls), otherwise
additive_prime :: num->bool
additive_prime n = prime (dsum n) & prime n
dsum :: num->num
dsum n = n, if n<10
= n mod 10 + dsum (n div 10), otherwise
prime :: num->bool
prime n = n>=2 & #[d | d<-[2..entier (sqrt n)]; n mod d=0] = 0

View file

@ -1,44 +1,65 @@
/*REXX program counts/displays the number of additive primes under a specified number N.*/
parse arg n cols . /*get optional number of primes to find*/
if n=='' | n=="," then n= 500 /*Not specified? Then assume default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " */
call genP n /*generate all primes under N. */
w= 10 /*width of a number in any column. */
title= " additive primes that are < " commas(n)
if cols>0 then say ' index 'center(title, 1 + cols*(w+1) )
if cols>0 then say ''center("" , 1 + cols*(w+1), '')
found= 0; idx= 1 /*initialize # of additive primes & IDX*/
$= /*a list of additive primes (so far). */
do j=1 for #; p= @.j /*obtain the Jth prime. */
_= sumDigs(p); if \!._ then iterate /*is sum of J's digs a prime? No, skip.*/ /* ◄■■■■■■■■ a filter. */
found= found + 1 /*bump the count of additive primes. */
if cols<0 then iterate /*Build the list (to be shown later)? */
c= commas(p) /*maybe add commas to the number. */
$= $ right(c, max(w, length(c) ) ) /*add additive prime──►list, allow big#*/
if found//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
/*REXX program counts/displays the number of additive primes less than N. */
Parse Arg n cols . /*get optional number of primes To find*/
If n=='' | n==',' Then n= 500 /*Not specified? Then assume default.*/
If cols=='' | cols==',' Then cols= 10 /* ' ' ' ' ' */
call genP n /*generate all primes under N. */
w=5 /*width of a number in any column. */
title= 'additive primes that are < 'commas(n)
If cols>0 Then Say ' index ¦'center(title,cols*(w+1)+1)
If cols>0 Then Say '-------+'center('' ,cols*(w+1)+1,'-')
found=0
ol='' /*a list of additive primes (so far). */
idx=1
Do j=1 By 1
p=p.j /*obtain the Jth prime. */
If p>n Then Leave /* no more needed */
_=sumDigs(p)
If !._ Then Do
found=found+1 /*bump the count of additive primes. */
c=commas(p) /*maybe add commas To the number. */
ol=ol right(c,max(w,length(c))) /*add additive prime--?list,allow big# */
If words(ol)=10 Then Do /* a line is complete */
Say center(idx,7)'¦' substr(ol,2) /*display what we have so far (cols). */
ol='' /* prepare for next line */
idx=idx+10
End
End
End /*j*/
if $\=='' then say center(idx, 7)"" substr($, 2) /*possible display residual output.*/
if cols>0 then say ''center("" , 1 + cols*(w+1), '')
say
say 'found ' commas(found) title
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
sumDigs: parse arg x 1 s 2; do k=2 for length(x)-1; s= s + substr(x,k,1); end; return s
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: parse arg n; @.1= 2; @.2= 3; @.3= 5; @.4= 7; @.5= 11; @.6= 13
!.= 0; !.2= 1; !.3= 1; !.5= 1; !.7= 1; !.11= 1; !.13= 1
#= 6; sq.#= @.# ** 2 /*the number of primes; prime squared.*/
do j=@.#+2 by 2 for max(0, n%2-@.#%2-1) /*find odd primes from here on. */
parse var j '' -1 _ /*obtain the last digit of the J var.*/
if _==5 then iterate; if j// 3==0 then iterate /*J ÷ by 5? J ÷ by 3? */
if j// 7==0 then iterate; if j//11==0 then iterate /*" " " 7? " " " 11? */
/* [↓] divide by the primes. ___ */
do k=6 while sq.k<=j /*divide J by other primes ≤ √ J */
if j//@.k==0 then iterate j /*÷ by prev. prime? ¬prime ___ */
end /*k*/ /* [↑] only divide up to √ J */
#= # + 1; @.#= j; sq.#= j*j; !.j= 1 /*bump prime count; assign prime & flag*/
end /*j*/; return
If ol\=='' Then
Say center(idx,7)'¦' substr(ol,2) /*possible display residual output. */
If cols>0 Then
Say '--------'center('',cols*(w+1)+1,'-')
Say
Say 'found ' commas(found) title
Exit 0 /*stick a fork in it, we're all done. */
/*--------------------------------------------------------------------------------*/
commas: Parse Arg ?; Do jc=length(?)-3 To 1 by -3; ?=insert(',',?,jc); End; Return ?
sumDigs:Parse Arg x 1 s 2; Do k=2 For length(x)-1; s=s+substr(x,k,1); End; Return s
/*--------------------------------------------------------------------------------*/
genP:
Parse Arg n
pl=2 3 5 7 11 13
!.=0
Do np=1 By 1 While pl<>''
Parse Var pl p pl
p.np=p
sq.np=p*p
!.p=1
End
np=np-1
Do j=p.np+2 by 2 While j<n
Parse Var j '' -1 _ /*obtain the last digit of the J var.*/
If _==5 Then Iterate
If j// 3==0 Then Iterate
If j// 7==0 Then Iterate
If j//11==0 Then Iterate
Do k=6 By 1 While sq.k<=j /*divide J by other primes <=sqrt(j) */
If j//p.k==0 Then Iterate j /* not prime - try next */
End /*k*/
np=np+1 /*bump prime count; assign prime & flag*/
p.np=j
sq.np=j*j
!.j=1
End /*j*/
Return

View file

@ -0,0 +1,26 @@
program additive_primes;
loop for i in [i : i in [1..499] | additive_prime i] do
nprint(lpad(str i, 4));
if (n +:= 1) mod 10 = 0 then
print;
end if;
end loop;
print;
print("There are " + str n + " additive primes less than 500.");
op additive_prime(n);
return prime n and prime digitsum n;
end op;
op prime(n);
return n>=2 and not exists d in {2..floor sqrt n} | n mod d = 0;
end op;
op digitsum(n);
loop while n>0;
s +:= n mod 10;
n div:= 10;
end loop;
return s;
end op;
end program;

View file

@ -0,0 +1,15 @@
[] # list of primes to be populated
↘2⇡500 # candidates (starting at 2)
# Take the first remaining candidate, which will be prime, save it,
# then remove every candidate that it divides. Repeat until none left.
⍢(▽≠0◿⊃⊢(.↘1)⟜(⊂⊢)|>0⧻)
# Tidy up.
⇌◌
# Build sum of digits of each.
≡(/+≡⋕°⋕)...
# Mask out those that result in non-primes.
⊏⊚±⬚0⊏⊗
# Return values and length.
⧻.

View file

@ -1,63 +1,126 @@
/*REXX program classifies various positive integers for types of aliquot sequences. */
parse arg low high $L /*obtain optional arguments from the CL*/
high= word(high low 10,1); low= word(low 1,1) /*obtain the LOW and HIGH (range). */
if $L='' then $L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080
numeric digits 100 /*be able to compute the number: BIG */
big= 2**47; NTlimit= 16 + 1 /*limits for a non─terminating sequence*/
numeric digits max(9, length(big) ) /*be able to handle big numbers for // */
digs= digits() /*used for align numbers for the output*/
#.= .; #.0= 0; #.1= 0 /*#. are the proper divisor sums. */
say center('numbers from ' low " ───► " high ' (inclusive)', 153, "")
do n=low to high; call classify n /*call a subroutine to classify number.*/
end /*n*/ /* [↑] process a range of integers. */
say
say center('first numbers for each classification', 153, "")
class.= 0 /* [↓] ensure one number of each class*/
do q=1 until class.sociable\==0 /*the only one that has to be counted. */
call classify -q /*minus (-) sign indicates don't tell. */
_= what; upper _ /*obtain the class and uppercase it. */
class._= class._ + 1 /*bump counter for this class sequence.*/
if class._==1 then say right(q, digs)':' center(what, digs) $
end /*q*/ /* [↑] only display the 1st occurrence*/
say /* [↑] process until all classes found*/
say center('classifications for specific numbers', 153, "")
do i=1 for words($L) /*$L: is a list of "special numbers".*/
call classify word($L, i) /*call a subroutine to classify number.*/
end /*i*/ /* [↑] process a list of integers. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
classify: parse arg a 1 aa; a= abs(a) /*obtain number that's to be classified*/
if #.a\==. then s= #.a /*Was this number been summed before?*/
else s= sigma(a) /*No, then classify number the hard way*/
#.a= s /*define sum of the proper divisors. */
$= s /*define the start of integer sequence.*/
what= 'terminating' /*assume this kind of classification. */
c.= 0 /*clear all cyclic sequences (to zero).*/
c.s= 1 /*set the first cyclic sequence. */
if $==a then what= 'perfect' /*check for a "perfect" number. */
else do t=1 while s>0 /*loop until sum isn't 0 or > big.*/
m= s /*obtain the last number in sequence. */
if #.m==. then s= sigma(m) /*Not defined? Then sum proper divisors*/
else s= #.m /*use the previously found integer. */
if m==s then if m>=0 then do; what= 'aspiring'; leave; end
parse var $ . word2 . /*obtain the 2nd number in sequence. */
if word2==a then do; what= 'amicable'; leave; end
$= $ s /*append a sum to the integer sequence.*/
if s==a then if t>3 then do; what= 'sociable'; leave; end
if c.s then if m>0 then do; what= 'cyclic' ; leave; end
c.s= 1 /*assign another possible cyclic number*/
/* [↓] Rosetta Code task's limit: >16 */
if t>NTlimit then do; what= 'nonterminating'; leave; end
if s>big then do; what= 'NONTERMINATING'; leave; end
end /*t*/ /* [↑] only permit within reason. */
if aa>0 then say right(a, digs)':' center(what, digs) $
return /* [↑] only display if AA is positive*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
sigma: procedure expose #. !.; parse arg x; if 11<2 then return 0; odd= x // 2
s= 1 /* [↓] use EVEN or ODD integers. ___*/
do j=2+odd by 1+odd while j*j<x /*divide by all the integers up to √ X */
if x//j==0 then s= s + j + x % j /*add the two divisors to the sum. */
end /*j*/ /* [↓] adjust for square. ___*/
if j*j==x then s= s + j /*Was X a square? If so, add √ X */
#.x= s /*memoize division sum for argument X.*/
return s /*return " " " " " */
/*REXX program classifies various positive integers For types of aliquot sequences.*/
Parse Arg low high LL /*obtain optional arguments from the CL*/
high=word(high low 10,1)
low=word(low 1,1) /*obtain the LOW and HIGH (range). */
If LL='' Then
LL=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080
Numeric Digits 20 /*be able To compute the number: BIG */
big=2**47
NTlimit=16+1 /*limit for a non-terminating sequence */
Numeric Digits max(9,length(big)) /*be able To handle big numbers For // */
digs=digits() /*used For align numbers For the output*/
dsum.=.
dsum.0=0
dsum.1=0 /* dsum. are the proper divisor sums. */
Say 'Numbers from ' low ' ---> ' high ' (inclusive):'
Do n=low To high /* process specified range */
Call classify n /* call subroutine To classify number. */
End
Say
Say 'First numbers for each classification:'
class.=0 /* [?] ensure one number of each class*/
Do q=1 Until class.sociable\==0 /*the only one that has To be counted. */
Call classify -q /*minus (-) sign indicates don't tell. */
_=translate(what) /*obtain the class and uppercase it. */
class._=class._+1 /*bump counter For this class sequence.*/
If class._==1 Then /*first number of this class */
Call out q,what,dd
End
Say /* [?] process Until all classes found*/
Say 'Classifications for specific numbers:'
Do i=1 To words(LL) /* process a list of "special numbers" */
Call classify word(LL,i) /*call subroutine To classify number. */
End
Exit /*stick a fork in it,we're all done. */
out:
Parse arg number,class,dd
dd.=''
Do di=1 By 1 While length(dd)>50
do dj=50 To 10 By -1
If substr(dd,dj,1)=' ' Then Leave
End
dd.di=left(dd,dj)
dd=substr(dd,dj+1)
End
dd.di=dd
Say right(number,digs)':' center(class,digs) dd.1||conti(1)
Do di=2 By 1 While dd.di>''
Say copies(' ',33)dd.di||conti(di)
End
Return
conti:
Parse arg this
next=this+1
If dd.next>'' Then Return '...'
Else Return ''
/*---------------------------------------------------------------------------------*/
classify:
Parse Arg a 1 aa
a=abs(a) /*obtain number that's to be classified*/
If dsum.a\==. Then
s=dsum.a /*Was this number been summed before?*/
Else
s=dsum(a) /*No,Then classify number the hard way */
dsum.a=s /*define sum of the proper divisors. */
dd=s /*define the start of integer sequence.*/
what='terminating' /*assume this kind of classification. */
c.=0 /*clear all cyclic sequences (to zero).*/
c.s=1 /*set the first cyclic sequence. */
If dd==a Then
what='perfect' /*check For a "perfect" number. */
Else Do t=1 By 1 While s>0 /*loop Until sum isn't 0 or > big.*/
m=s /*obtain the last number in sequence. */
If dsum.m==. Then /*Not defined? */
s=dsum(m) /* compute sum pro of per divisors */
Else
s=dsum.m /*use the previously found integer. */
If m==s Then
If m>=0 Then Do
what='aspiring'
Leave
End
If word(dd,2)=a Then Do
what='amicable'
Leave
End
dd=dd s /*append a sum To the integer sequence.*/
If s==a Then
If t>3 Then Do
what='sociable'
Leave
End
If c.s Then
If m>0 Then Do
what='cyclic'
Leave
End
c.s=1 /*assign another possible cyclic number*/
/* [?] Rosetta Code task's limit: >16 */
If t>NTlimit Then Do
what='non-terminating'
Leave
End
If s>big Then Do
what='NON-TERMINATING'
Leave
End
End
If aa>0 Then /* display only if AA is positive */
Call out a,what,dd
Return
/*---------------------------------------------------------------------------------*/
dsum: Procedure Expose dsum. /* compute the sum of proper divisors */
Parse Arg x
If x<2 Then
Return 0
odd=x//2
s=1 /* use EVEN or ODD integers. */
Do j=2+odd by 1+odd While j*j<x /* divide by all the integers ) */
/* up to but excluding sqrt(x) */
If x//j==0 Then /* j is a divisor, so is x%j */
s=s+j+x%j /*add the two divisors To the sum. */
End
If j*j==x Then /* if x is a square */
s=s+j /* add sqrt(X) */
dsum.x=s /* memoize proper divisor sum of X */
Return s /* return the proper divisor sum */

View file

@ -1,15 +1,15 @@
val .wordsets = [
w/the that a/,
w/frog elephant thing/,
w/walked treaded grows/,
w/slowly quickly/,
fw/the that a/,
fw/frog elephant thing/,
fw/walked treaded grows/,
fw/slowly quickly/,
]
val .alljoin = f(.words) for[=true] .i of len(.words)-1 {
val .alljoin = fn(.words) for[=true] .i of len(.words)-1 {
if last(.words[.i]) != first(.words[.i+1]): break = false
}
# .amb expects 2 or more arguments
val .amb = f(...[2 .. -1] .words) if(.alljoin(.words): join " ", .words)
val .amb = fn(...[2 .. -1] .words) if(.alljoin(.words): join " ", .words)
writeln join "\n", filter(mapX(.amb, .wordsets...))
writeln join "\n", filter mapX .amb, .wordsets...

View file

@ -33,7 +33,7 @@ const proc: main is func
var integer: length is 0;
var integer: maxLength is 0;
begin
dictFile := openStrifile(getHttp("wiki.puzzlers.org/pub/wordlists/unixdict.txt"));
dictFile := openStriFile(getHttp("wiki.puzzlers.org/pub/wordlists/unixdict.txt"));
while hasNext(dictFile) do
readln(dictFile, word);
sortedLetters := sort(word);

View file

@ -1,4 +1,4 @@
val .countDivisors = f(.n) {
val .countDivisors = fn(.n) {
if .n < 2: return 1
for[=2] .i = 2; .i <= .n\2; .i += 1 {
if .n div .i : _for += 1

View file

@ -1,40 +1,40 @@
/*REXX program finds and displays N number of anti─primes or highly─composite numbers.*/
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
maxD= 0 /*the maximum number of divisors so far*/
say 'index antiprime' /*display a title for the numbers shown*/
#= 0 /*the count of anti─primes found " " */
do once=1 for 1
do i=1 for 59 /*step through possible numbers by twos*/
d= #divs(i); if d<=maxD then iterate /*get # divisors; Is too small? Skip.*/
#= # + 1; maxD= d /*found an anti─prime #; set new minD.*/
say center(#, 7) right(i, 10) /*display the index and the anti─prime.*/
if #>=N then leave once /*if we have enough anti─primes, done. */
end /*i*/
/*REXX program finds and displays N number of anti-primes (highly-composite) numbers.*/
Parse Arg N . /* obtain optional argument from the CL. */
If N=='' | N=="," Then N=20 /* Not specified? Then use the default. */
maxD=0 /* the maximum number of divisors so far */
Say '-index- --anti-prime--' /* display a title For the numbers shown */
nn=0 /* the count of anti-primes found " " */
Do i=1 For 59 While nn<N /* step through possible numbers by twos */
d=nndivs(i) /* get nn divisors; */
If d>maxD Then Do /* found an anti-prime nn set new maxD */
maxD=d
nn=nn+1
Say center(nn,7) right(i,10) /* display the index and the anti-prime. */
End
End /*i*/
do j=60 by 20 /*step through possible numbers by 20. */
d= #divs(j); if d<=maxD then iterate /*get # divisors; Is too small? Skip.*/
#= # + 1; maxD= d /*found an anti─prime #; set new minD.*/
say center(#, 7) right(j, 10) /*display the index and the anti─prime.*/
if #>=N then leave /*if we have enough anti─primes, done. */
end /*j*/
end /*once*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
#divs: procedure; parse arg x 1 y /*X and Y: both set from 1st argument.*/
if x<3 then return x /*handle special cases for one and two.*/
if x==4 then return 3 /* " " " " four. */
if x<6 then return 2 /* " " " " three or five*/
odd= x // 2 /*check if X is odd or not. */
if odd then #= 1 /*Odd? Assume Pdivisors count of 1.*/
else do; #= 3; y= x % 2 /*Even? " " " " 3.*/
end /* [↑] start with known num of Pdivs.*/
do k=3 for x%2-3 by 1+odd while k<y /*for odd numbers, skip evens.*/
if x//k==0 then do; #= # + 2 /*if no remainder, then found a divisor*/
y= x % k /*bump # Pdivs, calculate limit Y. */
if k>=y then do; #= # - 1; leave; end /*limit?*/
end /* ___ */
else if k*k>x then leave /*only divide up to √ x */
end /*k*/ /* [↑] this form of DO loop is faster.*/
return #+1 /*bump "proper divisors" to "divisors".*/
Do i=60 by 20 While nn<N /* step through possible numbers by 20. */
d=nndivs(i)
If d>maxD Then Do /* found an anti-prime nn set new maxD */
maxD=d
nn=nn+1
Say center(nn,7) right(i,10) /* display the index and the anti-prime. */
End
End /*i*/
Exit /* stick a fork in it, we're all done. */
/*-----------------------------------------------------------------------------------*/
nndivs: Procedure /* compute the number of proper divisors */
Parse Arg x
If x<2 Then
Return 1
odd=x//2
n=1 /* 1 is a proper divisor */
Do j=2+odd by 1+odd While j*j<x /* test all possible integers */
/* up To but excluding sqrt(x) */
If x//j==0 Then /* j is a divisor,so is x%j */
n=n+2
End
If j*j==x Then /* If x is a square */
n=n+1 /* sqrt(x) is a proper divisor */
n=n+1 /* x is a proper divisor */
Return n

View file

@ -1 +1 @@
writeln map f{^2}, 1..10
writeln map fn{^2}, 1..10

View file

@ -1,4 +1,4 @@
val .xs = toString 5 ^ 4 ^ 3 ^ 2
val .xs = string 5 ^ 4 ^ 3 ^ 2
val .len = len .xs
writeln .len, " digits"

View file

@ -22,6 +22,6 @@ const proc: main is func
round(yCenter - radius * sin(theta)), white);
theta +:= delta;
end while;
DRAW_FLUSH;
flushGraphic;
ignore(getc(KEYBOARD));
end func;

View file

@ -0,0 +1,13 @@
import math
procedure main()
write("c1: ",(c1 := Complex(1.5,3)).toString())
write("c2: ",(c2 := Complex(1.5,1.5)).toString())
write("+: ",(c1+c2).toString())
write("-: ",(c1-c2).toString())
write("*: ",(c1*c2).toString())
write("/: ",(c1/c2).toString())
write("additive inverse: ",c1.addInverse().toString())
write("multiplicative inverse: ",c1.multInverse().toString())
write("conjugate of (4,-3i): ",Complex(4,-3).conjugate().toString())
end

View file

@ -0,0 +1,240 @@
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
template <class T>
class stack {
private:
vector<T> st;
T sentinel;
public:
stack() { sentinel = T(); }
bool empty() { return st.empty(); }
void push(T info) { st.push_back(info); }
T& top() {
if (!st.empty()) {
return st.back();
}
return sentinel;
}
T pop() {
T ret = top();
if (!st.empty()) st.pop_back();
return ret;
}
};
//determine associativity of operator, returns true if left, false if right
bool leftAssociate(char c) {
switch (c) {
case '^': return false;
case '*': return true;
case '/': return true;
case '%': return true;
case '+': return true;
case '-': return true;
default:
break;
}
return false;
}
//determins precedence level of operator
int precedence(char c) {
switch (c) {
case '^': return 7;
case '*': return 5;
case '/': return 5;
case '%': return 5;
case '+': return 3;
case '-': return 3;
default:
break;
}
return 0;
}
//converts infix expression string to postfix expression string
string shuntingYard(string expr) {
stack<char> ops;
string output;
for (char c : expr) {
if (c == '(') {
ops.push(c);
} else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%') {
if (precedence(c) < precedence(ops.top()) ||
(precedence(c) == precedence(ops.top()) && leftAssociate(c))) {
output.push_back(' ');
output.push_back(ops.pop());
output.push_back(' ');
ops.push(c);
} else {
ops.push(c);
output.push_back(' ');
}
} else if (c == ')') {
while (!ops.empty()) {
if (ops.top() != '(') {
output.push_back(ops.pop());
} else {
ops.pop();
break;
}
}
} else {
output.push_back(c);
}
}
while (!ops.empty())
if (ops.top() != '(')
output.push_back(ops.pop());
else ops.pop();
cout<<"Postfix: "<<output<<endl;
return output;
}
struct Token {
int type;
union {
double num;
char op;
};
Token(double n) : type(0), num(n) { }
Token(char c) : type(1), op(c) { }
};
//converts postfix expression string to vector of tokens
vector<Token> lex(string pfExpr) {
vector<Token> tokens;
for (int i = 0; i < pfExpr.size(); i++) {
char c = pfExpr[i];
if (isdigit(c)) {
string num;
do {
num.push_back(c);
c = pfExpr[++i];
} while (i < pfExpr.size() && isdigit(c));
tokens.push_back(Token(stof(num)));
i--;
continue;
} else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%') {
tokens.push_back(Token(c));
}
}
return tokens;
}
//structure used for nodes of expression tree
struct node {
Token token;
node* left;
node* right;
node(Token tok) : token(tok), left(nullptr), right(nullptr) { }
};
//builds expression tree from vector of tokens
node* buildTree(vector<Token> tokens) {
cout<<"Building Expression Tree: "<<endl;
stack<node*> sf;
for (int i = 0; i < tokens.size(); i++) {
Token c = tokens[i];
if (c.type == 1) {
node* x = new node(c);
x->right = sf.pop();
x->left = sf.pop();
sf.push(x);
cout<<"Push Operator Node: "<<sf.top()->token.op<<endl;
} else
if (c.type == 0) {
sf.push(new node(c));
cout<<"Push Value Node: "<<c.num<<endl;
continue;
}
}
return sf.top();
}
//evaluate expression tree, while anotating steps being performed.
int recd = 0;
double eval(node* x) {
recd++;
if (x == nullptr) {
recd--;
return 0;
}
if (x->token.type == 0) {
for (int i = 0; i < recd; i++) cout<<" ";
cout<<"Value Node: "<<x->token.num<<endl;
recd--;
return x->token.num;
}
if (x->token.type == 1) {
for (int i = 0; i < recd; i++) cout<<" ";
cout<<"Operator Node: "<<x->token.op<<endl;
double lhs = eval(x->left);
double rhs = eval(x->right);
for (int i = 0; i < recd; i++) cout<<" ";
cout<<lhs<<" "<<x->token.op<<" "<<rhs<<endl;
recd--;
switch (x->token.op) {
case '^': return pow(lhs, rhs);
case '*': return lhs*rhs;
case '/':
if (rhs == 0) {
cout<<"Error: divide by zero."<<endl;
} else
return lhs/rhs;
case '%':
return (int)lhs % (int)rhs;
case '+': return lhs+rhs;
case '-': return lhs-rhs;
default:
break;
}
}
return 0;
}
int main() {
string expr = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
cout<<eval(buildTree(lex(shuntingYard(expr))))<<endl;
return 0;
}
Output:
Postfix: 3 4 2 * 1 5 - 2 3^^/+
Building Expression Tree:
Push Value Node: 3
Push Value Node: 4
Push Value Node: 2
Push Operator Node: *
Push Value Node: 1
Push Value Node: 5
Push Operator Node: -
Push Value Node: 2
Push Value Node: 3
Push Operator Node: ^
Push Operator Node: ^
Push Operator Node: /
Push Operator Node: +
Operator Node: +
Value Node: 3
Operator Node: /
Operator Node: *
Value Node: 4
Value Node: 2
4 * 2
Operator Node: ^
Operator Node: -
Value Node: 1
Value Node: 5
1 - 5
Operator Node: ^
Value Node: 2
Value Node: 3
2 ^ 3
-4 ^ 8
8 / 65536
3 + 0.00012207
3.00012

View file

@ -0,0 +1,68 @@
include "cowgol.coh";
const MAX := 13000;
var divisorSum: uint16[MAX+1];
var divisorCount: uint8[MAX+1];
sub CalculateDivisorSums() is
MemZero(&divisorSum[0] as [uint8], @bytesof divisorSum);
MemZero(&divisorCount[0] as [uint8], @bytesof divisorCount);
var div: @indexof divisorSum := 1;
while div <= MAX loop
var num := div;
while num <= MAX loop
divisorSum[num] := divisorSum[num] + div;
divisorCount[num] := divisorCount[num] + 1;
num := num + div;
end loop;
div := div + 1;
end loop;
end sub;
sub NextArithmetic(n: uint16): (r: uint16) is
r := n + 1;
while divisorSum[r] % divisorCount[r] as uint16 != 0 loop
r := r + 1;
end loop;
end sub;
sub Composite(n: uint16): (r: uint8) is
r := 0;
if n>1 and divisorSum[n] != n+1 then
r := 1;
end if;
end sub;
var current: uint16 := 0;
var nth: uint16 := 0;
var composites: uint16 := 0;
CalculateDivisorSums();
print("First 100 arithmetic numbers:\n");
while nth < 10000 loop
current := NextArithmetic(current);
nth := nth + 1;
composites := composites + Composite(current) as uint16;
if nth <= 100 then
print_i16(current);
if nth % 5 == 0 then
print_nl();
else
print_char('\t');
end if;
end if;
if nth == 1000 or nth == 10000 then
print_nl();
print_i16(nth);
print(": ");
print_i16(current);
print("\t");
print_i16(composites);
print(" composites\n");
end if;
end loop;

View file

@ -0,0 +1,65 @@
MODULE ArithmeticNumbers;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
CONST
Max = 13000;
VAR
divSum: ARRAY [1..Max] OF CARDINAL;
divCount: ARRAY [1..Max] OF CHAR;
current, count, composites: CARDINAL;
PROCEDURE CalculateDivisorSums;
VAR div, num: CARDINAL;
BEGIN
FOR num := 1 TO Max DO
divSum[num] := 0;
divCount[num] := CHR(0)
END;
FOR div := 1 TO Max DO
num := div;
WHILE num <= Max DO
INC(divSum[num], div);
INC(divCount[num]);
INC(num, div)
END
END
END CalculateDivisorSums;
PROCEDURE Next(n: CARDINAL): CARDINAL;
BEGIN
REPEAT INC(n) UNTIL (divSum[n] MOD ORD(divCount[n])) = 0;
RETURN n
END Next;
PROCEDURE Composite(n: CARDINAL): BOOLEAN;
BEGIN
RETURN (n>1) AND (divSum[n] # n+1)
END Composite;
BEGIN
CalculateDivisorSums;
WriteString("First 100 arithmetic numbers:");
WriteLn;
current := 0;
FOR count := 1 TO 10000 DO
current := Next(current);
IF Composite(current) THEN INC(composites) END;
IF count <= 100 THEN
WriteCard(current, 5);
IF count MOD 10 = 0 THEN WriteLn END
END;
IF (count = 1000) OR (count = 10000) THEN
WriteCard(count, 5);
WriteString(": ");
WriteCard(current, 5);
WriteString(", ");
WriteCard(composites, 5);
WriteString(" composites");
WriteLn
END;
END
END ArithmeticNumbers.

View file

@ -0,0 +1 @@
(length [:apple :orange])

View file

@ -0,0 +1,37 @@
func average n reps .
for r to reps
f[] = [ ]
for i to n
f[] &= randint n
.
seen[] = [ ]
len seen[] n
x = 1
while seen[x] = 0
seen[x] = 1
x = f[x]
count += 1
.
.
return count / reps
.
func analytical n .
s = 1
t = 1
for i = n - 1 downto 1
t = t * i / n
s += t
.
return s
.
print " N average analytical (error)"
print "=== ======= ========== ======="
for n to 20
avg = average n 1e6
ana = analytical n
err = (avg - ana) / ana * 100
numfmt 0 2
write n
numfmt 4 9
print avg & ana & err & "%"
.

View file

@ -1,4 +1,4 @@
val .mean = f(.x) fold(f{+}, .x) / len(.x)
val .mean = fn(.x) fold(fn{+}, .x) / len(.x)
writeln " custom: ", .mean([7, 3, 12])
writeln "built-in: ", mean([7, 3, 12])

View file

@ -1,33 +1,14 @@
using System;
using System.Linq;
namespace Test
double median(double[] arr)
{
class Program
{
static void Main()
{
double[] myArr = new double[] { 1, 5, 3, 6, 4, 2 };
myArr = myArr.OrderBy(i => i).ToArray();
// or Array.Sort(myArr) for in-place sort
int mid = myArr.Length / 2;
double median;
if (myArr.Length % 2 == 0)
{
//we know its even
median = (myArr[mid] + myArr[mid - 1]) / 2.0;
}
else
{
//we know its odd
median = myArr[mid];
}
Console.WriteLine(median);
Console.ReadLine();
}
}
var sorted = arr.OrderBy(x => x).ToList();
var mid = arr.Length / 2;
return arr.Length % 2 == 0
? (sorted[mid] + sorted[mid-1]) / 2
: sorted[mid];
}
var write = (double[] x) =>
Console.WriteLine($"[{string.Join(", ", x)}]: {median(x)}");
write(new double[] { 1, 5, 3, 6, 4, 2 }); //even
write(new double[] { 1, 5, 3, 6, 4, 2, 7 }); //odd
write(new double[] { 5 }); //single

View file

@ -1,12 +0,0 @@
10 print "calculating..."
20 let n = 2
30 rem do
40 let n = n + 2
50 if (n ^ 2) % 1000000 <> 269696 then 30
60 print "The smallest number whose square ends in 269696 is: ", n
70 print "It's square is ", n * n

View file

@ -9,7 +9,7 @@ T BalancedTernary
I all(inp.map(d -> d C (0, 1, -1)))
.digits = copy(inp)
E
X ValueError(BalancedTernary: Wrong input digits.)
X.throw ValueError(BalancedTernary: Wrong input digits.)
F :from_str(inp)
R BalancedTernary(reversed(inp).map(c -> .:str2dig[c]))
@ -21,7 +21,7 @@ T BalancedTernary
I n3 == 0 {R [0] [+] .:int2ternary(n -I/ 3)}
I n3 == 1 {R [1] [+] .:int2ternary(n -I/ 3)}
I n3 == 2 {R [-1] [+] .:int2ternary((n + 1) -I/ 3)}
X RuntimeError()
X.throw RuntimeError()
F :from_int(inp)
R BalancedTernary(.:int2ternary(inp))

View file

@ -0,0 +1,137 @@
### Generic utilities
# Emit a stream of the constituent characters of the input string
def chars: explode[] | [.] | implode;
# Flip "+" and "-" in the input string, and change other characters to 0
def flip:
{"+": "-", "-": "+"} as $t
| reduce chars as $c (""; . + ($t[$c] // "0") );
### Balanced ternaries (BT)
# Input is assumed to be an integer (use `new` if checking is required)
def toBT:
# Helper - input should be an integer
def mod3:
if . > 0 then . % 3
else ((. % 3) + 3) % 3
end;
if . < 0 then - . | toBT | flip
else if . == 0 then ""
else mod3 as $rem
| if $rem == 0 then (. / 3 | toBT) + "0"
elif $rem == 1 then (. / 3 | toBT) + "+"
else ((. + 1) / 3 | toBT) + "-"
end
end
| sub("^00*";"")
| if . == "" then "0" end
end ;
# Input: BT
def integer:
. as $in
| length as $len
| { sum: 0,
pow: 1 }
| reduce range (0;$len) as $i (.;
$in[$len-$i-1: $len-$i] as $c
| (if $c == "+" then 1 elif $c == "-" then -1 else 0 end) as $digit
| if $digit != 0 then .sum += $digit * .pow else . end
| .pow *= 3 )
| .sum ;
# If the input is a string, check it is a valid BT, and trim leading 0s;
# if the input is an integer, convert it to a BT;
# otherwise raise an error.
def new:
if type == "string" and all(chars; IN("0", "+", "-"))
then sub("^00*"; "") | if . == "" then "0" end
elif type == "number" and trunc == .
then toBT
else "'new' given invalid input: \(.)" | error
end;
# . + $b
def plus($b):
# Helper functions:
def at($i): .[$i:$i+1];
# $a and $b should each be "0", "+" or "-"
def addDigits2($a; $b):
if $a == "0" then $b
elif $b == "0" then $a
elif $a == "+"
then if $b == "+" then "+-" else "0" end
elif $b == "+" then "0" else "-+"
end;
def addDigits3($a; $b; $carry):
addDigits2($a; $b) as $sum1
| addDigits2($sum1[-1:]; $carry) as $sum2
| if ($sum1|length) == 1
then $sum2
elif ($sum2|length) == 1
then $sum1[0:1] + $sum2
else $sum1[0:1]
end;
{ longer: (if length > ($b|length) then . else $b end),
shorter: (if length > ($b|length) then $b else . end) }
| until ( (.shorter|length) >= (.longer|length); .shorter = "0" + .shorter )
| .a = .longer
| .b = .shorter
| .carry = "0"
| .sum = ""
| reduce range(0; .a|length) as $i (.;
( (.a|length) - $i - 1) as $place
| addDigits3(.a | at($place); .b | at($place); .carry) as $digisum
| .carry = (if ($digisum|length) != 1 then $digisum[0:1] else "0" end)
| .sum = $digisum[-1:] + .sum )
| .carry + .sum
| new;
def minus: flip;
# . - $b
def minus($b): plus($b | flip);
def mult($b):
(1 | new) as $one
| (0 | new) as $zero
| { a: .,
$b,
mul: $zero,
flipFlag: false }
| if .b[0:1] == "-" # i.e. .b < 0
then .b |= minus
| .flipFlag = true
end
| .i = $one
| .in = 1
| (.b | integer) as $bn
| until ( .in > $bn;
.a as $a
| .mul |= plus($a)
| .i |= plus($one)
| .in += 1 )
| if .flipFlag then .mul | minus else .mul end ;
### Illustration
def a: "+-0++0+";
def b: -436 | new;
def c: "+-++-";
(a | integer) as $an
| (b | integer) as $bn
| (c | integer) as $cn
| ($an * ($bn - $cn)) as $in
| (a | mult( (b | minus(c)))) as $i
| "a = \($an)",
"b = \($bn)",
"c = \($cn)",
"a * (b - c) = \($i) ~ \($in) => \($in|new)"

View file

@ -0,0 +1,18 @@
begin % show some Bell numbers %
integer MAX_BELL;
MAX_BELL := 15;
begin
procedure showBell ( integer value n, bellNumber ) ;
write( i_w := 2, s_w := 0, n, ": ", i_w := 1, bellNumber );
integer array a ( 0 :: MAX_BELL - 2 );
for i := 1 until MAX_BELL - 2 do a( i ) := 0;
a( 0 ) := 1;
showBell( 1, a( 0 ) );
for n := 0 until MAX_BELL - 2 do begin
% replace a with the next line of the triangle %
a( n ) := a( 0 );
for j := n step -1 until 1 do a( j - 1 ) := a( j - 1 ) + a( j );
showBell( n + 2, a( 0 ) )
end for_n
end
end.

View file

@ -0,0 +1,10 @@
task{
benf ÷(9)(+/.=)()¨
fibs (,(+/¯2))9981 1
exp 101+÷9
obs benf fibs
'Expected Actual'5exp,[1.5]obs
}

View file

@ -0,0 +1,38 @@
100 cls
110 n = 1000
120 dim actual(n)
130 for nr = 1 to n
140 num$ = str$(fibonacci(nr))
150 j = val(left$(num$,1))
160 actual(j) = actual(j)+1
170 next
180 print "First 1000 Fibonacci numbers"
190 print "Digit Actual freq Expected freq"
200 for i = 1 to 9
210 freq = frequency(i)*100
220 print format$(i,"###");
230 print using " ##.###";actual(i)/10;
240 print using " ##.###";freq
250 next
260 end
270 sub frequency(n)
280 frequency = (log10(n+1)-log10(n))
290 end sub
300 sub log10(n)
310 log10 = log(n)/log(10)
320 end sub
330 sub fibonacci(n)
335 rem https://rosettacode.org/wiki/Fibonacci_sequence#Chipmunk_Basic
340 n1 = 0
350 n2 = 1
360 for k = 1 to abs(n)
370 sum = n1+n2
380 n1 = n2
390 n2 = sum
400 next k
410 if n < 0 then
420 fibonacci = n1*((-1)^((-n)+1))
430 else
440 fibonacci = n1
450 endif
460 end sub

View file

@ -0,0 +1,31 @@
program benfords_law;
fibos := fibo_list(1000);
expected := [log(1 + 1/d)/log 10 : d in [1..9]];
actual := benford(fibos);
print('d Expected Actual');
loop for d in [1..9] do
print(d, ' ', fixed(expected(d), 7, 5), ' ', fixed(actual(d), 7, 5));
end loop;
proc benford(list);
dist := [];
loop for n in list do
dist(val(str n)(1)) +:= 1;
end loop;
return [d / #list : d in dist];
end proc;
proc fibo_list(n);
a := 1;
b := 1;
fibs := [];
loop while n>0 do
fibs with:= a;
[a, b] := [b, a+b];
n -:= 1;
end loop;
return fibs;
end proc;
end program;

View file

@ -0,0 +1,38 @@
FUNCTION log10(n)
LET log10 = LOG(n)/LOG(10)
END FUNCTION
FUNCTION frequency(n)
LET frequency = (log10(n+1)-log10(n))
END FUNCTION
FUNCTION fibonacci(n)
!https://rosettacode.org/wiki/Fibonacci_sequence#True_BASIC
LET n1 = 0
LET n2 = 1
FOR k = 1 TO ABS(n)
LET sum = n1+n2
LET n1 = n2
LET n2 = sum
NEXT k
IF n < 0 THEN LET fibonacci = n1*((-1)^((-n)+1)) ELSE LET fibonacci = n1
END FUNCTION
CLEAR
LET n = 1000
DIM actual(0)
MAT REDIM actual(n)
FOR nr = 1 TO n
LET num$ = STR$(fibonacci(nr))
LET j = VAL((num$)[1:1])
LET actual(j) = actual(j)+1
NEXT nr
PRINT "First 1000 Fibonacci numbers"
PRINT "Digit Actual freq Expected freq"
FOR i = 1 TO 9
LET freq = frequency(i)*100
PRINT USING "###": i;
PRINT USING " ##.###": actual(i)/10;
PRINT USING " ##.###": freq
NEXT i
END

View file

@ -0,0 +1,39 @@
proc best_shuffle s$ . r$ diff .
l = len s$
for c$ in strchars s$
s[] &= strcode c$
.
len cnt[] 128
for i to l
cnt[s[i]] += 1
max = higher max cnt[s[i]]
.
for i to 128
while cnt[i] > 0
cnt[i] -= 1
buf[] &= i
.
.
r[] = s[]
for i to l
for j to l
if r[i] = buf[j]
r[i] = buf[(j + max) mod1 l] mod 128
if buf[j] <= 128
buf[j] += 128
.
break 1
.
.
.
diff = 0
r$ = ""
for i to l
diff += if r[i] = s[i]
r$ &= strchar r[i]
.
.
for s$ in [ "abracadabra" "seesaw" "elk" "grrrrrr" "up" "a" ]
best_shuffle s$ r$ d
print s$ & " " & r$ & " " & d
.

View file

@ -1,30 +1,24 @@
func$ crypt enc msg$ key$ .
key$[] = strchars key$
n = len msg$
for i to len msg$
c$ = substr msg$ i 1
for j to 25
if c$ = key$[j]
break 1
.
.
j -= 1
j = strpos key$ c$ - 1
h[] &= j div 5
h[] &= j mod 5
.
if enc = 1
for i = 1 step 4 to 2 * n - 3
j = h[i] * 5 + h[i + 2] + 1
r$ &= key$[j]
r$ &= substr key$ j 1
.
for i = 2 step 4 to 2 * n - 2
j = h[i] * 5 + h[i + 2] + 1
r$ &= key$[j]
r$ &= substr key$ j 1
.
else
for i = 1 to n
j = h[i] * 5 + h[i + n] + 1
r$ &= key$[j]
r$ &= substr key$ j 1
.
.
return r$

View file

@ -1,42 +1,67 @@
/*REXX program counts how many numbers of a set that fall in the range of each bin. */
lims= 23 37 43 53 67 83 /* ◄■■■■■■1st set of bin limits & data.*/
data= 95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47 ,
/*REXX program counts how many numbers of a set that fall in the range of each bin. */
lims= 23 37 43 53 67 83 /* <----- 1st set of bin limits & data.*/
data= 95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47,
16 8 9 32 84 7 87 46 19 30 37 96 6 98 40 79 97 45 64 60 29 49 36 43 55
call lims lims; call bins data
call limits lims
call bins data
call show 'the 1st set of bin counts for the specified data:'
say; say; say
lims= 14 18 249 312 389 392 513 591 634 720 /* ◄■■■■■■2nd set of bin limits & data.*/
data= 445 814 519 697 700 130 255 889 481 122 932 77 323 525 570 219 367 523 442 933 ,
416 589 930 373 202 253 775 47 731 685 293 126 133 450 545 100 741 583 763 306 ,
655 267 248 477 549 238 62 678 98 534 622 907 406 714 184 391 913 42 560 247 ,
346 860 56 138 546 38 985 948 58 213 799 319 390 634 458 945 733 507 916 123 ,
345 110 720 917 313 845 426 9 457 628 410 723 354 895 881 953 677 137 397 97 ,
854 740 83 216 421 94 517 479 292 963 376 981 480 39 257 272 157 5 316 395 ,
787 942 456 242 759 898 576 67 298 425 894 435 831 241 989 614 987 770 384 692 ,
698 765 331 487 251 600 879 342 982 527 736 795 585 40 54 901 408 359 577 237 ,
605 847 353 968 832 205 838 427 876 959 686 646 835 127 621 892 443 198 988 791 ,
Do 3; say''; End
lims= 14 18 249 312 389 392 513 591 634 720 /* <-----2nd set of bin limits & data.*/
data= 445 814 519 697 700 130 255 889 481 122 932 77 323 525 570 219 367 523 442 933,
416 589 930 373 202 253 775 47 731 685 293 126 133 450 545 100 741 583 763 306,
655 267 248 477 549 238 62 678 98 534 622 907 406 714 184 391 913 42 560 247,
346 860 56 138 546 38 985 948 58 213 799 319 390 634 458 945 733 507 916 123,
345 110 720 917 313 845 426 9 457 628 410 723 354 895 881 953 677 137 397 97,
854 740 83 216 421 94 517 479 292 963 376 981 480 39 257 272 157 5 316 395,
787 942 456 242 759 898 576 67 298 425 894 435 831 241 989 614 987 770 384 692,
698 765 331 487 251 600 879 342 982 527 736 795 585 40 54 901 408 359 577 237,
605 847 353 968 832 205 838 427 876 959 686 646 835 127 621 892 443 198 988 791,
466 23 707 467 33 670 921 180 991 396 160 436 717 918 8 374 101 684 727 749
call lims lims; call bins data
call limits lims
call bins data
call show 'the 2nd set of bin counts for the specified data:'
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bins: parse arg nums; !.= 0; datum= words(nums); wc= length(datum) /*max width count.*/
do j=1 for datum; x= word(nums, j)
do k=0 for # /*find the bin that this number is in. */
if x < @.k then do; !.k= !.k + 1; iterate j; end /*bump a bin count*/
end /*k*/
!.k= !.k + 1 /*number is > the highest bin specified*/
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
lims: parse arg limList; #= words(limList); wb= 0 /*max width binLim*/
do j=1 for #; _= j - 1; @._= word(limList, j); wb= max(wb, length(@._) )
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg t; say center(t, 51 ); $= left('', 9) /*$: for indentation*/
say center('', 51, "") /*show title separator.*/
jp= # - 1; ge= ''; le='<'; eq= ' count='
do j=0 for #; jm= j - 1; bin= right(@.j, wb)
if j==0 then say $ left('', length(ge) +3+wb+length(..) )le bin eq right(!.j, wc)
else say $ ge right(@.jm, wb) .. le bin eq right(!.j, wc)
if j==jp then say $ ge right(@.jp,wb) left('', 3+length(..)+wb) eq right(!.#, wc)
end /*j*/; return
exit 0
/*------------------------------------------------------------------------------*/
bins:
Parse Arg numbers
count.=0
Do j=1 To words(numbers)
x=word(numbers,j)
Do k=1 To bins-1 Until x<limit.k /* determine which bin is to be used */
End
count.k=count.k+1 /* increment count for this bin */
End
count_length=0 /* compute the length of the largest count */
Do k=0 To bins
count_length=max(count_length,length(count.k))
End
Return
/*------------------------------------------------------------------------------*/
limits:
Parse Arg limlist
limit_length=0
bins=words(limlist)+1 /* number of bins */
limit.=''
Do j=1 To bins-1
limit.j=word(limlist,j) /* lower limit of bin j */
limit_length=max(limit_length,length(limit.j)) /* length of largest limit */
End
Return
/*------------------------------------------------------------------------------*/
show:
Say arg(1)
Say copies('-',51)
ll=limit_length
do k=1 To bins
km1=k-1
Select
When k=1 Then
range=' ' right('' ,ll) ' <' right(limit.k,ll)
When k<bins Then
range='>=' right(limit.km1,ll) '.. <' right(limit.k,ll)
Otherwise
range='>=' right(limit.km1,ll) ' ' right('' ,ll)
End
Say ' 'range ' count=' right(count.k,count_length)
End
Return

View file

@ -0,0 +1,103 @@
### Generic utilities
# Output: a PRN in range(0; .)
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
# bag of words
def bow(stream):
reduce stream as $word ({}; .[($word|tostring)] += 1);
# Emit a stream of the constituent characters of the input string
def chars: explode[] | [.] | implode;
def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .;
# Print $n-character segments at a time, each prefixed by a 1-based index
def pretty_nwise($n):
(length | tostring | length) as $len
| def _n($i):
if length == 0 then empty
else "\($i|lpad($len)): \(.[:$n])",
(.[$n:] | _n($i+$n))
end;
_n(1);
### Biology
def bases: ["A", "C", "G", "T"];
def randomBase:
bases | .[length|prn];
# $w is an array [weightSwap, weightDelete, weightInsert]
# specifying the weights out of 300 for each of swap, delete and insert
# Input: an object {dna}
# Output: an object {dna, message}
def mutate($w):
def removeAt($p): .[:$p] + .[$p+1:];
(.dna|length) as $le
# get a random position in the dna to mutate
| ($le | prn) as $p
# get a random number between 0 and 299 inclusive
| (300 | prn) as $r
| .dna |= [chars]
| if $r < $w[0]
then # swap
randomBase as $base
| .message = " Change @\($p) \(.dna[$p]) to \($base)"
| .dna[$p] = $base
elif $r < $w[0] + $w[1]
then # delete
.message = " Delete @\($p) \(.dna[$p])"
| .dna |= removeAt($p)
else # insert
randomBase as $base
| .message = " Insert @\($p) \($base)"
| .dna |= .[:$p] + [$base] + .[$p:]
end
| .dna |= join("") ;
# Generate a random dna sequence of given length:
def generate($n):
[range(0; $n) | randomBase] | join("");
# Pretty print dna and stats.
def prettyPrint($rowLen):
"SEQUENCE:", pretty_nwise($rowLen),
( bow(chars) as $baseMap
| "\nBASE COUNT:",
( bases[] as $c | " \($c): \($baseMap[$c] // 0)" ),
" ------",
" Σ: \(length)",
" ======\n"
) ;
# For displaying the weights
def pretty_weights:
" Change: \(.[0])\n Delete: \(.[1])\n Insert: \(.[2])";
# Arguments are length, weights, mutations
def task($n; $w; $muts ):
generate($n)
| . as $dna
| prettyPrint(50),
"\nWEIGHTS (0 .. 300):", ($w|pretty_weights),
"\nMUTATIONS (\($muts)):",
(reduce range(0;$muts) as $i ({$dna};
mutate($w)
| .emit += [.message] )
| (.emit | join("\n")),
"",
(.dna | prettyPrint(50)) ) ;
task(250; # length
[100, 100, 100]; # use e.g. [0, 300, 0] to choose only deletions
10 # mutations
)

View file

@ -0,0 +1,46 @@
birth$ = "1943-03-09"
date$ = "1972-07-11"
# date$ = substr timestr systime 1 10
#
func day d$ .
y = number substr d$ 1 4
m = number substr d$ 6 2
d = number substr d$ 9 2
return 367 * y - 7 * (y + (m + 9) div 12) div 4 + 275 * m div 9 + d - 730530
.
textsize 4
func init b$ d$ .
linewidth 0.2
move 50 0
line 50 100
move 0 50
line 100 50
for d = -20 to 20
move x 50
circle 0.5
x += 2.5
.
move 4 94
text b$
move 4 88
text d$
days = day date$ - day birth$
move 4 80
text days & " days"
return days
.
proc cycle now cyc t$ col . .
color col
move 4 cyc * 1.2 - 20
text t$
linewidth 0.5
for d = now - 20 to now + 20
p = 20 * sin (360 * d / cyc)
line x 50 + p
x += 2.5
.
.
days = init birth$ date$
cycle days 23 "Physical" 900
cycle days 28 "Emotional" 090
cycle days 33 "Intellectual" 009

View file

@ -65,4 +65,4 @@ bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
print(bitmap.writeppmp3())
File(tmp.ppm, w).write_bytes(bitmap.writeppmp6())
File(tmp.ppm, WRITE).write_bytes(bitmap.writeppmp6())

View file

@ -1,10 +1,10 @@
T BitWriter
File out
FileWr out
accumulator = 0
bcount = 0
F (fname)
.out = File(fname, w)
.out = File(fname, WRITE)
F _writebit(bit)
I .bcount == 8
@ -34,11 +34,11 @@ T BitReader
read = 0
F (fname)
.input = File(fname, r)
.input = File(fname)
F _readbit()
I .bcount == 0
V a = .input.read_bytes(1)
V a = .input.read_bytes(at_most' 1)
I !a.empty
.accumulator = a[0]
.bcount = 8

View file

@ -0,0 +1,112 @@
Type BitFilter
nombre As String
accu As Integer
bits As Integer
bw As Integer
br As Integer
offset As Integer
End Type
Sub openWriter(bf As BitFilter)
bf.bw = Freefile
Open bf.nombre For Binary Access Write As #bf.bw
End Sub
Sub openReader(bf As BitFilter)
bf.br = Freefile
Open bf.nombre For Binary Access Read As #bf.br
bf.offset = 0
End Sub
Sub escribe(bf As BitFilter, buf() As Byte, start As Integer, nBits As Integer, shift As Integer)
Dim As Integer index = start + (shift \ 8)
shift Mod= 8
While nBits <> 0 Or bf.bits >= 8
While bf.bits >= 8
bf.bits -= 8
Dim As Byte outByte = ((bf.accu Shr bf.bits) And &hFF)
Put #bf.bw, , outByte
Wend
While bf.bits < 8 And nBits <> 0
Dim As Byte b = buf(index)
bf.accu = (bf.accu Shl 1) Or (((128 Shr shift) And b) Shr (7 - shift))
nBits -= 1
bf.bits += 1
shift += 1
If shift = 8 Then
shift = 0
index += 1
End If
Wend
Wend
End Sub
Sub lee(bf As BitFilter, buf() As Byte, start As Integer, nBits As Integer, shift As Integer)
Dim As Integer index = start + (shift \ 8)
shift Mod= 8
While nBits <> 0
While bf.bits <> 0 And nBits <> 0
Dim As Byte mask = 128 Shr shift
buf(index) = Iif((bf.accu And (1 Shl (bf.bits - 1))) <> 0, (buf(index) Or mask) And &hFF, (buf(index) And Not mask) And &hFF)
nBits -= 1
bf.bits -= 1
shift += 1
If shift >= 8 Then
shift = 0
index += 1
End If
Wend
If nBits = 0 Then Exit Sub
Dim As Byte inByte
Get #bf.br, bf.offset + 1, inByte
bf.accu = (bf.accu Shl 8) Or inByte
bf.bits += 8
bf.offset += 1
Wend
End Sub
Sub closeWriter(bf As BitFilter)
If bf.bits <> 0 Then
bf.accu Shl= (8 - bf.bits)
Dim As Byte outByte = (bf.accu And &hFF)
Put #bf.bw, , outByte
End If
Close #bf.bw
bf.accu = 0
bf.bits = 0
End Sub
Sub closeReader(bf As BitFilter)
Close #bf.br
bf.accu = 0
bf.bits = 0
bf.offset = 0
End Sub
Dim As Integer i
Dim As BitFilter bf
bf.nombre = "test.bin"
' for each byte in s, write 7 bits skipping 1
Dim As Byte s(10) => {Asc("a"), Asc("b"), Asc("c"), Asc("d"), _
Asc("e"), Asc("f"), Asc("g"), Asc("h"), Asc("i"), Asc("j"), Asc("k")}
openWriter(bf)
For i = 0 To Ubound(s)
escribe(bf, s(), i, 7, 1)
Next i
closeWriter(bf)
' read 7 bits and expand to each byte of s2 skipping 1 bit
openReader(bf)
Dim As Byte s2(0 To Ubound(s)) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
For i = 0 To Ubound(s2)
lee(bf, s2(), i, 7, 1)
Next i
closeReader(bf)
For i = 0 To Ubound(s2)
Print Chr(s2(i));
Next i
Print
Sleep

View file

@ -23,23 +23,19 @@ const proc: writeAscii (inout file: outFile, inout integer: bitPos, in string: a
const proc: finishWriteAscii (inout file: outFile, inout integer: bitPos) is func
begin
putBitsMsb(outFile, bitPos, 0, 7); # Write a terminating NUL char.
write(outFile, chr(ord(outFile.bufferChar)));
end func;
const proc: initReadAscii (inout file: outFile, inout integer: bitPos) is func
begin
bitPos := 8;
end func;
const func string: readAscii (inout file: inFile, inout integer: bitPos, in integer: length) is func
const func string: readAscii (inout msbBitStream: aBitStream) is func
result
var string: stri is "";
local
var char: ch is ' ';
begin
while not eof(inFile) and length(stri) < length do
ch := chr(getBitsMsb(inFile, bitPos, 7));
if inFile.bufferChar <> EOF then
while ch <> '\0;' do
ch := chr(getBits(aBitStream, 7));
if ch <> '\0;' then
stri &:= ch;
end if;
end while;
@ -49,12 +45,13 @@ const proc: main is func
local
var file: aFile is STD_NULL;
var integer: bitPos is 0;
var msbBitStream: aBitStream is msbBitStream.value;
begin
aFile := openStrifile;
aFile := openStriFile;
initWriteAscii(aFile, bitPos);
writeAscii(aFile, bitPos, "Hello, Rosetta Code!");
finishWriteAscii(aFile, bitPos);
seek(aFile, 1);
initReadAscii(aFile, bitPos);
writeln(literal(readAscii(aFile, bitPos, 100)));
aBitStream := openMsbBitStream(aFile);
writeln(literal(readAscii(aBitStream)));
end func;

View file

@ -0,0 +1,70 @@
ClearAll[BlumIntegerQ, BlumIntegersInRange, PrimePi2, BlumCount, binarySearch, BlumInts, timing, upperLimitEstimate, lastDigit, lastDigitDistributionPercents];
BlumIntegerQ[n_Integer] := With[{factors = FactorInteger[n]},
n ~ Mod ~ 4 == 1 &&
Length[factors] == 2 &&
factors[[1, 1]] ~ Mod ~ 4 == 3 &&
Last@Total@factors == 2
];
SetAttributes[BlumIntegerQ, Listable];
BlumIntegersInRange[n_Integer] := BlumIntegersInRange[1, n];
BlumIntegersInRange[start_Integer, end_Integer] :=
Select[Range[start + (4 - start) ~ Mod ~ 4, end, 4] + 1, BlumIntegerQ];
(* Counts semiprimes. See https://people.maths.ox.ac.uk/erban/papers/paperDCRE.pdf *)
PrimePi2[x_] := (PrimePi[Sqrt[x]] - PrimePi[Sqrt[x]]^2)/2 + Sum[PrimePi[x/Prime[p]], {p, 1, PrimePi[Sqrt[x]]}];
SetAttributes[PrimePi2, Listable];
(* Blum integers are semiprimes that are 1 mod 4, with two distinct factors where both factors are 3 mod 4. The following function gives an approximation of the number of Blum integers <= x.
According to my tests, this function tends to overestimate by approximately 5% in the range we're interested in.
*)
BlumCount[x_] := Ceiling[(PrimePi2[x] - PrimePi[Sqrt[x]]) / 4];
SetAttributes[BlumCount, Listable];
binarySearch[f_, targetValue_] :=
Module[{lo = 1, mid, hi = 1, currentValue},
While[f[hi] < targetValue,
hi *= 2;];
While[lo <= hi,
mid = Ceiling[(lo + hi) / 2];
currentValue = f[mid];
If[currentValue < targetValue,
lo = mid + 1;];
If[currentValue > targetValue,
hi = mid - 1;];
If[currentValue == targetValue,
While[f[mid] == targetValue,
mid++;
];
Return[mid - 1];
];
];
];
lastDigit[n_Integer] := n ~ Mod ~ 10;
SetAttributes[lastDigit, Listable];
upperLimitEstimate = Ceiling[binarySearch[BlumCount, 400000]* 1.1];
timing = First@AbsoluteTiming[BlumInts = BlumIntegersInRange[upperLimitEstimate];];
lastDigitDistributionPercents = N[Counts@lastDigit@BlumInts[[;; 400000]] / 4000, 5];
Print["Calculated the first ", Length[BlumInts],
" Blum integers in ", timing, " seconds."];
Print[];
Print["First 50 Blum integers:"];
Print[TableForm[Partition[BlumInts[[;; 50]], 10],
TableAlignments -> Right]];
Print[];
Print[Grid[
Table[{"The ", n , "th Blum integer is: ",
BlumInts[[n]]}, {n, {26828, 100000, 200000, 300000, 400000}}] ,
Alignment -> Right]]
Print[];
Print["% distribution of the first 400,000 Blum integers:"];
Print[Grid[
Table[{lastDigitDistributionPercents[n], "% end in ",
n}, {n, {1, 3, 7, 9}} ], Alignment -> Right]];

View file

@ -1,59 +1,57 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">LIMIT</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1e7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">N</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">LIMIT</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span>
with javascript_semantics
constant LIMIT = 1e7, N = floor((floor(LIMIT/3)-1)/4)+1
<span style="color: #008080;">function</span> <span style="color: #000000;">Sieve4n_3_Primes</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sieve</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">N</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">p4n3</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">*</span><span style="color: #000000;">4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<span style="color: #000000;">p4n3</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">N</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">// collect the rest</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sieve</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">p4n3</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">*</span><span style="color: #000000;">j</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</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;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span> <span style="color: #008080;">to</span> <span style="color: #000000;">N</span> <span style="color: #008080;">by</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">sieve</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;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">p4n3</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function Sieve4n_3_Primes()
sequence sieve = repeat(0,N), p4n3 = {}
for idx=1 to N do
if sieve[idx]=0 then
integer n = idx*4-1
p4n3 &= n
if idx+n>N then
// collect the rest
for j=idx+1 to N do
if sieve[j]=0 then
p4n3 &= 4*j-1
end if
end for
exit
end if
for j=idx+n to N by n do
sieve[j] = 1
end for
end if
end for
return p4n3
end function
<span style="color: #004080;">sequence</span> <span style="color: #000000;">p4n3</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">Sieve4n_3_Primes</span><span style="color: #0000FF;">(),</span>
<span style="color: #000000;">BlumField</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #000000;">LIMIT</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">Blum50</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span> <span style="color: #000000;">counts</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
sequence p4n3 = Sieve4n_3_Primes(),
BlumField = repeat(false,LIMIT),
Blum50 = {}, counts = repeat(0,10)
<span style="color: #008080;">for</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span> <span style="color: #008080;">in</span> <span style="color: #000000;">p4n3</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">bj</span> <span style="color: #008080;">in</span> <span style="color: #000000;">p4n3</span> <span style="color: #008080;">from</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">*</span><span style="color: #000000;">bj</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">></span><span style="color: #000000;">LIMIT</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">BlumField</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: #004600;">true</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: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span> <span style="color: #008080;">in</span> <span style="color: #000000;">BlumField</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">k</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;"><</span><span style="color: #000000;">50</span> <span style="color: #008080;">then</span> <span style="color: #000000;">Blum50</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">counts</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">50</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;">"First 50 Blum integers:\n%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join_by</span><span style="color: #0000FF;">(</span><span style="color: #000000;">Blum50</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: #008000;">" "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">:=</span><span style="color: #008000;">"%3d"</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">26828</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e5</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</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;">"The %,7d%s Blum integer is: %,9d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">ord</span><span style="color: #0000FF;">(</span><span style="color: #000000;">count</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4e5</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</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: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nPercentage distribution of the first 400,000 Blum integers:\n"</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;">n</span> <span style="color: #008080;">in</span> <span style="color: #000000;">counts</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</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;">" %6.3f%% end in %d\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">4000</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>
<!--
for idx,n in p4n3 do
for bj in p4n3 from idx+1 do
atom k = n*bj
if k>LIMIT then exit end if
BlumField[k] = true
end for
end for
integer count = 0
for n,k in BlumField do
if k then
if count<50 then Blum50 &= n end if
counts[remainder(n,10)] += 1
count += 1
if count=50 then
printf(1,"First 50 Blum integers:\n%s\n",{join_by(Blum50,1,10," ",fmt:="%3d")})
elsif count=26828 or remainder(count,1e5)=0 then
printf(1,"The %,7d%s Blum integer is: %,9d\n", {count,ord(count),n})
if count=4e5 then exit end if
end if
end if
end for
printf(1,"\nPercentage distribution of the first 400,000 Blum integers:\n")
for i,n in counts do
if n then
printf(1," %6.3f%% end in %d\n", {n/4000, i})
end if
end for

View file

@ -17,6 +17,6 @@ writeln "index degrees compass point"
writeln "----- ------- -------------"
for .phi in .angles {
val .i = trunc(.phi x 32 / 360 + 0.5) rem 32 + 1
val .i = trunc(.phi * 32 / 360 + 0.5) rem 32 + 1
writeln $"\{.i:5} \{.phi:r2:6} \{.box[.i]}"
}

View file

@ -0,0 +1,56 @@
fastfunc factor num .
if num mod 2 = 0
if num = 2
return 1
.
return 2
.
i = 3
while i <= sqrt num
if num mod i = 0
return i
.
i += 2
.
return 1
.
func brilliant n .
f1 = factor n
if f1 = 1
return 0
.
f2 = n div f1
if floor log10 f1 <> floor log10 f2
return 0
.
if factor f1 = 1 and factor f2 = 1
return 1
.
return 0
.
proc main . .
i = 2
while cnt < 100
if brilliant i = 1
cnt += 1
write i & " "
.
i += 1
.
print "\n"
i = 2
cnt = 0
mag = 1
repeat
if brilliant i = 1
cnt += 1
if i >= mag
print i & " (" & cnt & ")"
mag *= 10
.
.
until mag = 10000000
i += 1
.
.
main

View file

@ -34,7 +34,7 @@ const proc: genBrownianTree (in integer: fieldSize, in integer: numParticles) is
# Bumped into something
world[py][px] := 1;
rect(SCALE * pred(px), SCALE * pred(py), SCALE, SCALE, white);
DRAW_FLUSH;
flushGraphic;
bumped := TRUE;
else
py +:= dy;
@ -43,11 +43,3 @@ const proc: genBrownianTree (in integer: fieldSize, in integer: numParticles) is
until bumped;
end for;
end func;
const proc: main is func
begin
screen(SIZE * SCALE, SIZE * SCALE);
KEYBOARD := GRAPH_KEYBOARD;
genBrownianTree(SIZE, 20000);
readln(KEYBOARD);
end func;

View file

@ -0,0 +1,21 @@
S ← 80
# Create SxS grid, and set the centre point as seed.
⍜⊡(+1)↯2⌊÷2S ↯ S_S 0
RandInt ← ⌊×⚂
RandPoint ← ([⍥(RandInt S)2])
# Update the pair to be a new adjacent [[Here] [Last]]
Move ← ⊟∵(-1+⌊RandInt 3).⊢
In ← /××⊃(≥0)(<S) # Is this point in bounds?
# Given a grid return a free point pair and that grid.
SeedPair ← ⊟.⍢(RandPoint ◌)(=1⊡) RandPoint
# Find next adjacent position, or new seed if out of bounds.
Next ← ⟨SeedPair ◌|∘⟩:⟜(In ⊢)Move
# Start from a new Seed Pair and move until you hit the tree. Add the prior pos to the tree.
JoinTree ← ⍜⊡(+1)◌°⊟⍢Next (=0⊡⊢) SeedPair
# Do it multiple times.
⍜now⍥JoinTree500
# ◌
# &ime "png"
# &fwa "BrownianTree.png"

View file

@ -0,0 +1,6 @@
S ← 80
⍜⊡(+1)↯2⌊÷2S↯S_S0
Rp ← (⊟⍥(⌊×⚂S)2)
Sd ← ⊟.⍢(Rp◌)(=1⊡) Rp
Nx ← ⟨Sd◌|∘⟩:⟜(/××⊃(≥0)(<S)⊢)⊟∵(-1+⌊×⚂3).⊢
⍜now⍥(⍜⊡(+1)◌°⊟⍢Nx(=0⊡⊢)Sd)500

View file

@ -1,26 +1,17 @@
// version 1.1.2
import java.util.Random
const val MAX_GUESSES = 20 // say
fun main(args: Array<String>) {
val r = Random()
var num: String
// generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
do {
num = (1234 + r.nextInt(8643)).toString()
} while ('0' in num || num.toSet().size < 4)
fun main() {
val num = ('1'..'9').shuffled().take(4).joinToString("")
println("All guesses should have exactly 4 distinct digits excluding zero.")
println("Keep guessing until you guess the chosen number (maximum $MAX_GUESSES valid guesses).\n")
var guesses = 0
while (true) {
print("Enter your guess : ")
val guess = readLine()!!
val guess = readln().trim()
if (guess == num) {
println("You've won with ${++guesses} valid guesses!")
return
break
}
val n = guess.toIntOrNull()
if (n == null)

View file

@ -0,0 +1,103 @@
#define STX Chr(&H2)
#define ETX Chr(&H3)
Sub Sort(arr() As String)
Dim As Integer i, j, n
n = Ubound(arr) + 1
For i = 0 To n - 1
For j = i + 1 To n - 1
If arr(i) > arr(j) Then Swap arr(i), arr(j)
Next j
Next i
End Sub
Function Replace(Byval cadena As String, Byval subcadena As String, Byval reemplazaCon As String) As String
Dim As Integer posic = Instr(cadena, subcadena)
While posic <> 0
cadena = Left(cadena, posic - 1) & reemplazaCon & Mid(cadena, posic + Len(subcadena))
posic = Instr(posic + Len(reemplazaCon), cadena, subcadena)
Wend
Return cadena
End Function
Sub Rotate(s As String)
Dim As Integer longi = Len(s)
Dim As String t = Right(s, 1)
s = t & Left(s, longi - 1)
End Sub
Function BWT(s As String) As String
Dim As Integer i
For i = 1 To Len(s)
If Mid(s, i, 1) = STX Orelse Mid(s, i, 1) = ETX Then
Print "ERROR: String can't contain STX or ETX";
Exit Function
End If
Next i
Dim As String ss = STX & s & ETX
Dim As Integer longi = Len(ss)
Dim As String tabla(longi)
For i = 1 To longi
tabla(i) = ss
Rotate(ss)
Next i
Sort tabla()
Dim As String salida
For i = 1 To longi
salida &= Right(tabla(i), 1)
Next i
Return salida
End Function
Function Ibwt(r As String) As String
Dim As Integer i, j
Dim As Integer longi = Len(r)
Dim As String sa(1 To longi)
Dim As String tabla(Lbound(sa) To Ubound(sa))
For i = 1 To longi
For j = 1 To longi
tabla(j) = Mid(r, j, 1) & tabla(j)
Next j
Sort tabla()
Next i
For i = Lbound(tabla) To Ubound(tabla)
If Right(tabla(i), 1) = ETX Then Return Mid(tabla(i), 2, longi - 2)
Next i
Return ""
End Function
Function makePrintable(s As String) As String
Dim As String ls = s
For i As Integer = 1 To Len(ls)
Select Case Mid(ls, i, 1)
Case STX : Mid(ls, i, 1) = "^"
Case ETX : Mid(ls, i, 1) = "|"
End Select
Next i
Return ls
End Function
Dim As String tests(5) = { _
"banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", _
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", STX & "ABC" & ETX }
For i As Integer = Lbound(tests) To Ubound(tests)
Print makePrintable(tests(i))
Print " --> ";
Dim As String t = BWT(tests(i))
Print makePrintable(t)
Dim As String r = iBWT(t)
Print " --> "; r; Chr(10); Chr(10);
Next i
Sleep

View file

@ -10,9 +10,9 @@ L(i) 256
crc_table[i] = rem
F crc32(buf, =crc = UInt32(0))
crc = (-)crc
crc = ~crc
L(k) buf
crc = (crc >> 8) (+) :crc_table[(crc [&] F'F) (+) k.code]
R (-)crc
R ~crc
print(hex(crc32(The quick brown fox jumps over the lazy dog)))

View file

@ -0,0 +1,17 @@
s$ = input
print s$ & ",SUM"
repeat
s$ = input
until s$ = ""
sum = 0
for v in number strsplit s$ ","
sum += v
.
print s$ & "," & sum
.
input_data
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20

View file

@ -0,0 +1,19 @@
to csv.data.manipulation :in :out
local [header line list sum]
openread :in
setread :in
openwrite :out
setwrite :out
make "header readword
print word :header ",SUM
while [not eofp] [
make "line readword
make "list parse map [ifelse equalp ? ", ["\ ] [?]] :line
make "sum apply "sum :list
print (word :line "\, :sum)
]
close :in
setread []
close :out
setwrite []
end

View file

@ -0,0 +1 @@
csv.data.manipulation "data.csv "output.csv

View file

@ -0,0 +1,37 @@
h$ = "<table border=1>\n<tr><th>"
repeat
s$ = input
until s$ = ""
write h$
for c$ in strchars s$
if c$ = ","
if scnd = 0
c$ = "</th><th>"
else
c$ = "</td><td>"
.
elif c$ = "<"
c$ = "&lt;"
elif c$ = ">"
c$ = "&gt;"
elif c$ = "&"
c$ = "&amp;"
.
write c$
.
if scnd = 0
h$ = "</th></tr>\n<tr><td>"
scnd = 1
else
h$ = "</td></tr>\n<tr><td>"
.
.
print "</td></tr>\n</table>"
#
input_data
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!

View file

@ -1,6 +1,6 @@
F cusip_check(=cusip)
I cusip.len != 9
X ValueError(CUSIP must be 9 characters)
X.throw ValueError(CUSIP must be 9 characters)
cusip = cusip.uppercase()
V total = 0

View file

@ -1,22 +1,22 @@
val .isCusip = f(.s) {
if not isString(.s) or len(.s) != 9 {
val .isCusip = fn(.s) {
if .s is not string or len(.s) != 9 {
return false
}
val .basechars = cp2s('0'..'9') ~ cp2s('A'..'Z') ~ "*@#"
val .basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#"
val .sum = for[=0] .i of 8 {
var .v = index(s2s(.s, .i), .basechars)
if not .v: return false
.v = .v[1]-1
if .i div 2: .v x= 2
if .i div 2: .v *= 2
_for += .v \ 10 + .v rem 10
}
.s[9]-'0' == (10-(.sum rem 10)) rem 10
}
val .candidates = w/037833100 17275R102 38259P508 594918104 68389X106 68389X105/
val .candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/
for .c in .candidates {
writeln .c, ": ", if(.isCusip(.c): "good" ; "bad")

View file

@ -1,5 +1,5 @@
val .isCusip = f(.s) {
if not isString(.s) or len(.s) != 9 {
val .isCusip = fn(.s) {
if .s is not string or len(.s) != 9 {
return false
}
@ -21,7 +21,7 @@ val .isCusip = f(.s) {
default: return false
}
if .i div 2: .v x= 2
if .i div 2: .v *= 2
_for += .v \ 10 + .v rem 10
}

View file

@ -1,45 +1,58 @@
with Ada.Text_IO;
-- Caesar Cipher Implementation in Ada
with Ada.Text_IO; use Ada.Text_IO;
procedure Caesar is
type modulo26 is modulo 26;
function modulo26 (Character: Character; Output: Character) return modulo26 is
-- Base function to encrypt a character
function Cipher(Char_To_Encrypt: Character; Shift: Integer; Base: Character) return Character is
Base_Pos : constant Natural := Character'Pos(Base);
begin
return modulo26 (Character'Pos(Character)+Character'Pos(Output));
end modulo26;
return Character'Val((Character'Pos(Char_To_Encrypt) + Shift - Base_Pos) mod 26 + Base_Pos);
end Cipher;
function Character(Val: in modulo26; Output: Character)
return Character is
-- Function to encrypt a character
function Encrypt_Char(Char_To_Encrypt: Character; Shift: Integer) return Character is
begin
return Character'Val(Integer(Val)+Character'Pos(Output));
end Character;
function crypt (Playn: String; Key: modulo26) return String is
Ciph: String(Playn'Range);
case Char_To_Encrypt is
when 'A'..'Z' =>
-- Encrypt uppercase letters
return Cipher (Char_To_Encrypt, Shift, 'A');
when 'a'..'z' =>
-- Encrypt lowercase letters
return Cipher (Char_To_Encrypt, Shift, 'a');
when others =>
-- Leave other characters unchanged
return Char_To_Encrypt;
end case;
end Encrypt_Char;
-- Function to decrypt a character
function Decrypt_Char(Char_To_Decrypt: Character; Shift: Integer) return Character is
begin
for I in Playn'Range loop
case Playn(I) is
when 'A' .. 'Z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'A');
when 'a' .. 'z' =>
Ciph(I) := Character(modulo26(Playn(I)+Key), 'a');
when others =>
Ciph(I) := Playn(I);
end case;
end loop;
return Ciph;
end crypt;
return Encrypt_Char(Char_To_Decrypt, -Shift);
end Decrypt_Char;
Text: String := Ada.Text_IO.Get_Line;
Key: modulo26 := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher
Message: constant String := Ada.Text_IO.Get_Line;
Shift: Positive := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher
-- Shift value (can be any positive integer)
begin -- encryption main program
Encrypted_Message: String(Message'Range);
Decrypted_Message: String(Message'Range);
begin
-- Encrypt the message
for I in Message'Range loop
Encrypted_Message(I) := Encrypt_Char(Message(I), Shift);
end loop;
Ada.Text_IO.Put_Line("Playn ------------>" & Text);
Text := crypt(Text, Key);
Ada.Text_IO.Put_Line("Ciphertext ----------->" & Text);
Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & crypt(Text, -Key));
-- Decrypt the encrypted message
for I in Message'Range loop
Decrypted_Message(I) := Decrypt_Char(Encrypted_Message(I), Shift);
end loop;
-- Display results
Put_Line("Plaintext: " & Message);
Put_Line("Ciphertext: " & Encrypted_Message);
Put_Line("Decrypted Ciphertext: " & Decrypted_Message);
end Caesar;

View file

@ -1,5 +1,5 @@
val .rot = f(.s, .key) {
cp2s map(f(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s)
val .rot = fn(.s, .key) {
cp2s map(fn(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s)
}
val .s = "A quick brown fox jumped over something."

View file

@ -0,0 +1,23 @@
const std = @import("std");
const stdout = @import("std").io.getStdOut().writer();
pub fn rot(txt: []u8, key: u8) void {
for (txt, 0..txt.len) |c, i| {
if (std.ascii.isLower(c)) {
txt[i] = (c - 'a' + key) % 26 + 'a';
} else if (std.ascii.isUpper(c)) {
txt[i] = (c - 'A' + key) % 26 + 'A';
}
}
}
pub fn main() !void {
const key = 3;
var txt = "The five boxing wizards jump quickly".*;
try stdout.print("Original: {s}\n", .{txt});
rot(&txt, key);
try stdout.print("Encrypted: {s}\n", .{txt});
rot(&txt, 26 - key);
try stdout.print("Decrypted: {s}\n", .{txt});
}

View file

@ -6,7 +6,7 @@ var .e = 2
for .fact, .n = 1, 2 ; ; .n += 1 {
val .e0 = .e
.fact x= .n
.fact *= .n
.e += 1 / .fact
if abs(.e - .e0) < .epsilon: break
}

View file

@ -4,7 +4,7 @@
declare -ir one=10**9
declare -i e n rfct=one
while (( (rfct /= ++n) != 0 ))
while (( rfct /= ++n ))
do e+=rfct
done

View file

@ -0,0 +1,67 @@
library(lubridate)
library(stringi)
# Helper function padding
pad_d <- function(gr) gr %>% stri_pad_left(2) %>% stri_c(collapse = " ")
pad_l <- function(gr) gr %>% pad_d() %>% stri_pad_left(20)
pad_r <- function(gr) gr %>% pad_d() %>% stri_pad_right(20)
pad_20 <- " " %s*% 20
# 1st week mapping
idx_week <- list("1"=1,"7"=2,"6"=3,"5"=4,"4"=5,"3"=6,"2"=7)
# Generate a single month
gen_cal <- function(date_str) {
str_l <- list()
# Pick up month name
month_name <- month(ymd(date_str),label = T,abbr = F) %>%
as.character() %>%
stri_pad_both(20)
# Add to list with day header
str_l[length(str_l)+1] <- month_name
str_l[length(str_l)+1] <- "Mo Tu We Th Fr Sa Su"
# Day list for the month
cc <- 1:days_in_month(as.Date(date_str))
# Staring week
wd <- wday(ymd(date_str))
st <- idx_week[as.character(wd)][[1]]
# Add 1st week
str_l[length(str_l)+1] <- pad_l(head(cc,st))
# Middle weeks
cc <- tail(cc,-st)
while (length(cc) > 7) {
str_l[length(str_l)+1] <- pad_l(head(cc,7))
cc <- tail(cc,-7)
}
# Last week
str_l[length(str_l)+1] <- pad_r(cc)
# Pad for empty week
if (length(str_l)==7)
str_l[length(str_l)+1] <- pad_20
str_l
}
# Print calendar
print_calendar <- function(target_year) {
cat("\n",stri_pad_both(target_year,64),"\n\n")
for (j in seq.int(1,12,3)) {
cal <- sapply(j:(j+2),\(x) gen_cal(paste0(target_year,"/",x,"/1")))
xres <- paste(cal[,1],cal[,2],cal[,3],sep = " ")
for (i in xres) cat(i,"\n")
}
}
#
# Main
#
print_calendar("1969")

View file

@ -0,0 +1,22 @@
subr first
n = 1 ; d = 1
.
proc next . .
n = 2 * (n div d) * d + d - n
swap n d
.
print "The first 20 terms of the Calkwin-Wilf sequence are:"
first
for i to 20
write n & "/" & d & " "
next
.
print ""
#
first
i = 1
while n <> 83116 or d <> 51639
next
i += 1
.
print "83116/51639 is at position " & i

View file

@ -1,7 +1,7 @@
val .sum = foldfrom(
f(.sum, .i, .c) .sum + toNumber(.c, 36) x .weight[.i],
fn(.sum, .i, .c) .sum + number(.c, 36) * .weight[.i],
0,
pseries len .code,
split ZLS, .code,
split .code,
)
# split, pseries, and len using unbounded lists, ending before comma preceding line return

View file

@ -0,0 +1,69 @@
func$ strip s$ .
a = 1
while substr s$ a 1 = " "
a += 1
.
b = len s$
while substr s$ b 1 = " "
b -= 1
.
return substr s$ a (b - a + 1)
.
func$ toupper c$ .
c = strcode c$
if c >= 97 and c <= 122
c$ = strchar (c - 32)
.
return c$
.
func$ tolower c$ .
c = strcode c$
if c >= 65 and c <= 90
c$ = strchar (c + 32)
.
return c$
.
func isupper c$ .
c = strcode c$
if c >= 65 and c <= 90
return 1
.
.
delim$ = "_- "
func$ snakecase s$ .
s$ = strip s$
for c$ in strchars s$
if isupper c$ = 1 and prev$ <> ""
if strpos delim$ prev$ = 0
r$ &= "_"
.
r$ &= tolower c$
else
r$ &= c$
.
prev$ = c$
.
return r$
.
func$ camelcase s$ .
s$ = strip s$
prev$ = "x"
for c$ in strchars s$
if strpos delim$ prev$ <> 0
r$ &= toupper c$
elif strpos delim$ c$ = 0
r$ &= c$
.
prev$ = c$
.
return r$
.
test$[] = [ "snakeCase" "snake_case" "variable_10_case" "variable10Case" "ɛrgo rE tHis" "hurry-up-joe!" "c://my-docs/happy_Flag-Day/12.doc" " spaces " ]
print "=== To snake_case ==="
for s$ in test$[]
print s$ & " -> " & snakecase s$
.
print "\n=== To camelCase ==="
for s$ in test$[]
print s$ & " -> " & camelcase s$
.

View file

@ -1,4 +1,4 @@
val .X = f(... .x) .x
val .X = fn(... .x) .x
writeln mapX(.X, [1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]]
writeln mapX(.X, [3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]]

Some files were not shown because too many files have changed in this diff Show more