Data update

This commit is contained in:
Ingy döt Net 2024-03-06 22:25:12 -08:00
parent ed705008a8
commit 0df55f9f24
2196 changed files with 32999 additions and 3075 deletions

View file

@ -0,0 +1,29 @@
* NB: the implementation is rather vanilla
* besides using the idiomatic buffer overrun.
* LOOP is what PERFORM in COBOL is, with defaults.
* MOVE in this language acts like OVE CORRESPONDING,
* which is actually good here.
IDENTIFICATION DIVISION.
PROGRAM-ID. ONE HUNDRED DOORS.
DATA DIVISION.
01 I PICTURE IS 9(3).
01 J LIKE I.
01 DOOR PICTURE IS 9 OCCURS 100 TIMES.
01 STOP LIKE DOOR.
PROCEDURE DIVISION.
* Initialise the data
MOVE HIGH-VALUES TO STOP
MOVE SPACES TO DOOR.
* Do the main algorithm
LOOP VARYING I UNTIL DOOR(I) = 9
LOOP VARYING J FROM I TO 100 BY I
SUBTRACT DOOR (J) FROM 1 GIVING DOOR (J)
END
END.
* Print the results
LOOP VARYING I UNTIL DOOR(I) = 9
DISPLAY "Door" I "is" WITH NO ADVANCING
IF DOOR (I) = 1
THEN DISPLAY "open"
ELSE DISPLAY "closed".
END.

View file

@ -4,15 +4,15 @@ import extensions;
public program()
{
var Doors := Array.allocate(100).populate::(n=>false);
for(int i := 0, i < 100, i := i + 1)
for(int i := 0; i < 100; i++)
{
for(int j := i, j < 100, j := j + i + 1)
for(int j := i; j < 100; j := j + i + 1)
{
Doors[j] := Doors[j].Inverted
}
};
for(int i := 0, i < 100, i := i + 1)
for(int i := 0; i < 100; i++)
{
console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed"))
};

View file

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

View file

@ -0,0 +1,38 @@
$ENTRY Go {
= <Show 1 <Walk 1 <Doors>>>;
};
NDoors { = 100; };
Doors { = <Repeat <NDoors> Closed>; };
Repeat {
0 s.val = ;
s.N s.val = s.val <Repeat <- s.N 1> s.val> ;
};
Toggle {
1 Closed e.rest = Open e.rest;
1 Open e.rest = Closed e.rest;
s.N s.door e.rest = s.door <Toggle <- s.N 1> e.rest>;
};
Pass {
s.pass s.door e.doors, <Compare s.door <NDoors>>: '+'
= e.doors;
s.pass s.door e.doors
= <Pass s.pass <+ s.pass s.door> <Toggle s.door e.doors>>;
};
Walk {
s.pass e.doors, <Compare s.pass <NDoors>>: '+'
= e.doors;
s.pass e.doors
= <Walk <+ s.pass 1> <Pass s.pass s.pass e.doors>>;
};
Show {
s.N Open e.rest = <Prout Door s.N is open>
<Show <+ s.N 1> e.rest>;
s.N Closed e.rest = <Show <+ s.N 1> e.rest>;
s.N = ;
};

View file

@ -0,0 +1 @@
var arr: [Bool] = Array(1...100).map{ remquo(exp(log(Float($0))/2.0),1).0 == 0 }

View file

@ -1,15 +1,16 @@
!yamlscript/v0
defn main():
say:
"Open doors after 100 passes:
$(apply str interpose(\", \" open-doors()))"
say: |-
Open doors after 100 passes:
$(apply str interpose(', ' open-doors()))
defn open-doors():
for: .[[d n] map(vector doors() iterate(inc 1)) :when d] n
for [[d n] map(vector doors() iterate(inc 1)) :when d]:
n
defn doors():
reduce:
fn [doors idx]: assoc(doors idx true)
fn(doors idx): assoc(doors idx true)
into []: repeat(100 false)
map \(dec (% * %)): (1 .. 10)
map \(dec (%1 * %1)): 1 .. 10

View file

@ -4,7 +4,7 @@ for i = 1 to 100
.
subr shuffle_drawer
for i = len drawer[] downto 2
r = random i
r = randint i
swap drawer[r] drawer[i]
.
.
@ -13,7 +13,7 @@ subr play_random
for prisoner = 1 to 100
found = 0
for i = 1 to 50
r = random (100 - i)
r = randint (100 - i)
card = drawer[sampler[r]]
swap sampler[r] sampler[100 - i - 1]
if card = prisoner

View file

@ -44,7 +44,7 @@ proc init . .
.
# shuffle
for i = 15 downto 2
r = random i
r = randint i
swap f[r] f[i]
.
# make it solvable

View file

@ -0,0 +1,452 @@
/*
**
** Game : CalmoSoft Fifteen Puzzle Game 3D
** Date : 2017/09/01
** Author : CalmoSoft <calmosoft@gmail.com>, Mahmoud Fayed
**
*/
# Load Libraries
load "gamelib.ring" # RingAllegro Library
load "opengl21lib.ring" # RingOpenGL Library
butSize = 3
texture = list(9)
cube = list(9)
rnd = list(9)
rndok = 0
for n=1 to 9
rnd[n] = 0
next
for n=1 to 9
while true
rndok = 0
ran = random(8) + 1
for nr=1 to 9
if rnd[nr] = ran
rndok = 1
ok
next
if rndok = 0
rnd[n] = ran
exit
ok
end
next
for n=1 to 9
if rnd[n] = 9
empty = n
ok
next
#==============================================================
# To Support MacOS X
al_run_main()
func al_game_start # Called by al_run_main()
main() # Now we call our main function
#==============================================================
func main
new TicTacToe3D {
start()
}
class TicTacToe3D from GameLogic
FPS = 60
TITLE = "CalmoSoft Fifteen Puzzle Game 3D"
oBackground = new GameBackground
oGameSound = new GameSound
oGameCube = new GameCube
oGameInterface = new GameInterface
func loadresources
oGameSound.loadresources()
oBackGround.loadresources()
oGameCube.loadresources()
func drawScene
oBackground.update()
oGameInterface.update(self)
func MouseClickEvent
oGameInterface.MouseClickEvent(self)
class GameInterface
func Update oGame
prepare()
cubes(oGame)
func Prepare
w = 1024 h = 768
ratio = w / h
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(-120,ratio,1,120)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glEnable(GL_TEXTURE_2D)
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.0, 0.0, 0.5)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glEnable(GL_CULL_FACE)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
func Cubes oGame
oGame.oGameCube {
aGameMap = oGame.aGameMap
cube[1] = cube( 5 , -3 , -5 , texture[rnd[1]] )
cube[2] = cube( 0 , -3 , -5 , texture[rnd[2]] )
cube[3] = cube( -5 , -3 , -5 , texture[rnd[3]] )
cube[4] = cube( 5 , 1 , -5 , texture[rnd[4]] )
cube[5] = cube( 0 , 1 , -5 , texture[rnd[5]] )
cube[6] = cube( -5 , 1 , -5 , texture[rnd[6]] )
cube[7] = cube( 5 , 5 , -5 , texture[rnd[7]] )
cube[8] = cube( 0 , 5 , -5 , texture[rnd[8]] )
cube[9] = cube( -5 , 5 , -5 , texture[rnd[9]] )
rotate()
}
func MouseClickEvent oGame
oGame {
aBtn = Point2Button(Mouse_X,Mouse_Y)
move = 0
nRow = aBtn[1]
nCol = aBtn[2]
tile = (nRow-1)*3 + nCol
up = (empty = (tile - butSize))
down = (empty = (tile + butSize))
left = ((empty = (tile- 1)) and ((tile % butSize) != 1))
right = ((empty = (tile + 1)) and ((tile % butSize) != 0))
move = up or down or left or right
if move = 1
temp = rnd[empty]
rnd[empty] = rnd[tile]
rnd[tile] = temp
empty = tile
oGame.oGameCube {
aGameMap = oGame.aGameMap
cube[1] = cube( 5 , -3 , -5 , texture[rnd[1]] )
cube[2] = cube( 0 , -3 , -5 , texture[rnd[2]] )
cube[3] = cube( -5 , -3 , -5 , texture[rnd[3]] )
cube[4] = cube( 5 , 1 , -5 , texture[rnd[4]] )
cube[5] = cube( 0 , 1 , -5 , texture[rnd[5]] )
cube[6] = cube( -5 , 1 , -5 , texture[rnd[6]] )
cube[7] = cube( 5 , 5 , -5 , texture[rnd[7]] )
cube[8] = cube( 0 , 5 , -5 , texture[rnd[8]] )
cube[9] = cube( -5 , 5 , -5 , texture[rnd[9]] )
rotate()
}
ok
}
Class GameLogic from GraphicsAppBase
aGameMap = [
[ :n , :n , :n ] ,
[ :n , :n , :n ] ,
[ :n , :n , :n ]
]
aGameButtons = [ # x1,y1,x2,y2
[176,88,375,261], # [1,1]
[423,88,591,261], # [1,2]
[645,88,876,261], # [1,3]
[176,282,375,428], # [2,1]
[423,282,591,428], # [2,2]
[645,282,876,428], # [2,3]
[176,454,375,678], # [3,1]
[423,454,591,678], # [3,2]
[645,454,876,678] # [3,3]
]
cActivePlayer = :x
func point2button x,y
nRow = 0
nCol = 0
for t = 1 to len(aGameButtons)
rect = aGameButtons[t]
if x >= rect[1] and x <= rect[3] and
y >= rect[2] and y <= rect[4]
switch t
on 1 nRow = 1 nCol = 1
on 2 nRow = 1 nCol = 2
on 3 nRow = 1 nCol = 3
on 4 nRow = 2 nCol = 1
on 5 nRow = 2 nCol = 2
on 6 nRow = 2 nCol = 3
on 7 nRow = 3 nCol = 1
on 8 nRow = 3 nCol = 2
on 9 nRow = 3 nCol = 3
off
exit
ok
next
return [nRow,nCol]
class GameCube
bitmap bitmap2 bitmap3
textureX textureO textureN
xrot = 0.0
yrot = 0.0
zrot = 0.0
func loadresources
bitmp1 = al_load_bitmap("image/n1.jpg")
texture[1] = al_get_opengl_texture(bitmp1)
bitmp2 = al_load_bitmap("image/n2.jpg")
texture[2] = al_get_opengl_texture(bitmp2)
bitmp3 = al_load_bitmap("image/n3.jpg")
texture[3] = al_get_opengl_texture(bitmp3)
bitmp4 = al_load_bitmap("image/n4.jpg")
texture[4] = al_get_opengl_texture(bitmp4)
bitmp5 = al_load_bitmap("image/n5.jpg")
texture[5] = al_get_opengl_texture(bitmp5)
bitmp6 = al_load_bitmap("image/n6.jpg")
texture[6] = al_get_opengl_texture(bitmp6)
bitmp7 = al_load_bitmap("image/n7.jpg")
texture[7] = al_get_opengl_texture(bitmp7)
bitmp8 = al_load_bitmap("image/n8.jpg")
texture[8] = al_get_opengl_texture(bitmp8)
bitmp9 = al_load_bitmap("image/empty.png")
texture[9] = al_get_opengl_texture(bitmp9)
func cube(x,y,z,nTexture)
glLoadIdentity()
glTranslatef(x,y,z)
glRotatef(xrot,1.0,0.0,0.0)
glRotatef(yrot,0.0,1.0,0.0)
glRotatef(zrot,0.0,0.0,1.0)
setCubeTexture(nTexture)
drawCube()
func setCubeTexture cTexture
glBindTexture(GL_TEXTURE_2D, cTexture)
func Rotate
xrot += 0.3 * 5
yrot += 0.2 * 5
zrot += 0.4 * 5
func drawcube
glBegin(GL_QUADS)
// Front Face
glTexCoord2f(0.0, 0.0) glVertex3f(-1.0, -1.0, 1.0)
glTexCoord2f(1.0, 0.0) glVertex3f( 1.0, -1.0, 1.0)
glTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0)
glTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, 1.0)
// Back Face
glTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, -1.0)
glTexCoord2f(1.0, 1.0) glVertex3f(-1.0, 1.0, -1.0)
glTexCoord2f(0.0, 1.0) glVertex3f( 1.0, 1.0, -1.0)
glTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, -1.0)
// Top Face
glTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, -1.0)
glTexCoord2f(0.0, 0.0) glVertex3f(-1.0, 1.0, 1.0)
glTexCoord2f(1.0, 0.0) glVertex3f( 1.0, 1.0, 1.0)
glTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, -1.0)
// Bottom Face
glTexCoord2f(1.0, 1.0) glVertex3f(-1.0, -1.0, -1.0)
glTexCoord2f(0.0, 1.0) glVertex3f( 1.0, -1.0, -1.0)
glTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, 1.0)
glTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, 1.0)
// Right face
glTexCoord2f(1.0, 0.0) glVertex3f( 1.0, -1.0, -1.0)
glTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, -1.0)
glTexCoord2f(0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0)
glTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, 1.0)
// Left Face
glTexCoord2f(0.0, 0.0) glVertex3f(-1.0, -1.0, -1.0)
glTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, 1.0)
glTexCoord2f(1.0, 1.0) glVertex3f(-1.0, 1.0, 1.0)
glTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, -1.0)
glEnd()
class GameBackground
nBackX = 0
nBackY = 0
nBackDiffx = -1
nBackDiffy = -1
nBackMotion = 1
aBackMotionList = [
[ -1, -1 ] , # Down - Right
[ 0 , 1 ] , # Up
[ -1, -1 ] , # Down - Right
[ 0 , 1 ] , # Up
[ 1 , -1 ] , # Down - Left
[ 0 , 1 ] , # Up
[ 1 , -1 ] , # Down - Left
[ 0 , 1 ] # Up
]
bitmap
func Update
draw()
motion()
func draw
al_draw_bitmap(bitmap,nBackX,nBackY,1)
func motion
nBackX += nBackDiffx
nBackY += nBackDiffy
if (nBackY = -350) or (nBackY = 0)
nBackMotion++
if nBackMotion > len(aBackMotionList)
nBackMotion = 1
ok
nBackDiffx = aBackMotionList[nBackMotion][1]
nBackDiffy = aBackMotionList[nBackMotion][2]
ok
func loadResources
bitmap = al_load_bitmap("image/back.jpg")
class GameSound
sample sampleid
func loadresources
sample = al_load_sample( "sound/music1.wav" )
sampleid = al_new_allegro_sample_id()
al_play_sample(sample, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,sampleid)
class GraphicsAppBase
display event_queue ev timeout
timer
redraw = true
FPS = 60
SCREEN_W = 1024
SCREEN_H = 700
KEY_UP = 1
KEY_DOWN = 2
KEY_LEFT = 3
KEY_RIGHT = 4
Key = [false,false,false,false]
Mouse_X = 0
Mouse_Y = 0
TITLE = "Graphics Application"
PRINT_MOUSE_XY = False
func start
SetUp()
loadResources()
eventsLoop()
destroy()
func setup
al_init()
al_init_font_addon()
al_init_ttf_addon()
al_init_image_addon()
al_install_audio()
al_init_acodec_addon()
al_reserve_samples(1)
al_set_new_display_flags(ALLEGRO_OPENGL)
display = al_create_display(SCREEN_W,SCREEN_H)
al_set_window_title(display,TITLE)
al_clear_to_color(al_map_rgb(0,0,0))
event_queue = al_create_event_queue()
al_register_event_source(event_queue,
al_get_display_event_source(display))
ev = al_new_allegro_event()
timeout = al_new_allegro_timeout()
al_init_timeout(timeout, 0.06)
timer = al_create_timer(1.0 / FPS)
al_register_event_source(event_queue,
al_get_timer_event_source(timer))
al_start_timer(timer)
al_install_mouse()
al_register_event_source(event_queue,
al_get_mouse_event_source())
al_install_keyboard()
al_register_event_source(event_queue,
al_get_keyboard_event_source())
func eventsLoop
while true
al_wait_for_event_until(event_queue, ev, timeout)
switch al_get_allegro_event_type(ev)
on ALLEGRO_EVENT_DISPLAY_CLOSE
CloseEvent()
on ALLEGRO_EVENT_TIMER
redraw = true
on ALLEGRO_EVENT_MOUSE_AXES
mouse_x = al_get_allegro_event_mouse_x(ev)
mouse_y = al_get_allegro_event_mouse_y(ev)
if PRINT_MOUSE_XY
see "x = " + mouse_x + nl
see "y = " + mouse_y + nl
ok
on ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY
mouse_x = al_get_allegro_event_mouse_x(ev)
mouse_y = al_get_allegro_event_mouse_y(ev)
on ALLEGRO_EVENT_MOUSE_BUTTON_UP
MouseClickEvent()
on ALLEGRO_EVENT_KEY_DOWN
switch al_get_allegro_event_keyboard_keycode(ev)
on ALLEGRO_KEY_UP
key[KEY_UP] = true
on ALLEGRO_KEY_DOWN
key[KEY_DOWN] = true
on ALLEGRO_KEY_LEFT
key[KEY_LEFT] = true
on ALLEGRO_KEY_RIGHT
key[KEY_RIGHT] = true
off
on ALLEGRO_EVENT_KEY_UP
switch al_get_allegro_event_keyboard_keycode(ev)
on ALLEGRO_KEY_UP
key[KEY_UP] = false
on ALLEGRO_KEY_DOWN
key[KEY_DOWN] = false
on ALLEGRO_KEY_LEFT
key[KEY_LEFT] = false
on ALLEGRO_KEY_RIGHT
key[KEY_RIGHT] = false
on ALLEGRO_KEY_ESCAPE
exit
off
off
if redraw and al_is_event_queue_empty(event_queue)
redraw = false
drawScene()
al_flip_display()
ok
callgc()
end
func destroy
al_destroy_timer(timer)
al_destroy_allegro_event(ev)
al_destroy_allegro_timeout(timeout)
al_destroy_event_queue(event_queue)
al_destroy_display(display)
al_exit()
func loadresources
func drawScene
func MouseClickEvent
exit # Exit from the Events Loop
func CloseEvent
exit # Exit from the Events Loop

View file

@ -17,7 +17,7 @@ repeat
else
sleep 1
if sum mod 4 = 1
n = random 3
n = randint 3
else
n = 4 - (sum + 3) mod 4
.

View file

@ -0,0 +1,32 @@
: READKEY
1+ BEGIN
KEY DUP 27 = ABORT" Bye!"
48 - 2DUP > OVER 0 > AND IF
DUP 48 + EMIT CR SWAP DROP EXIT
THEN DROP
REPEAT
;
: 21GAME CLS
0 2 RND 1-
." 21 is a two player game." CR
." The game is played by choosing a number (1, 2 or 3) to be added to the running total. "
." The game is won by the player whose chosen number causes the running total to reach exactly 21."
." The running total starts at zero. One player will be the computer."
BEGIN
NOT
CR ." The sum is " OVER . CR
SWAP OVER IF
." How many would you like add?"
." (1-3) " 3 READKEY
ELSE
." It is the computer's turn."
4 OVER 1- 4 MOD -
DUP 4 = IF 3 RND 1+ MIN THEN
DUP CR ." Computer adds " . CR
THEN + SWAP
OVER 21 < NOT UNTIL
CR
IF ." Congratulations. You win."
ELSE ." Bad Luck. Computer wins."
THEN CR DROP
;

View file

@ -1,25 +1,25 @@
100 PROGRAM "21Game.bas"
110 RANDOMIZE
120 LET SUM,ADD=0
130 LET TURN=RND(2)
130 LET TURN=RND(2)-1
140 CLEAR SCREEN
150 PRINT "21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly 21."
160 PRINT "The running total starts at zero. One player will be the computer.":PRINT
170 DO
180 LET TURN=1-TURN
180 LET TURN=NOT TURN
190 SET #102:INK 3:PRINT "The sum is";SUM:SET #102:INK 1
200 IF TURN=1 THEN
200 IF TURN THEN
210 PRINT "It is your turn.":PRINT "How many would you like to add? (1-3): ";
220 LET ADD=READKEY
230 IF ADD>21-SUM THEN PRINT "You can only add";21-SUM
240 ELSE
250 LET ADD=4-MOD((SUM-1),4)
260 IF ADD=4 THEN LET ADD=MIN(RND(3)+1,SUM)
250 LET ADD=4-MOD(SUM-1,4)
260 IF ADD=4 THEN LET ADD=RND(3)+1
270 PRINT "It is the computer's turn.":PRINT "The computer adds";ADD
280 END IF
290 PRINT :LET SUM=SUM+ADD
300 LOOP WHILE SUM<21
310 IF TURN=1 THEN
310 IF TURN THEN
320 PRINT "Congratulations. You win."
330 ELSE
340 PRINT "Bad luck. The computer wins."

View file

@ -0,0 +1,42 @@
real Stack(10), A, B;
int SP, I, Char, Digit, Digits(10);
proc Push(X);
real X;
[Stack(SP):= X; SP:= SP+1];
func real Pop;
[SP:= SP-1; return Stack(SP)];
[SP:= 0;
for I:= 0 to 9 do Digits(I):= 0;
Text(0, "Enter an RPN expression that equals 24 using all these digits:");
for I:= 0 to 3 do
[Digit:= Ran(9)+1;
ChOut(0, ^ ); ChOut(0, Digit+^0);
Digits(Digit):= Digits(Digit)+1;
];
Text(0, "^m^j> ");
loop [Char:= ChIn(1);
ChOut(0, Char);
if Char >= ^1 and Char <=^9 then
[Digit:= Char - ^0;
Push(float(Digit));
Digits(Digit):= Digits(Digit) - 1;
]
else [if SP >= 2 then [A:= Pop; B:= Pop] else quit;
case Char of
^+: Push(B+A);
^-: Push(B-A);
^*: Push(B*A);
^/: Push(B/A)
other quit;
];
];
CrLf(0);
for I:= 0 to 9 do
if Digits(I) # 0 then
[Text(0, "Must use each of the given digits.^m^j"); exit];
Text(0, if abs(Pop-24.0) < 0.001 then "Correct!" else "Wrong.");
CrLf(0);
]

View file

@ -0,0 +1,10 @@
library(partitions)
library(stringi)
get_row <- function(x) unname(table(parts(x)[1,]))
center_string <- function(s,pad_len=80) stri_pad_both(s,(pad_len - length(s))," ")
for (i in 1:25) cat(center_string(stri_c(get_row(i),collapse = " "),80),"\n")
cat("The sum of G(25) is:", sum(get_row(25)),"\n")

View file

@ -0,0 +1,38 @@
* Pointing out some interesting things:
* - BY 0 subclause of VARYING (illegal in some COBOL dialects)
* - PERFORM THROUGH with internal/external GO TOs
* - using non-reserved keywords (END, DATA)
* - ALTER (works the same way in COBOL)
* - fall-through from MANY-BOTTLES
* - the last NEXT SENTENCE does nothing (plays the role of EXIT)
IDENTIFICATION DIVISION.
PROGRAM-ID. 99 BOTTLES.
DATA DIVISION.
01 DATA PICTURE IS 999.
PROCEDURE DIVISION.
LOOP VARYING DATA FROM 99 BY 0
PERFORM COUNT-BOTTLES THROUGH END
DISPLAY DATA "bottles of beer"
DISPLAY "Take one down, pass it around"
SUBTRACT 1 FROM DATA
IF DATA = 1
THEN ALTER COUNT-BOTTLES TO PROCEED TO SINGLE-BOTTLE
END
PERFORM COUNT-BOTTLES THROUGH END
DISPLAY ""
END.
NO-BOTTLES-LEFT.
DISPLAY "No bottles of beer on the wall"
DISPLAY ""
DISPLAY "Go to the store and buy some more"
DISPLAY "99 bottles of beer on the wall".
STOP.
COUNT-BOTTLES.
GO TO MANY-BOTTLES.
SINGLE-BOTTLE.
DISPLAY DATA "bottle of beer on the wall".
GO TO NO-BOTTLES-LEFT.
MANY-BOTTLES.
DISPLAY DATA "bottles of beer on the wall".
END.
NEXT SENTENCE.

View file

@ -0,0 +1,11 @@
:import std/Combinator .
:import std/Number .
:import std/String .
main [y [[=?0 case-end case-rec]] (+99)]
case-rec n ++ t1 ++ n ++ t2 ++ t3 ++ n ++ t1 ++ "\n" ++ (1 --0)
n number→string 0
t1 " bottles of beer on the wall\n"
t2 " bottles of beer\n"
t3 "Take one down, pass it around\n"
case-end empty

View file

@ -0,0 +1,29 @@
$ENTRY Go {
= <Prout <Verses 99>>;
};
Verses {
'-'1 = ;
s.1 = <Verse s.1>
<Verses <- s.1 1>>;
};
Verse {
s.1 = <Bottles s.1> ' of beer on the wall,\n'
<Bottles s.1> ' of beer,\n'
<ThirdLine s.1> '\n'
<Bottles <- s.1 1>> ' of beer on the wall!\n\n';
};
Bottles {
'-'1 = '99 bottles';
0 = 'No more bottles';
1 = '1 bottle';
s.1 = s.1 'bottles';
};
ThirdLine {
0 = 'Go to the store and buy some more,';
1 = 'Take it down and pass it around,';
s.1 = 'Take one down and pass it around,';
};

View file

@ -0,0 +1,63 @@
( uxncli 99bottles.rom )
|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1
|0100 ( -> )
#63 &loop
DUP <print-verse>
[ LIT2 0a -Console/write ] DEO
#01 EQUk ?&done
POP #01 SUB
!&loop
&done BRK
@<print-verse> ( num -- )
DUP <print-bottle> ;dict/wall <print-string>
DUP <print-bottle> [ LIT2 0a -Console/write ] DEO
;dict/take <print-string>
#01 SUB <print-bottle> ;dict/wall !<print-string>
@<print-bottle> ( num -- )
DUP #00 EQU ?&zero
DUP #01 EQU ?&one
<print-dec> ;dict/bottle <print-string>
[ LIT2 "s -Console/write ] DEO
!&end
&one ( num -- )
<print-dec> ;dict/bottle <print-string>
!&end
&zero ( num -- )
POP ;dict/no-more <print-string>
;dict/bottle <print-string>
[ LIT2 "s -Console/write ] DEO
( >> )
&end
;dict/of-beer
( >> )
@<print-string> ( str -- )
&loop
LDAk .Console/write DEO
INC2 LDAk ?&loop
POP2 JMP2r
@<print-dec> ( byte -- )
DUP #64 DIV <print-num>/try
DUP #0a DIV <print-num>/try
( >> )
@<print-num> ( num -- )
#0a DIVk MUL SUB
[ LIT "0 ] ADD .Console/write DEO
JMP2r
&try ( num -- )
DUP ?<print-num>
POP JMP2r
@dict &no-more "No 20 "more $1
&bottle 20 "bottle $1
&of-beer 20 "of 20 "beer 20 $1
&wall "on 20 "the 20 "wall 0a $1
&take "Take 20 "one 20 "down, 20 "pass 20 "it 20 "around 0a $1

View file

@ -5,19 +5,18 @@
# usage:
# ys 99-bottles.ys [<count>]
defn main(&[number]):
each [n ((number || 99) .. 1)]:
say:
paragraph: n
defn main(number=99):
each [n (number .. 1)]:
say: paragraph(n)
defn paragraph(num): |
$(bottles num) of beer on the wall,
$(bottles num) of beer.
$bottles(num) of beer on the wall,
$bottles(num) of beer.
Take one down, pass it around.
$(bottles (num - 1)) of beer on the wall.
$bottles(num - 1) of beer on the wall.
defn bottles(n):
cond:
(n == 0) "No more bottles"
(n == 1) "1 bottle"
:else str(n " bottles")
n == 0 : 'No more bottles'
n == 1 : '1 bottle'
=> : "$n bottles"

View file

@ -0,0 +1,11 @@
* NB: COBOL's ACCEPT does not work with multiple identifiers
IDENTIFICATION DIVISION.
PROGRAM-ID. PLUS.
DATA DIVISION.
01 A PICTURE IS S9999.
01 B LIKE A.
PROCEDURE DIVISION.
DISPLAY "Enter two numbers: " WITH NO ADVANCING.
ACCEPT A B.
ADD A TO B.
DISPLAY "A+B =" B.

View file

@ -0,0 +1,6 @@
:import std/Combinator .
:import std/String .
:import std/Number .
:import std/Char C
main (split-by (C.eq? ' ')) → &(add ⋔ string→number)

View file

@ -1,8 +1,8 @@
a$ = input
i = 1
while i < len a$ and substr a$ i 1 <> " "
i += 1
repeat
i += 1
until i > len a$ or substr a$ i 1 = " "
.
a = number substr a$ 1 i
b = number substr a$ i -1
b = number substr a$ i 99
print a + b

View file

@ -0,0 +1,35 @@
$ENTRY Go {
= <Each Show (<Blocks>) <Words>>;
};
Each {
s.F (e.Arg) = ;
s.F (e.Arg) t.I e.R = <Mu s.F t.I e.Arg> <Each s.F (e.Arg) e.R>;
};
Show {
(e.Word) e.Blocks = <Prout e.Word ': ' <CanMakeWord (e.Word) e.Blocks>>;
};
Blocks {
= ('BO') ('XK') ('DQ') ('CP') ('NA')
('GT') ('RE') ('TG') ('QD') ('FS')
('JW') ('HU') ('VI') ('AN') ('OB')
('ER') ('FS') ('LY') ('PC') ('ZM');
};
Words {
= ('A') ('BARK') ('BOOK') ('TREAT')
('common') ('squad') ('CoNfUsE');
};
CanMakeWord {
(e.Word) e.Blocks = <CanMakeWord1 (<Upper e.Word>) e.Blocks>;
}
CanMakeWord1 {
() e.Blocks = T;
(s.Ltr e.Word) e.Blocks1 (e.X s.Ltr e.Y) e.Blocks2
= <CanMakeWord1 (e.Word) e.Blocks1 e.Blocks2>;
(e.Word) e.Blocks = F;
};

View file

@ -0,0 +1,21 @@
program ABC_problem;
blocks := ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"];
words := ["A","BARK","BOOK","treat","common","Squad","CoNfUsE"];
loop for word in words do
print(rpad(word, 8), can_make_word(word, blocks));
end loop;
proc can_make_word(word, blocks);
loop for letter in word do
if exists block = blocks(i) | to_upper(letter) in block then
blocks(i) := "";
else
return false;
end if;
end loop;
return true;
end proc;
end program;

View file

@ -12,9 +12,9 @@ singleton AksTest
if ((n < 0) || (n > 63)) { AbortException.raise() }; // gracefully deal with range issue
c[i] := 1l;
for (int i := 0, i < n, i += 1) {
for (int i := 0; i < n; i += 1) {
c[1 + i] := 1l;
for (int j := i, j > 0, j -= 1) {
for (int j := i; j > 0; j -= 1) {
c[j] := c[j - 1] - c[j]
};
c[0] := c[0].Negative
@ -52,7 +52,7 @@ singleton AksTest
public program()
{
for (int n := 0, n < 10, n += 1) {
for (int n := 0; n < 10; n += 1) {
AksTest.coef(n);
console.print("(x-1)^",n," = ");
@ -61,7 +61,7 @@ public program()
};
console.print("Primes:");
for (int n := 1, n <= 63, n += 1) {
for (int n := 1; n <= 63; n += 1) {
if (AksTest.is_prime(n))
{
console.print(n," ")

View file

@ -0,0 +1,33 @@
protocol Pet {
var name: String { get set }
var favouriteToy: String { get set }
func feed() -> Bool
func stroke() -> Void
}
extension Pet {
// Default implementation must be in an extension, not in the declaration above
func stroke() {
print("default purr")
}
}
struct Dog: Pet {
var name: String
var favouriteToy: String
// Required implementation
func feed() -> Bool {
print("more please")
return false
}
// If this were not implemented, the default from the extension above
// would be called.
func stroke() {
print("roll over")
}
}

View file

@ -7,15 +7,15 @@ classifyNumbers(int bound, ref int abundant, ref int deficient, ref int perfect)
int p := 0;
int[] sum := new int[](bound + 1);
for(int divisor := 1, divisor <= bound / 2, divisor += 1)
for(int divisor := 1; divisor <= bound / 2; divisor += 1)
{
for(int i := divisor + divisor, i <= bound, i += divisor)
for(int i := divisor + divisor; i <= bound; i += divisor)
{
sum[i] := sum[i] + divisor
}
};
for(int i := 1, i <= bound, i += 1)
for(int i := 1; i <= bound; i += 1)
{
int t := sum[i];

View file

@ -0,0 +1,33 @@
// classify the numbers 1 : 20 000 as abudant, deficient or perfect
"use strict"
let abundantCount = 0
let deficientCount = 0
let perfectCount = 0
const maxNumber = 20000
// construct a table of the proper divisor sums
let pds = []
pds[ 1 ] = 0
for( let i = 2; i <= maxNumber; i ++ ){ pds[ i ] = 1 }
for( let i = 2; i <= maxNumber; i ++ )
{
for( let j = i + i; j <= maxNumber; j += i ){ pds[ j ] += i }
}
// classify the numbers
for( let n = 1; n <= maxNumber; n ++ )
{
if( pds[ n ] < n )
{
deficientCount ++
}
else if( pds[ n ] == n )
{
perfectCount ++
}
else // pds[ n ] > n
{
abundantCount ++
}
}
console.log( "abundant " + abundantCount.toString() )
console.log( "deficient " + deficientCount.toString() )
console.log( "perfect " + perfectCount.toString() )

View file

@ -0,0 +1,101 @@
func gcd n d .
if d = 0
return n
.
return gcd d (n mod d)
.
func totient n .
for m = 1 to n
if gcd m n = 1
tot += 1
.
.
return tot
.
func isPowerful m .
n = m
f = 2
l = sqrt m
if m <= 1
return 0
.
while 1 = 1
q = n div f
if n mod f = 0
if m mod (f * f) <> 0
return 0
.
n = q
if f > n
return 1
.
else
f += 1
if f > l
if m mod (n * n) <> 0
return 0
.
return 1
.
.
.
.
func isAchilles n .
if isPowerful n = 0
return 0
.
m = 2
a = m * m
repeat
repeat
if a = n
return 0
.
a *= m
until a > n
.
m += 1
a = m * m
until a > n
.
return 1
.
print "First 50 Achilles numbers:"
n = 1
repeat
if isAchilles n = 1
write n & " "
num += 1
.
n += 1
until num >= 50
.
print ""
print ""
print "First 20 strong Achilles numbers:"
num = 0
n = 1
repeat
if isAchilles n = 1 and isAchilles totient n = 1
write n & " "
num += 1
.
n += 1
until num >= 20
.
print ""
print ""
print "Number of Achilles numbers with 2 to 5 digits:"
a = 10
b = 100
for i = 2 to 5
num = 0
for n = a to b - 1
if isAchilles n = 1
num += 1
.
.
write num & " "
a = b
b *= 10
.

View file

@ -1,78 +1,108 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.Map;
public final class AchlllesNumbers {
public class AchillesNumbers {
public static void main(String[] aArgs) {
Set<Integer> perfectPowers = perfectPowers(500_000);
List<Integer> achilles = achilles(1, 250_000, perfectPowers);
List<Integer> totients = totients(250_000);
private Map<Integer, Boolean> pps = new HashMap<>();
System.out.println("First 50 Achilles numbers:");
for ( int i = 0; i < 50; i++ ) {
System.out.print(String.format("%4d%s", achilles.get(i), ( ( i + 1 ) % 10 == 0 ) ? "\n" : " "));
}
System.out.println();
System.out.println("First 50 strong Achilles numbers:");
for ( int i = 0, count = 0; count < 50; i++ ) {
if ( achilles.contains(totients.get(achilles.get(i))) ) {
System.out.print(String.format("%6d%s", achilles.get(i), ( ++count % 10 == 0 ) ? "\n" : " "));
}
}
System.out.println();
System.out.println("Number of Achilles numbers with:");
for ( int i = 100; i < 1_000_000; i *= 10 ) {
final int digits = String.valueOf(i).length() - 1;
System.out.println(" " + digits + " digits: " + achilles(i / 10, i - 1, perfectPowers).size());
}
}
private static List<Integer> achilles(int aFrom, int aTo, Set<Integer> aPerfectPowers) {
Set<Integer> result = new TreeSet<Integer>();
final int cubeRoot = (int) Math.cbrt(aTo / 4);
final int squareRoot = (int) Math.sqrt(aTo / 8);
for ( int b = 2; b <= cubeRoot; b++ ) {
final int bCubed = b * b * b;
for ( int a = 2; a <= squareRoot; a++ ) {
int achilles = bCubed * a * a;
if ( achilles >= aTo ) {
break;
}
if ( achilles >= aFrom && ! aPerfectPowers.contains(achilles) ) {
result.add(achilles);
}
}
}
return new ArrayList<Integer>(result);
}
private static Set<Integer> perfectPowers(int aN) {
Set<Integer> result = new TreeSet<Integer>();
for ( int i = 2, root = (int) Math.sqrt(aN); i <= root; i++ ) {
for ( int perfect = i * i; perfect < aN; perfect *= i ) {
result.add(perfect);
}
}
return result;
}
private static List<Integer> totients(int aN) {
List<Integer> result = IntStream.rangeClosed(0, aN).boxed().collect(Collectors.toList());;
for ( int i = 2; i <= aN; i++ ) {
if ( result.get(i) == i ) {
result.set(i, i - 1);
for ( int j = i * 2; j <= aN; j = j + i ) {
result.set(j, ( result.get(j) / i ) * ( i - 1 ));
}
}
}
return result;
}
public int totient(int n) {
int tot = n;
int i = 2;
while (i * i <= n) {
if (n % i == 0) {
while (n % i == 0) {
n /= i;
}
tot -= tot / i;
}
if (i == 2) {
i = 1;
}
i += 2;
}
if (n > 1) {
tot -= tot / n;
}
return tot;
}
public void getPerfectPowers(int maxExp) {
double upper = Math.pow(10, maxExp);
for (int i = 2; i <= Math.sqrt(upper); i++) {
double fi = i;
double p = fi;
while (true) {
p *= fi;
if (p >= upper) {
break;
}
pps.put((int) p, true);
}
}
}
public Map<Integer, Boolean> getAchilles(int minExp, int maxExp) {
double lower = Math.pow(10, minExp);
double upper = Math.pow(10, maxExp);
Map<Integer, Boolean> achilles = new HashMap<>();
for (int b = 1; b <= (int) Math.cbrt(upper); b++) {
int b3 = b * b * b;
for (int a = 1; a <= (int) Math.sqrt(upper); a++) {
int p = b3 * a * a;
if (p >= (int) upper) {
break;
}
if (p >= (int) lower) {
if (!pps.containsKey(p)) {
achilles.put(p, true);
}
}
}
}
return achilles;
}
public static void main(String[] args) {
AchillesNumbers an = new AchillesNumbers();
int maxDigits = 8;
an.getPerfectPowers(maxDigits);
Map<Integer, Boolean> achillesSet = an.getAchilles(1, 5);
List<Integer> achilles = new ArrayList<>(achillesSet.keySet());
Collections.sort(achilles);
System.out.println("First 50 Achilles numbers:");
for (int i = 0; i < 50; i++) {
System.out.printf("%4d ", achilles.get(i));
if ((i + 1) % 10 == 0) {
System.out.println();
}
}
System.out.println("\nFirst 30 strong Achilles numbers:");
List<Integer> strongAchilles = new ArrayList<>();
int count = 0;
for (int n = 0; count < 30; n++) {
int tot = an.totient(achilles.get(n));
if (achillesSet.containsKey(tot)) {
strongAchilles.add(achilles.get(n));
count++;
}
}
for (int i = 0; i < 30; i++) {
System.out.printf("%5d ", strongAchilles.get(i));
if ((i + 1) % 10 == 0) {
System.out.println();
}
}
System.out.println("\nNumber of Achilles numbers with:");
for (int d = 2; d <= maxDigits; d++) {
int ac = an.getAchilles(d - 1, d).size();
System.out.printf("%2d digits: %d\n", d, ac);
}
}
}

View file

@ -0,0 +1,15 @@
:import std/Combinator .
:import std/Number/Unary U
:import std/Math .
# unary ackermann
ackermann-unary [0 [[U.inc 0 1 (+1u)]] U.inc]
:test (ackermann-unary (+0u) (+0u)) ((+1u))
:test (ackermann-unary (+3u) (+4u)) ((+125u))
# ternary ackermann (lower space complexity)
ackermann-ternary y [[[=?1 ++0 (=?0 (2 --1 (+1)) (2 --1 (2 1 --0)))]]]
:test ((ackermann-ternary (+0) (+0)) =? (+1)) ([[1]])
:test ((ackermann-ternary (+3) (+4)) =? (+125)) ([[1]])

View file

@ -18,9 +18,9 @@ ackermann(m,n)
public program()
{
for(int i:=0, i <= 3, i += 1)
for(int i:=0; i <= 3; i += 1)
{
for(int j := 0, j <= 5, j += 1)
for(int j := 0; j <= 5; j += 1)
{
console.printLine("A(",i,",",j,")=",ackermann(i,j))
}

View file

@ -0,0 +1,9 @@
$ENTRY Go {
= <Prout 'A(3,9) = ' <A 3 9>>;
};
A {
0 s.N = <+ s.N 1>;
s.M 0 = <A <- s.M 1> 1>;
s.M s.N = <A <- s.M 1> <A s.M <- s.N 1>>>;
};

View file

@ -1,4 +1,5 @@
val .isPrime = f .i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 .. .i ^/ 2
val .isPrime = f .i == 2 or .i > 2 and
not any f(.x) .i div .x, pseries 2 .. .i ^/ 2
val .sumDigits = f fold f{+}, s2n toString .i

View file

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
public class AliquotSequenceClassifications
{
private static long ProperDivsSum(long n)
{
return Enumerable.Range(1, (int)(n / 2)).Where(i => n % i == 0).Sum(i => (long)i);
}
public static bool Aliquot(long n, int maxLen, long maxTerm)
{
List<long> s = new List<long>(maxLen) {n};
long newN = n;
while (s.Count <= maxLen && newN < maxTerm)
{
newN = ProperDivsSum(s.Last());
if (s.Contains(newN))
{
if (s[0] == newN)
{
switch (s.Count)
{
case 1:
return Report("Perfect", s);
case 2:
return Report("Amicable", s);
default:
return Report("Sociable of length " + s.Count, s);
}
}
else if (s.Last() == newN)
{
return Report("Aspiring", s);
}
else
{
return Report("Cyclic back to " + newN, s);
}
}
else
{
s.Add(newN);
if (newN == 0)
return Report("Terminating", s);
}
}
return Report("Non-terminating", s);
}
static bool Report(string msg, List<long> result)
{
Console.WriteLine(msg + ": " + string.Join(", ", result));
return false;
}
public static void Main(string[] args)
{
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488
};
Enumerable.Range(1, 10).ToList().ForEach(n => Aliquot(n, 16, 1L << 47));
Console.WriteLine();
foreach (var n in arr)
{
Aliquot(n, 16, 1L << 47);
}
}
}

View file

@ -0,0 +1,65 @@
import java.math.BigDecimal
import java.math.BigInteger
import java.math.MathContext
import java.math.RoundingMode
object CodeKt{
@JvmStatic
fun main(args: Array<String>) {
println("n Integer part")
println("================================================")
for (n in 0..9) {
println(String.format("%d%47s", n, almkvistGiullera(n).toString()))
}
val decimalPlaces = 70
val mathContext = MathContext(decimalPlaces + 1, RoundingMode.HALF_EVEN)
val epsilon = BigDecimal.ONE.divide(BigDecimal.TEN.pow(decimalPlaces))
var previous = BigDecimal.ONE
var sum = BigDecimal.ZERO
var pi = BigDecimal.ZERO
var n = 0
while (pi.subtract(previous).abs().compareTo(epsilon) >= 0) {
val nextTerm = BigDecimal(almkvistGiullera(n)).divide(BigDecimal.TEN.pow(6 * n + 3), mathContext)
sum = sum.add(nextTerm)
previous = pi
n += 1
pi = BigDecimal.ONE.divide(sum, mathContext).sqrt(mathContext)
}
println("\npi to $decimalPlaces decimal places:")
println(pi)
}
private fun almkvistGiullera(aN: Int): BigInteger {
val term1 = factorial(6 * aN) * BigInteger.valueOf(32)
val term2 = BigInteger.valueOf(532L * aN * aN + 126 * aN + 9)
val term3 = factorial(aN).pow(6) * BigInteger.valueOf(3)
return term1 * term2 / term3
}
private fun factorial(aNumber: Int): BigInteger {
var result = BigInteger.ONE
for (i in 2..aNumber) {
result *= BigInteger.valueOf(i.toLong())
}
return result
}
private fun BigDecimal.sqrt(context: MathContext): BigDecimal {
var x = BigDecimal(Math.sqrt(this.toDouble()), context)
if (this == BigDecimal.ZERO) return BigDecimal.ZERO
val two = BigDecimal.valueOf(2)
while (true) {
val y = this.divide(x, context)
x = x.add(y).divide(two, context)
val nextY = this.divide(x, context)
if (y == nextY || y == nextY.add(BigDecimal.ONE.divide(BigDecimal.TEN.pow(context.precision), context))) {
break
}
}
return x
}
}

View file

@ -0,0 +1,44 @@
import java.math.{BigDecimal, BigInteger, MathContext, RoundingMode}
object AlmkvistGiulleraFormula extends App {
println("n Integer part")
println("================================================")
for (n <- 0 to 9) {
val term = almkvistGiullera(n).toString
println(f"$n%1d" + " " * (47 - term.length) + term)
}
val decimalPlaces = 70
val mathContext = new MathContext(decimalPlaces + 1, RoundingMode.HALF_EVEN)
val epsilon = BigDecimal.ONE.divide(BigDecimal.TEN.pow(decimalPlaces))
var previous = BigDecimal.ONE
var sum = BigDecimal.ZERO
var pi = BigDecimal.ZERO
var n = 0
while (pi.subtract(previous).abs.compareTo(epsilon) >= 0) {
val nextTerm = new BigDecimal(almkvistGiullera(n)).divide(BigDecimal.TEN.pow(6 * n + 3))
sum = sum.add(nextTerm)
previous = pi
n += 1
pi = BigDecimal.ONE.divide(sum, mathContext).sqrt(mathContext)
}
println("\npi to " + decimalPlaces + " decimal places:")
println(pi)
def almkvistGiullera(aN: Int): BigInteger = {
val term1 = factorial(6 * aN).multiply(BigInteger.valueOf(32))
val term2 = BigInteger.valueOf(532 * aN * aN + 126 * aN + 9)
val term3 = factorial(aN).pow(6).multiply(BigInteger.valueOf(3))
term1.multiply(term2).divide(term3)
}
def factorial(aNumber: Int): BigInteger = {
var result = BigInteger.ONE
for (i <- 2 to aNumber) {
result = result.multiply(BigInteger.valueOf(i))
}
result
}
}

View file

@ -37,14 +37,14 @@ class AmbValueCollection
constructor new(params object[] args)
{
_combinator := SequentialEnumerator.new(params args)
_combinator := SequentialEnumerator.load(params args)
}
seek(cond)
{
_combinator.reset();
_combinator.seekEach:(v => dispatcher.eval(v,cond))
_combinator.seekEach::(v => dispatcher.eval(v,cond))
}
do(f)
@ -81,12 +81,12 @@ public program()
new object[]{"frog", "elephant", "thing"},
new object[]{"walked", "treaded", "grows"},
new object[]{"slowly", "quickly"})
.seek:(a,b,c,d => joinable(a,b) && joinable(b,c) && joinable(c,d) )
.do:(a,b,c,d) { console.printLine(a," ",b," ",c," ",d) }
.seek::(a,b,c,d => joinable(a,b) && joinable(b,c) && joinable(c,d) )
.do::(a,b,c,d) { console.printLine(a," ",b," ",c," ",d) }
}
catch(Exception e)
{
console.printLine:"AMB is angry"
console.printLine("AMB is angry")
};
console.readChar()

View file

@ -6,30 +6,30 @@ const int N = 20000;
extension op
{
ProperDivisors
= Range.new(1,self / 2).filterBy:(n => self.mod:n == 0);
= Range.new(1,self / 2).filterBy::(n => self.mod(n) == 0);
get AmicablePairs()
{
var divsums := Range
.new(0, self + 1)
.selectBy:(i => i.ProperDivisors.summarize(Integer.new()))
.selectBy::(i => i.ProperDivisors.summarize(Integer.new()))
.toArray();
^ 1.repeatTill(divsums.Length)
.filterBy:(i)
.filterBy::(i)
{
var ii := i;
var sum := divsums[i];
^ (i < sum) && (sum < divsums.Length) && (divsums[sum] == i)
}
.selectBy:(i => new { Item1 = i; Item2 = divsums[i]; })
.selectBy::(i => new { Item1 = i; Item2 = divsums[i]; })
}
}
public program()
{
N.AmicablePairs.forEach:(pair)
N.AmicablePairs.forEach::(pair)
{
console.printLine(pair.Item1, " ", pair.Item2)
}

View file

@ -7,27 +7,27 @@ const int N = 20000;
extension op : IntNumber
{
Enumerator<int> ProperDivisors
= new Range(1,self / 2).filterBy:(int n => self.mod:n == 0);
= new Range(1,self / 2).filterBy::(int n => self.mod(n) == 0);
get AmicablePairs()
{
auto divsums := new List<int>(
cast Enumerator<int>(
new Range(0, self).selectBy:(int i => i.ProperDivisors.summarize(0))));
new Range(0, self).selectBy::(int i => i.ProperDivisors.summarize(0))));
^ new Range(0, divsums.Length)
.filterBy:(int i)
.filterBy::(int i)
{
auto sum := divsums[i];
^ (i < sum) && (sum < divsums.Length) && (divsums[sum] == i)
}
.selectBy:(int i => new Tuple<int,int>(i,divsums[i]));
.selectBy::(int i => new Tuple<int,int>(i,divsums[i]));
}
}
public program()
{
N.AmicablePairs.forEach:(var Tuple<int,int> pair)
N.AmicablePairs.forEach::(var Tuple<int,int> pair)
{
console.printLine(pair.Item1, " ", pair.Item2)
}

View file

@ -7,7 +7,7 @@ const int Limit = 20000;
singleton ProperDivisors
{
Enumerator<int> function(int number)
= Range.new(1, number / 2).filterBy:(int n => number.mod:n == 0);
= Range.new(1, number / 2).filterBy::(int n => number.mod(n) == 0);
}
public sealed AmicablePairs
@ -21,9 +21,9 @@ public sealed AmicablePairs
yieldable Tuple<int, int> next()
{
List<int> divsums := Range.new(0, max + 1).selectBy:(int i => ProperDivisors(i).summarize(0));
List<int> divsums := Range.new(0, max + 1).selectBy::(int i => ProperDivisors(i).summarize(0));
for (int i := 1, i < divsums.Length, i += 1)
for (int i := 1; i < divsums.Length; i += 1)
{
int sum := divsums[i];
if(i < sum && sum <= divsums.Length && divsums[sum] == i) {
@ -38,7 +38,7 @@ public sealed AmicablePairs
public program()
{
auto e := new AmicablePairs(Limit);
for(auto pair := e.next(), pair != nil)
for(auto pair := e.next(); pair != nil)
{
console.printLine(pair.Item1, " ", pair.Item2)
}

View file

@ -2,34 +2,32 @@ $lines
$constant search_limit = 20000
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
rem - return sum of the proper divisors of n
function sumf(n = integer) = integer
var f1, f2, sum = integer
sum = 1
f1 = 2
while (f1 * f1) <= n do
begin
if mod(n, f1) = 0 then
begin
sum = sum + f1
f2 = n / f1
if f2 > f1 then sum = sum + f2
end
f1 = f1 + 1
end
end = sum
rem - main program begins here
var a, b, count = integer
dim integer sumf(search_limit)
print "Searching up to"; search_limit; " for amicable pairs:"
rem - set up the table of proper divisor sums
for a = 1 to search_limit
sumf(a) = 1
next a
for a = 2 to search_limit
b = a + a
while (b > 0) and (b <= search_limit) do
begin
sumf(b) = sumf(b) + a
b = b + a
end
next a
rem - search for pairs using the table
count = 0
for a = 2 to search_limit do
for a = 2 to search_limit
b = sumf(a)
if b > a then
if (b > a) and (b < search_limit) then
if a = sumf(b) then
begin
print using "##### #####"; a; b

View file

@ -0,0 +1,10 @@
# Define the sum of proper divisors function
def sum_of_proper_divisors(n):
return sum(divisors(n)) - n
# Iterate over the desired range
for x in range(1, 20001):
y = sum_of_proper_divisors(x)
if y > x:
if x == sum_of_proper_divisors(y):
print(f"{x} {y}")

View file

@ -19,7 +19,7 @@ public program()
auto dictionary := new Map<string,object>();
File.assign("unixdict.txt").forEachLine:(word)
File.assign("unixdict.txt").forEachLine::(word)
{
var key := word.normalized();
var item := dictionary[key];
@ -29,13 +29,13 @@ public program()
dictionary[key] := item
};
item.append:word
item.append(word)
};
dictionary.Values
.quickSort:(former,later => former.Item2.Length > later.Item2.Length )
.top:20
.forEach:(pair){ console.printLine(pair.Item2) };
.quickSort::(former,later => former.Item2.Length > later.Item2.Length )
.top(20)
.forEach::(pair){ console.printLine(pair.Item2) };
var end := now;

View file

@ -0,0 +1,38 @@
BEGIN # angle difference between 2 bearings - translated from the 11l sample #
PROC wrap = (REAL v, l1, l2 )REAL:
BEGIN
REAL result := v;
WHILE result < l1 DO result +:= 2 * l2 OD;
WHILE result > l2 DO result +:= 2 * l1 OD;
result
END # wrap # ;
PROC get_difference = ( REAL b1, b2 )REAL: wrap( b2 - b1, -180.0, 180.0 );
OP FMT = ( REAL v )STRING:
BEGIN
STRING result := fixed( ABS v, 0, 3 );
IF result[ LWB result ] = "." THEN "0" +=: result FI;
WHILE result[ UPB result ] = "0" DO result := result[ : UPB result - 1 ] OD;
IF result[ UPB result ] = "." THEN result := result[ : UPB result - 1 ] FI;
IF v < 0 THEN "-" ELSE " " FI + result
END # FMT # ;
print( ( FMT get_difference( 20.0, 45.0 ), newline ) );
print( ( FMT get_difference( -45.0, 45.0 ), newline ) );
print( ( FMT get_difference( -85.0, 90.0 ), newline ) );
print( ( FMT get_difference( -95.0, 90.0 ), newline ) );
print( ( FMT get_difference( -45.0, 125.0 ), newline ) );
print( ( FMT get_difference( -45.0, 145.0 ), newline ) );
print( ( FMT get_difference( -45.0, 125.0 ), newline ) );
print( ( FMT get_difference( -45.0, 145.0 ), newline ) );
print( ( FMT get_difference( 29.4803, -88.6381 ), newline ) );
print( ( FMT get_difference( -78.3251, -159.036 ), newline ) );
print( ( newline ) );
print( ( FMT get_difference( -70099.74233810938, 29840.67437876723 ), newline ) );
print( ( FMT get_difference( -165313.6666297357, 33693.9894517456 ), newline ) );
print( ( FMT get_difference( 1174.8380510598456, -154146.66490124757 ), newline ) );
print( ( FMT get_difference( 60175.77306795546, 42213.07192354373 ), newline ) )
END

View file

@ -0,0 +1,64 @@
BEGIN # Angles (geometric), normalization and conversion - translated from the 11l sample #
[]REAL values = ( -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 );
PROC norm = ( REAL x, y )REAL:
BEGIN
INT n = ENTIER ( ABS x / ABS y );
REAL r := x - ( n * y );
r
END # norm # ;
PROC normd = ( REAL x )REAL: norm( x, 360 );
PROC normg = ( REAL x )REAL: norm( x, 400 );
PROC normm = ( REAL x )REAL: norm( x, 6400 );
PROC normr = ( REAL x )REAL: norm( x, 2 * pi );
PROC d2g = ( REAL x )REAL: normd( x ) * 10 / 9;
PROC d2m = ( REAL x )REAL: normd( x ) * 160 / 9;
PROC d2r = ( REAL x )REAL: normd( x ) * pi / 180;
PROC g2d = ( REAL x )REAL: normg( x ) * 9 / 10;
PROC g2m = ( REAL x )REAL: normg( x ) * 16;
PROC g2r = ( REAL x )REAL: normg( x ) * pi / 200;
PROC m2d = ( REAL x )REAL: normm( x ) * 9 / 160;
PROC m2g = ( REAL x )REAL: normm( x ) / 16;
PROC m2r = ( REAL x )REAL: normm( x ) * pi / 3200;
PROC r2d = ( REAL x )REAL: normr( x ) * 180 / pi;
PROC r2g = ( REAL x )REAL: normr( x ) * 200 / pi;
PROC r2m = ( REAL x )REAL: normr( x ) * 3200 / pi;
STRING underline = "----------------------------------------------------------------------------------";
PROC f7d7 = ( REAL v )STRING: fixed( v, -15, 7 );
PROC print values = ( STRING heading, []PROC(REAL)REAL f )VOID:
BEGIN
print( ( heading, newline ) );
print( ( underline, newline ) );
FOR i FROM LWB values TO UPB values DO
REAL v = values[ i ];
print( ( f7d7( v ) ) );
FOR p FROM LWB f TO UPB f DO
print( ( " ", f7d7( f[ p ]( v ) ) ) )
OD;
print( ( newline ) )
OD;
print( ( newline ) )
END # print values # ;
print values( " Degrees Normalized Gradians Mils Radians"
, ( normd, d2g, d2m, d2r )
);
print values( " Gradians Normalized Degrees Mils Radians"
, ( normg, g2d, g2m, g2r )
);
print values( " Mils Normalized Degrees Gradians Radians"
, ( normm, m2d, m2g, m2r )
);
print values( " Radians Normalized Degrees Gradians Mils"
, ( normr, r2d, r2g, r2m )
)
END

View file

@ -0,0 +1,71 @@
begin % Angles (geometric), normalization and conversion %
% - translation of the Algol 68 translation of the 11l sample %
real procedure norm ( real value x, y ) ;
begin
integer n;
n := entier( abs x / abs y );
x - ( n * y )
end norm ;
real procedure normd ( real value x ) ; norm( x, 360 );
real procedure normg ( real value x ) ; norm( x, 400 );
real procedure normm ( real value x ) ; norm( x, 6400 );
real procedure normr ( real value x ) ; norm( x, 2 * pi );
real procedure d2g ( real value x ) ; normd( x ) * 10 / 9;
real procedure d2m ( real value x ) ; normd( x ) * 160 / 9;
real procedure d2r ( real value x ) ; normd( x ) * pi / 180;
real procedure g2d ( real value x ) ; normg( x ) * 9 / 10;
real procedure g2m ( real value x ) ; normg( x ) * 16;
real procedure g2r ( real value x ) ; normg( x ) * pi / 200;
real procedure m2d ( real value x ) ; normm( x ) * 9 / 160;
real procedure m2g ( real value x ) ; normm( x ) / 16;
real procedure m2r ( real value x ) ; normm( x ) * pi / 3200;
real procedure r2d ( real value x ) ; normr( x ) * 180 / pi;
real procedure r2g ( real value x ) ; normr( x ) * 200 / pi;
real procedure r2m ( real value x ) ; normr( x ) * 3200 / pi;
procedure writeonF7d7 ( real value v ) ; writeon( r_format := "A", r_w := 15, r_d := 7, s_w := 0, v );
procedure printValues ( string(82) value heading
; real procedure f1, f2, f3, f4
; real array values( * )
; integer value numberOfValues
) ;
begin
write( heading );
write( "----------------------------------------------------------------------------------" );
for i := 1 until numberOfValues do begin
real v;
v := values( i );
write();
writeonF7d7( v );
writeon( " " ); writeonF7d7( f1( v ) ); writeon( " " ); writeonF7d7( f2( v ) );
writeon( " " ); writeonF7d7( f3( v ) ); writeon( " " ); writeonF7d7( f4( v ) );
end for_i ;
write()
end printValues ;
real array values ( 1 :: 12 );
values( 1 ) := -2; values( 2 ) := -1; values( 3 ) := 0; values( 4 ) := 1; values( 5 ) := 2;
values( 6 ) := 6.2831853; values( 7 ) := 16; values( 8 ) := 57.2957795; values( 9 ) := 359;
values( 10 ) := 399; values( 11 ) := 6399; values( 12 ) := 1000000;
printValues( " Degrees Normalized Gradians Mils Radians"
, normd, d2g, d2m, d2r, values, 12
);
printValues( " Gradians Normalized Degrees Mils Radians"
, normg, g2d, g2m, g2r, values, 12
);
printValues( " Mils Normalized Degrees Gradians Radians"
, normm, m2d, m2g, m2r, values, 12
);
printValues( " Radians Normalized Degrees Gradians Mils"
, normr, r2d, r2g, r2m, values, 12
)
end.

View file

@ -2,36 +2,35 @@ import extensions;
fib(n)
{
if (n < 0)
{ InvalidArgumentException.raise() };
if (n < 0)
{ InvalidArgumentException.raise() };
^ (n)
{
if (n > 1)
{
^ this self(n - 2) + (this self(n - 1))
}
else
{
^ n
}
}(n)
^ (n) {
if (n > 1)
{
^ this self(n - 2) + (this self(n - 1))
}
else
{
^ n
}
}(n)
}
public program()
{
for (int i := -1, i <= 10, i += 1)
{
console.print("fib(",i,")=");
try
{
console.printLine(fib(i))
}
catch(Exception e)
{
console.printLine:"invalid"
}
};
for (int i := -1; i <= 10; i += 1)
{
console.print("fib(",i,")=");
try
{
console.printLine(fib(i))
}
catch(Exception e)
{
console.printLine("invalid")
}
};
console.readChar()
console.readChar()
}

View file

@ -0,0 +1,34 @@
import Foundation
func appendPasswd(
account: String,
passwd: String,
uid: Int,
gid: Int,
bio: String,
home: String,
shell: String
) {
let str = [
account,
passwd,
String(uid),
String(gid),
bio,
home,
shell
].joined(separator: ":").appending("\n")
guard let data = str.data(using: .utf8) else { return }
let url = URL(fileURLWithPath: "./passwd")
do {
if let fileHandle = try? FileHandle(forWritingTo: url) {
fileHandle.seekToEndOfFile()
fileHandle.write(data)
try? fileHandle.close()
} else {
try data.write(to: url)
}
} catch {
print(error)
}
}

View file

@ -0,0 +1,9 @@
appendPasswd(
account: "jsmith",
passwd:"x",
uid: 1001,
gid: 1000,
bio: "Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org",
home: "/home/jsmith",
shell: "/bin/bash"
)

View file

@ -4,5 +4,5 @@ PrintSecondPower(n){ console.writeLine(n * n) }
public program()
{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach(PrintSecondPower)
}

View file

@ -10,6 +10,6 @@ public program()
console.printLine(a," - ",b," = ",a - b);
console.printLine(a," * ",b," = ",a * b);
console.printLine(a," / ",b," = ",a / b); // truncates towards 0
console.printLine(a," % ",b," = ",a.mod:b); // matches sign of first operand
console.printLine(a," % ",b," = ",a.mod(b)); // matches sign of first operand
console.printLine(a," ^ ",b," = ",a ^ b);
}

View file

@ -0,0 +1,20 @@
func lagarias n .
if n < 0
return -lagarias -n
.
if n = 0 or n = 1
return 0
.
f = 2
while n mod f <> 0
f += 1
.
q = n / f
if q = 1
return 1
.
return q * lagarias f + f * lagarias q
.
for n = -99 to 100
write lagarias n & " "
.

View file

@ -0,0 +1,37 @@
import java.math.BigInteger
object ArithmeticDerivative extends App {
println("Arithmetic derivatives for -99 to 100 inclusive:")
for {
n <- -99 to 100
column = n + 100
} print(f"${derivative(BigInteger.valueOf(n))}%4d${if (column % 10 == 0) "\n" else " "}")
println()
val seven = BigInteger.valueOf(7)
for (power <- 1 to 20) {
println(f"D(10^$power%d) / 7 = ${derivative(BigInteger.TEN.pow(power)).divide(seven)}")
}
def derivative(aNumber: BigInteger): BigInteger = {
if (aNumber.signum == -1) {
return derivative(aNumber.negate()).negate()
}
if (aNumber == BigInteger.ZERO || aNumber == BigInteger.ONE) {
return BigInteger.ZERO
}
var divisor = BigInteger.TWO
while (divisor.multiply(divisor).compareTo(aNumber) <= 0) {
if (aNumber.mod(divisor).signum == 0) {
val quotient = aNumber.divide(divisor)
return quotient.multiply(derivative(divisor)).add(divisor.multiply(derivative(quotient)))
}
divisor = divisor.add(BigInteger.ONE)
}
BigInteger.ONE
}
}

View file

@ -0,0 +1,28 @@
function integer Lagarias (N); \Lagarias arithmetic derivative
integer N;
integer F, Q;
function integer SmallPF (J, K); \Smallest prime factor
integer J, K;
return if rem(J/K) = 0 then K else SmallPF(J, K+1);
begin
if N < 0
then return -Lagarias (-N)
else if N = 0 or N = 1
then return 0
else begin
F := SmallPF (N, 2); Q := N / F;
return if Q = 1
then 1
else Q * Lagarias (F) + F * Lagarias (Q)
end;
end \Lagarias\ ;
integer N;
begin
for N:= -99 to 100 do begin
IntOut(0, Lagarias(N) );
if rem(N/10) = 0 then CrLf(0) else ChOut(0, 9\tab\);
end;
end

View file

@ -97,7 +97,7 @@ singleton operatorState
$40 { // (
^ weak self.newBracket().gotoStarting()
}
: {
! {
^ weak self.newToken().append(ch).gotoToken()
}
}
@ -123,8 +123,8 @@ singleton tokenState
$47 { // /
^ weak self.newFraction().gotoOperator()
}
: {
^ weak self.append:ch
! {
^ weak self.append(ch)
}
}
}
@ -140,8 +140,8 @@ singleton startState
$45 { // -
^ weak self.newToken().append("0").newDifference().gotoOperator()
}
: {
^ weak self.newToken().append:ch.gotoToken()
! {
^ weak self.newToken().append(ch).gotoToken()
}
}
}
@ -207,7 +207,7 @@ class Scope
closeBracket()
{
if (_level < 10)
{ InvalidArgumentException.new:"Invalid expression".raise() };
{ InvalidArgumentException.new("Invalid expression").raise() };
_level := _level - 10
}
@ -216,17 +216,17 @@ class Scope
{
if(ch >= $48 && ch < $58)
{
_token.append:ch
_token.append(ch)
}
else
{
InvalidArgumentException.new:"Invalid expression".raise()
InvalidArgumentException.new("Invalid expression").raise()
}
}
append(string s)
{
s.forEach:(ch){ self.append:ch }
s.forEach::(ch){ self.append(ch) }
}
gotoStarting()
@ -316,7 +316,7 @@ class Parser
{
var scope := Scope.new(self);
text.forEach:(ch){ scope.eval:ch };
text.forEach::(ch){ scope.eval(ch) };
^ scope.Number
}
@ -331,11 +331,11 @@ public program()
{
try
{
console.printLine("=",parser.run:text)
console.printLine("=",parser.run(text))
}
catch(Exception e)
{
console.writeLine:"Invalid Expression"
console.writeLine("Invalid Expression")
};
text.clear()

View file

@ -0,0 +1,42 @@
clear all;close all;clc;
testMakePi();
function [a, g] = agm1step(x, y)
a = (x + y) / 2;
g = sqrt(x * y);
end
function [a, g, s, k] = approxPiStep(x, y, z, n)
[a, g] = agm1step(x, y);
k = n + 1;
s = z + 2^(k + 1) * (a^2 - g^2);
end
function pi_approx = approxPi(a, g, s)
pi_approx = 4 * a^2 / (1 - s);
end
function testMakePi()
digits(512); % Set the precision for variable-precision arithmetic
a = vpa(1.0);
g = 1 / sqrt(vpa(2.0));
s = vpa(0.0);
k = 0;
oldPi = vpa(0.0);
% Define a small value as a threshold for convergence
convergence_threshold = vpa(10)^(-digits);
fprintf(' k Error Result\n');
for i = 1:100
[a, g, s, k] = approxPiStep(a, g, s, k);
estPi = approxPi(a, g, s);
if abs(estPi - oldPi) < convergence_threshold
break;
end
oldPi = estPi;
err = abs(vpa(pi) - estPi);
fprintf('%4d%10.1e', i, double(err));
fprintf('%70.60f\n', double(estPi));
end
end

View file

@ -0,0 +1,64 @@
on isArithmetic(n)
if (n < 4) then
if (n < 0) then return {arithmetic:false, composite:missing value}
return {arithmetic:(n mod 2 = 1), composite:false}
end if
set factorSum to 1 + n
set factorCount to 2
set sqrt to n ^ 0.5
set limit to sqrt div 1
if (limit = sqrt) then
set factorSum to factorSum + limit
set factorCount to 3
set limit to limit - 1
end if
repeat with i from 2 to limit
if (n mod i = 0) then
set factorSum to factorSum + i + n div i
set factorCount to factorCount + 2
end if
end repeat
return {arithmetic:(factorSum mod factorCount = 0), composite:(factorCount > 2)}
end isArithmetic
on task()
set output to {linefeed & "The first 100 arithmetic numbers are:"}
set {n, hitCount, compositeCount, pad} to {0, 0, 0, " "}
repeat 10 times
set row to {}
set targetCount to hitCount + 10
repeat until (hitCount = targetCount)
set n to n + 1
tell isArithmetic(n) to if (its arithmetic) then
set hitCount to hitCount + 1
if (its composite) then set compositeCount to compositeCount + 1
set row's end to text -4 thru -1 of (pad & n)
end if
end repeat
set output's end to join(row, "")
end repeat
repeat with targetCount in {1000, 10000, 100000, 1000000}
repeat while (hitCount < targetCount)
set n to n + 1
tell isArithmetic(n) to if (its arithmetic) then
set hitCount to hitCount + 1
if (its composite) then set compositeCount to compositeCount + 1
end if
end repeat
set output's end to (linefeed & "The " & targetCount & "th arithmetic number is " & n) & ¬
(linefeed & "(" & compositeCount & " composite numbers up to here)")
end repeat
return join(output, linefeed)
end task
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
task()

View file

@ -0,0 +1,24 @@
"
The first 100 arithmetic numbers are:
1 3 5 6 7 11 13 14 15 17
19 20 21 22 23 27 29 30 31 33
35 37 38 39 41 42 43 44 45 46
47 49 51 53 54 55 56 57 59 60
61 62 65 66 67 68 69 70 71 73
77 78 79 83 85 86 87 89 91 92
93 94 95 96 97 99 101 102 103 105
107 109 110 111 113 114 115 116 118 119
123 125 126 127 129 131 132 133 134 135
137 138 139 140 141 142 143 145 147 149
The 1000th arithmetic number is 1361
(782 composite numbers up to here)
The 10000th arithmetic number is 12953
(8458 composite numbers up to here)
The 100000th arithmetic number is 125587
(88219 composite numbers up to here)
The 1000000th arithmetic number is 1228663
(905043 composite numbers up to here)"

View file

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
public class ArithmeticNumbers
{
public static void Main(string[] args)
{
int arithmeticCount = 0;
int compositeCount = 0;
int n = 1;
while (arithmeticCount <= 1_000_000)
{
var factors = Factors(n);
int sum = factors.Sum();
if (sum % factors.Count == 0)
{
arithmeticCount++;
if (factors.Count > 2)
{
compositeCount++;
}
if (arithmeticCount <= 100)
{
Console.Write($"{n,3}{(arithmeticCount % 10 == 0 ? "\n" : " ")}");
}
if (new[] { 1_000, 10_000, 100_000, 1_000_000 }.Contains(arithmeticCount))
{
Console.WriteLine();
Console.WriteLine($"{arithmeticCount}th arithmetic number is {n}");
Console.WriteLine($"Number of composite arithmetic numbers <= {n}: {compositeCount}");
}
}
n++;
}
}
private static HashSet<int> Factors(int number)
{
var result = new HashSet<int> { 1, number };
int i = 2;
int j;
while ((j = number / i) >= i)
{
if (i * j == number)
{
result.Add(i);
result.Add(j);
}
i++;
}
return result;
}
}

View file

@ -0,0 +1,27 @@
object ArithmeticNumbers extends App {
var arithmeticCount = 0
var compositeCount = 0
var n = 1
while (arithmeticCount <= 1_000_000) {
val factors = findFactors(n)
val sum = factors.sum
if (sum % factors.size == 0) {
arithmeticCount += 1
if (factors.size > 2) compositeCount += 1
if (arithmeticCount <= 100) {
print(f"$n%3d" + (if (arithmeticCount % 10 == 0) "\n" else " "))
}
if (List(1_000, 10_000, 100_000, 1_000_000).contains(arithmeticCount)) {
println()
println(s"${arithmeticCount}th arithmetic number is $n")
println(s"Number of composite arithmetic numbers <= $n: $compositeCount")
}
}
n += 1
}
def findFactors(number: Int): Set[Int] = {
(1 to number).filter(number % _ == 0).toSet
}
}

View file

@ -0,0 +1,21 @@
Program arrayConcat;
{$mode delphi}
type
TDynArr = array of integer;
var
i: integer;
arr1, arr2, arrSum : TDynArr;
begin
arr1 := [1, 2, 3];
arr2 := [4, 5, 6];
arrSum := arr1 + arr2;
for i in arrSum do
write(i, ' ');
writeln;
end.

View file

@ -0,0 +1 @@
#("apple";"orange")

View file

@ -1,4 +1,4 @@
var array := system'Array.allocate:3;
var array := system'Array.allocate(3);
array[0] := 1;
array[1] := 2;
array[2] := 3;

View file

@ -1,6 +1,6 @@
var dynamicArray := new system'collections'ArrayList();
dynamicArray.append:1;
dynamicArray.append:2;
dynamicArray.append:4;
dynamicArray.append(1);
dynamicArray.append(2);
dynamicArray.append(4);
dynamicArray[2] := 3;

View file

@ -1,8 +1,8 @@
fun main(a: Array<String>) {
fun main() {
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
with(map) {
entries.forEach { println("key = ${it.key}, value = ${it.value}") }
forEach { println("key = ${it.key}, value = ${it.value}") }
keys.forEach { println("key = $it") }
values.forEach { println("value = $it") }
}

View file

@ -0,0 +1,3 @@
Avg{(+)÷}
Avg 1 2 3 4 5 6
3.5

View file

@ -0,0 +1,3 @@
Avg +÷
Avg 1 2 3 4 5 6
3.5

View file

@ -1,4 +0,0 @@
1 2 3 5 7
AMEAN
<< CLEAR DEPTH DUP 'N' STO →LIST ΣLIST N / >>
3.6

View file

@ -0,0 +1,46 @@
BEGIN # Mean time of day mapping time to angles #
# code from the Averages/Mean angle task - angles are in degrees #
PROC mean angle = ([]REAL angles)REAL:
(
INT size = UPB angles - LWB angles + 1;
REAL y part := 0, x part := 0;
FOR i FROM LWB angles TO UPB angles DO
x part +:= cos (angles[i] * pi / 180);
y part +:= sin (angles[i] * pi / 180)
OD;
arc tan2 (y part / size, x part / size) * 180 / pi
);
# end code from the Averages/Mean angle task #
MODE TIME = STRUCT( INT hh, mm, ss );
OP TOANGLE = ( TIME t )REAL: ( ( ( ( ( ss OF t / 60 ) + mm OF t ) / 60 ) + hh OF t ) * 360 ) / 24;
OP TOTIME = ( REAL a )TIME:
BEGIN
REAL t := ( a * 24 ) / 360;
WHILE t < 0 DO t +:= 24 OD;
WHILE t > 24 DO t -:= 24 OD;
INT hh = ENTIER t;
t -:= hh *:= 60;
INT mm = ENTIER t;
INT ss = ENTIER ( ( t - mm ) * 60 );
( hh, mm, ss )
END # TOTIME # ;
PROC mean time = ( []TIME times )TIME:
BEGIN
[ LWB times : UPB times ]REAL angles;
FOR i FROM LWB times TO UPB times DO angles[ i ] := TOANGLE times[ i ] OD;
TOTIME mean angle( angles )
END # mean time # ;
OP SHOW = ( TIME t )VOID:
BEGIN
PROC d2 = ( INT n )STRING: IF n < 10 THEN "0" ELSE "" FI + whole( n, 0 );
print( ( d2( hh OF t ), ":", d2( mm OF t ), ":", d2( ss OF t ) ) )
END # show time # ;
SHOW mean time( ( ( 23,00,17 ), ( 23,40,20 ), ( 00,12,45 ), ( 00,17,19 ) ) )
END

View file

@ -16,7 +16,7 @@ extension op
else
{
var middleIndex := len / 2;
if (len.mod:2 == 0)
if (len.mod(2) == 0)
{
^ (sorted[middleIndex - 1] + sorted[middleIndex]) / 2
}

View file

@ -0,0 +1,47 @@
// Utility to aid easy type conversion
extension Double {
init(withNum v: any Numeric) {
switch v {
case let ii as any BinaryInteger: self.init(ii)
case let ff as any BinaryFloatingPoint: self.init(ff)
default: self.init()
}
}
}
extension Array where Element: Numeric & Comparable {
// Helper func for random element in range
func randomElement(within: Range<Int>) -> Element {
return self[.random(in: within)]
}
mutating func median() -> Double? {
switch self.count {
case 0: return nil
case 1: return Double(withNum: self[0])
case 2: return self.reduce(0, {sum,this in sum + Double(withNum: this)/2.0})
default: break
}
let pTarget: Int = self.count / 2 + 1
let resultSetLen: Int = self.count.isMultiple(of: 2) ? 2 : 1
func divideAndConquer(bottom: Int, top: Int, goal: Int) -> Int {
var (lower,upper) = (bottom,top)
while true {
let splitVal = self.randomElement(within: lower..<upper)
let partitionIndex = self.partition(subrange: lower..<upper, by: {$0 > splitVal})
switch partitionIndex {
case goal: return partitionIndex
case ..<goal: lower = partitionIndex
default: upper = partitionIndex
}
}
}
// Split just above the 'median point'
var pIndex = divideAndConquer(bottom: 0, top: self.count, goal: pTarget)
// Shove the highest 'low' values into the result slice
pIndex = divideAndConquer(bottom: 0, top: pIndex, goal: pIndex - resultSetLen)
// Average the contents of the result slice
return self[pIndex..<pIndex + resultSetLen]
.reduce(0.0, {sum,this in sum + Double(withNum: this)/Double(withNum: resultSetLen)})
}
}

View file

@ -0,0 +1,2 @@
var c: [Double] = (0...100).map {_ in Double.random(in: 0...100)}
print(c.median())

View file

@ -7,31 +7,31 @@ extension op
get Mode()
{
var countMap := Dictionary.new(0);
self.forEach:(item)
self.forEach::(item)
{
countMap[item] := countMap[item] + 1
};
countMap := countMap.Values.sort:(p,n => p > n);
countMap := countMap.Values.sort::(p,n => p > n);
var max := countMap.FirstMember;
^ countMap
.filterBy:(kv => max.equal(kv.Value))
.selectBy:(kv => kv.Key)
.filterBy::(kv => max.equal(kv.Value))
.selectBy::(kv => kv.Key)
.toArray()
}
}
public program()
{
var array1 := new int[]{1, 1, 2, 4, 4};
var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17};
var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"};
var array1 := new int[]{1, 1, 2, 4, 4};
var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17};
var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"};
console
.printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")")
.printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")")
.printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")")
.readChar()
console
.printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")")
.printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")")
.printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")")
.readChar()
}

View file

@ -0,0 +1,14 @@
Double ari = 1, geo = 0, har = 0
Short i, n = 10
for i = 1 to n
ari += i
geo *= i
har += 1 \ i
next
print "ari:", ari \ n
print "geo:", geo^( 1 \ n )
print "har:", n \ har
handleevents

View file

@ -0,0 +1,33 @@
// Utility for easy creation of Double from any Numeric
extension Double {
init(withNum v: any Numeric) {
switch v {
case let ii as any BinaryInteger: self.init(ii)
case let ff as any BinaryFloatingPoint: self.init(ff)
default: self.init()
}
}
}
// Extension for numeric collections
extension Collection where Element: Numeric {
var arithmeticMean: Double {
self.reduce(0.0, {$0 + Double(withNum: $1)})/Double(self.count)
}
var geometricMean: Double {
pow(self.reduce(1.0, {$0 * Double(withNum: $1)}), 1.0/Double(self.count))
}
var harmonicMean: Double {
Double(self.count) / self.reduce(0.0, {$0 + 1.0/Double(withNum:$1)})
}
}
//Usage:
var c: [Int] = (1...10).map {$0}
print(c.arithmeticMean)
print(c.geometricMean)
print(c.harmonicMean)
// output:
// 5.5
// 4.528728688116765
// 3.414171521474055

View file

@ -5,7 +5,7 @@ import system'math;
extension op
{
get RootMeanSquare()
= (self.selectBy:(x => x * x).summarize(Real.new()) / self.Length).sqrt();
= (self.selectBy::(x => x * x).summarize(Real.new()) / self.Length).sqrt();
}
public program()

View file

@ -20,10 +20,10 @@ class SMA
var count := theList.Length;
count =>
0 { ^0.0r }
: {
! {
if (count > thePeriod)
{
theList.removeAt:0;
theList.removeAt(0);
count := thePeriod
};
@ -35,19 +35,21 @@ class SMA
}
}
// --- Program ---
public program()
{
var SMA3 := SMA.new:3;
var SMA5 := SMA.new:5;
var SMA3 := SMA.new(3);
var SMA5 := SMA.new(5);
for (int i := 1, i <= 5, i += 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i);
console.printLine("sma5 + ", i, " = ", SMA5.append:i)
for (int i := 1; i <= 5; i += 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i));
console.printLine("sma5 + ", i, " = ", SMA5.append(i))
};
for (int i := 5, i >= 1, i -= 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i);
console.printLine("sma5 + ", i, " = ", SMA5.append:i)
for (int i := 5; i >= 1; i -= 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i));
console.printLine("sma5 + ", i, " = ", SMA5.append(i))
};
console.readChar()

View file

@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
public class BezierCurveIntersection
{
public static void Main(string[] args)
{
QuadCurve vertical = new QuadCurve(new QuadSpline(-1.0, 0.0, 1.0), new QuadSpline(0.0, 10.0, 0.0));
// QuadCurve vertical represents the Bezier curve having control points (-1, 0), (0, 10) and (1, 0)
QuadCurve horizontal = new QuadCurve(new QuadSpline(2.0, -8.0, 2.0), new QuadSpline(1.0, 2.0, 3.0));
// QuadCurve horizontal represents the Bezier curve having control points (2, 1), (-8, 2) and (2, 3)
Console.WriteLine("The points of intersection are:");
List<Point> intersects = FindIntersects(vertical, horizontal);
foreach (Point intersect in intersects)
{
Console.WriteLine($"( {intersect.X,9:0.000000}, {intersect.Y,9:0.000000} )");
}
}
private static List<Point> FindIntersects(QuadCurve p, QuadCurve q)
{
List<Point> result = new List<Point>();
Stack<QuadCurve> stack = new Stack<QuadCurve>();
stack.Push(p);
stack.Push(q);
while (stack.Count > 0)
{
QuadCurve pp = stack.Pop();
QuadCurve qq = stack.Pop();
List<object> objects = TestIntersection(pp, qq);
bool accepted = (bool)objects[0];
bool excluded = (bool)objects[1];
Point intersect = (Point)objects[2];
if (accepted)
{
if (!SeemsToBeDuplicate(result, intersect))
{
result.Add(intersect);
}
}
else if (!excluded)
{
QuadCurve p0 = new QuadCurve();
QuadCurve q0 = new QuadCurve();
QuadCurve p1 = new QuadCurve();
QuadCurve q1 = new QuadCurve();
SubdivideQuadCurve(pp, 0.5, p0, p1);
SubdivideQuadCurve(qq, 0.5, q0, q1);
stack.Push(p0);
stack.Push(q0);
stack.Push(p0);
stack.Push(q1);
stack.Push(p1);
stack.Push(q0);
stack.Push(p1);
stack.Push(q1);
}
}
return result;
}
private static bool SeemsToBeDuplicate(List<Point> intersects, Point point)
{
foreach (Point intersect in intersects)
{
if (Math.Abs(intersect.X - point.X) < Spacing && Math.Abs(intersect.Y - point.Y) < Spacing)
{
return true;
}
}
return false;
}
private static List<object> TestIntersection(QuadCurve p, QuadCurve q)
{
double pxMin = Math.Min(Math.Min(p.X.C0, p.X.C1), p.X.C2);
double pyMin = Math.Min(Math.Min(p.Y.C0, p.Y.C1), p.Y.C2);
double pxMax = Math.Max(Math.Max(p.X.C0, p.X.C1), p.X.C2);
double pyMax = Math.Max(Math.Max(p.Y.C0, p.Y.C1), p.Y.C2);
double qxMin = Math.Min(Math.Min(q.X.C0, q.X.C1), q.X.C2);
double qyMin = Math.Min(Math.Min(q.Y.C0, q.Y.C1), q.Y.C2);
double qxMax = Math.Max(Math.Max(q.X.C0, q.X.C1), q.X.C2);
double qyMax = Math.Max(Math.Max(q.Y.C0, q.Y.C1), q.Y.C2);
bool accepted = false;
bool excluded = true;
Point intersect = new Point(0.0, 0.0);
if (RectanglesOverlap(pxMin, pyMin, pxMax, pyMax, qxMin, qyMin, qxMax, qyMax))
{
excluded = false;
double xMin = Math.Max(pxMin, qxMin);
double xMax = Math.Min(pxMax, pxMax);
if (xMax - xMin <= Tolerance)
{
double yMin = Math.Max(pyMin, qyMin);
double yMax = Math.Min(pyMax, qyMax);
if (yMax - yMin <= Tolerance)
{
accepted = true;
intersect = new Point(0.5 * (xMin + xMax), 0.5 * (yMin + yMax));
}
}
}
return new List<object> { accepted, excluded, intersect };
}
private static bool RectanglesOverlap(double xa0, double ya0, double xa1, double ya1,
double xb0, double yb0, double xb1, double yb1)
{
return xb0 <= xa1 && xa0 <= xb1 && yb0 <= ya1 && ya0 <= yb1;
}
private static void SubdivideQuadCurve(QuadCurve q, double t, QuadCurve u, QuadCurve v)
{
SubdivideQuadSpline(q.X, t, u.X, v.X);
SubdivideQuadSpline(q.Y, t, u.Y, v.Y);
}
// de Casteljau's algorithm
private static void SubdivideQuadSpline(QuadSpline q, double t, QuadSpline u, QuadSpline v)
{
double s = 1.0 - t;
u.C0 = q.C0;
v.C2 = q.C2;
u.C1 = s * q.C0 + t * q.C1;
v.C1 = s * q.C1 + t * q.C2;
u.C2 = s * u.C1 + t * v.C1;
v.C0 = u.C2;
}
public struct Point
{
public double X { get; }
public double Y { get; }
public Point(double x, double y)
{
X = x;
Y = y;
}
}
public class QuadSpline
{
public double C0 { get; set; }
public double C1 { get; set; }
public double C2 { get; set; }
public QuadSpline(double c0, double c1, double c2)
{
C0 = c0;
C1 = c1;
C2 = c2;
}
public QuadSpline() : this(0.0, 0.0, 0.0) { }
}
public class QuadCurve
{
public QuadSpline X { get; set; }
public QuadSpline Y { get; set; }
public QuadCurve(QuadSpline x, QuadSpline y)
{
X = x;
Y = y;
}
public QuadCurve() : this(new QuadSpline(), new QuadSpline()) { }
}
private const double Tolerance = 0.000_000_1;
private const double Spacing = 10 * Tolerance;
}

View file

@ -5,7 +5,7 @@ public program()
{
var n := 1;
until(n.sqr().mod:1000000 == 269696)
until(n.sqr().mod(1000000) == 269696)
{
n += 1
};

View file

@ -0,0 +1,21 @@
clear all;close all;clc;
BabbageProblem();
function BabbageProblem
% Initialize x to 524, as the square root of 269696 is approximately 519.something
x = 524;
% Loop until the square of x modulo 1000000 equals 269696
while mod(x^2, 1000000) ~= 269696
% If the last digit of x is 4, increment x by 2
% Otherwise, increment x by 8
if mod(x, 10) == 4
x = x + 2;
else
x = x + 8;
end
end
% Display the result
fprintf('The smallest positive integer whose square ends in 269696 = %d\n', x);
end

View file

@ -1,3 +1,4 @@
f
The '''Babylonian spiral''' is a sequence of points in the plane that are created so as to
continuously minimally increase in vector length and minimally bend in vector direction,
while always moving from point to point on strictly integral coordinates. Of the two criteria

View file

@ -0,0 +1,65 @@
% Rosetta Code task rosettacode.org/wiki/Babylonian_spiral
clear all;close all;clc;
% Example usage
fprintf("The first 40 Babylonian spiral points are:\n");
spiral_points = babylonianspiral(40);
for i = 1:size(spiral_points, 1)
fprintf('(%d, %d) ', spiral_points(i, 1), spiral_points(i, 2));
if mod(i, 10) == 0
fprintf('\n');
end
end
% For plotting the spiral (requires MATLAB plotting functions)
spiral_points = babylonianspiral(10000);
plot(spiral_points(:, 1), spiral_points(:, 2), 'LineWidth', 1);
function points = babylonianspiral(nsteps)
% Get the points for a Babylonian spiral of `nsteps` steps. Origin is at (0, 0)
% with first step one unit in the positive direction along the vertical (y) axis.
% See also: oeis.org/A256111, oeis.org/A297346, oeis.org/A297347
persistent squarecache;
if isempty(squarecache)
squarecache = [];
end
if length(squarecache) <= nsteps
squarecache = [squarecache, arrayfun(@(x) x^2, length(squarecache):nsteps)];
end
xydeltas = [0, 0; 0, 1];
deltaSq = 1;
for i = 1:nsteps-2
x = xydeltas(end, 1);
y = xydeltas(end, 2);
theta = atan2(y, x);
candidates = [];
while isempty(candidates)
deltaSq = deltaSq + 1;
for k = 1:length(squarecache)
a = squarecache(k);
if a > deltaSq / 2
break;
end
for j = floor(sqrt(deltaSq)):-1:1
b = squarecache(j+1);
if a + b < deltaSq
break;
end
if a + b == deltaSq
i = k - 1;
candidates = [candidates; i, j; -i, j; i, -j; -i, -j; ...
j, i; -j, i; j, -i; -j, -i];
end
end
end
end
[~, idx] = min(arrayfun(@(n) mod(theta - atan2(candidates(n, 2), candidates(n, 1)), 2*pi), 1:size(candidates, 1)));
xydeltas = [xydeltas; candidates(idx, :)];
end
points = cumsum(xydeltas);
end

View file

@ -1,46 +1,50 @@
// Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order.
// Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order),
// none of which mis-nest.
import system'routines;
import extensions;
import extensions'text;
randomBrackets(len)
{
if (0 == len)
{
^emptyString
}
else
{
var brackets :=
Array.allocate(len).populate:(i => $91)
+
Array.allocate(len).populate:(i => $93);
if (0 == len)
{
^emptyString
}
else
{
var brackets :=
Array.allocate(len).populate::(i => $91)
+
Array.allocate(len).populate::(i => $93);
brackets := brackets.randomize(len * 2);
brackets := brackets.randomize(len * 2);
^ brackets.summarize(new StringWriter()).toString()
}
^ brackets.summarize(new StringWriter()).toString()
}
}
extension op
{
get isBalanced()
{
var counter := new Integer(0);
get isBalanced()
{
var counter := new Integer(0);
self.seekEach:(ch => counter.append((ch==$91).iif(1,-1)) < 0);
self.seekEach::(ch => counter.append((ch==$91).iif(1,-1)) < 0);
^ (0 == counter)
}
^ (0 == counter)
}
}
public program()
{
for(int len := 0, len < 9, len += 1)
{
var str := randomBrackets(len);
for(int len := 0; len < 9; len += 1)
{
var str := randomBrackets(len);
console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced")
};
console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced")
};
console.readChar()
console.readChar()
}

View file

@ -0,0 +1,100 @@
:import std/Combinator .
:import std/Logic .
:import std/Pair .
# negative trit indicating coefficient of (-1)
t⁻ [[[2]]]
# positive trit indicating coefficient of (+1)
t⁺ [[[1]]]
# zero trit indicating coefficient of 0
t⁰ [[[0]]]
# shifts a negative trit into a balanced ternary number
↑⁻‣ [[[[[2 (4 3 2 1 0)]]]]]
# shifts a positive trit into a balanced ternary number
↑⁺‣ [[[[[1 (4 3 2 1 0)]]]]]
# shifts a zero trit into a balanced ternary number
↑⁰‣ [[[[[0 (4 3 2 1 0)]]]]]
# shifts a specified trit into a balanced ternary number
…↑… [[[[[[5 2 1 0 (4 3 2 1 0)]]]]]]
# negates a balanced ternary number
-‣ [[[[[4 3 1 2 0]]]]]
# increments a balanced ternary number (can introduce leading 0s)
++‣ [~(0 z a⁻ a⁺ a⁰)]
z (+0) : (+1)
a⁻ &[[↑⁻1 : ↑⁰1]]
a⁺ &[[↑⁺1 : ↑⁻0]]
a⁰ &[[↑⁰1 : ↑⁺1]]
# decrements a balanced ternary number (can introduce leading 0s)
--‣ [~(0 z a⁻ a⁺ a⁰)]
z (+0) : (-1)
a⁻ &[[↑⁻1 : ↑⁺0]]
a⁺ &[[↑⁺1 : ↑⁰1]]
a⁰ &[[↑⁰1 : ↑⁻1]]
# converts the normal balanced ternary representation into abstract form
→^‣ [0 z a⁻ a⁺ a⁰]
z (+0)
a⁻ [[[[[2 4]]]]]
a⁺ [[[[[1 4]]]]]
a⁰ [[[[[0 4]]]]]
# converts the abstracted balanced ternary representation back to normal
→_‣ y [[0 z a⁻ a⁺ a⁰]]
z (+0)
a⁻ [↑⁻(2 0)]
a⁺ [↑⁺(2 0)]
a⁰ [↑⁰(2 0)]
# adds two balanced ternary numbers (can introduce leading 0s)
…+… [[[c (0 z a⁻ a⁺ a⁰)] 1 →^0]]
b⁻ [1 ↑⁺(3 0 t⁻) ↑⁰(3 0 t⁰) ↑⁻(3 0 t⁰)]
b⁰ [1 ↑ (3 0 t⁰)]
b⁺ [1 ↑⁰(3 0 t⁰) ↑⁻(3 0 t⁺) ↑⁺(3 0 t⁰)]
a⁻ [[[1 (b⁻ 1) b⁻' b⁰ b⁻]]]
b⁻' [1 ↑⁰(3 0 t⁻) ↑⁻(3 0 t⁰) ↑⁺(3 0 t⁻)]
a⁺ [[[1 (b⁺ 1) b⁰ b⁺' b⁺]]]
b⁺' [1 ↑⁺(3 0 t⁰) ↑⁰(3 0 t⁺) ↑⁻(3 0 t⁺)]
a⁰ [[[1 (b⁰ 1) b⁻ b⁺ b⁰]]]
z [[0 --(→_1) ++(→_1) →_1]]
c [[1 0 t⁰]]
# subtracts two balanced ternary numbers (can introduce leading 0s)
…-… [[1 + -0]]
# multiplicates two balanced ternary numbers (can introduce leading 0s)
…⋅… [[1 z a⁻ a⁺ a⁰]]
z (+0)
a⁻ [↑⁰0 - 1]
a⁺ [↑⁰0 + 1]
a⁰ [↑⁰0]
# true if balanced ternary number is zero
=?‣ [0 true [false] [false] i]
# true if two balanced ternary numbers are equal
# → ignores leading 0s!
…=?… [[[0 z a⁻ a⁺ a⁰] 1 →^0]]
z [=?(→_0)]
a⁻ [[0 false [2 0] [false] [false]]]
a⁺ [[0 false [false] [2 0] [false]]]
a⁰ [[0 (1 0) [false] [false] [2 0]]]
main [[0]]
# --- tests/examples ---
:test ((-42) + (-1) =? (-43)) (true)
:test ((+1) + (+2) =? (+3)) (true)
:test ((-42) - (-1) =? (-41)) (true)
:test ((+1) - (+2) =? (-1)) (true)
:test ((-1) ⋅ (+42) =? (-42)) (true)
:test ((+3) ⋅ (+11) =? (+33)) (true)

View file

@ -0,0 +1,10 @@
import Foundation
let input = """
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=
"""
if let decoded = Data(base64Encoded: input),
let str = String(data: decoded, encoding: .utf8) {
print( str )
}

View file

@ -0,0 +1,57 @@
benfords_law();
function benfords_law
% Benford's Law
P = @(d) log10(1 + 1./d);
% Benford function
function counts = benford(numbers)
firstdigit = @(n) floor(mod(n / 10^floor(log10(n)), 10));
counts = zeros(1, 9);
for i = 1:length(numbers)
digit = firstdigit(numbers(i));
if digit ~= 0
counts(digit) = counts(digit) + 1;
end
end
counts = counts ./ sum(counts);
end
% Generate Fibonacci numbers
function fibNums = fibonacci(n)
fibNums = zeros(1, n);
a = 0;
b = 1;
for i = 1:n
c = b;
b = a + b;
a = c;
fibNums(i) = b;
end
end
% Sample
sample = fibonacci(1000);
% Observed and expected frequencies
observed = benford(sample) * 100;
expected = arrayfun(P, 1:9) * 100;
% Table
mytable = [1:9; observed; expected]';
% Plotting
bar(1:9, observed);
hold on;
plot(1:9, expected, 'LineWidth', 2);
hold off;
title("Benford's Law");
xlabel("First Digit");
ylabel("Frequency %");
legend("1000 Fibonacci Numbers", "P(d) = log10(1 + 1/d)");
xticks(1:9);
% Displaying the results
fprintf("Benford's Law\nFrequency of first digit\nin 1000 Fibonacci numbers\n");
disp(table(mytable(:,1),mytable(:,2),mytable(:,3),'VariableNames',{'digit', 'observed(%)', 'expected(%)'}))
end

View file

@ -4,45 +4,45 @@ import extensions'text;
extension op
{
get Shuffled()
{
var original := self.toArray();
var shuffled := self.toArray();
get Shuffled()
{
var original := self.toArray();
var shuffled := self.toArray();
for (int i := 0, i < original.Length, i += 1) {
for (int j := 0, j < original.Length, j += 1) {
if (i != j && original[i] != shuffled[j] && original[j] != shuffled[i])
{
shuffled.exchange(i,j)
}
for (int i := 0; i < original.Length; i += 1) {
for (int j := 0; j < original.Length; j += 1) {
if (i != j && original[i] != shuffled[j] && original[j] != shuffled[i])
{
shuffled.exchange(i,j)
}
};
}
};
^ shuffled.summarize(new StringWriter()).toString()
}
^ shuffled.summarize(new StringWriter()).toString()
}
score(originalText)
{
var shuffled := self.toArray();
var original := originalText.toArray();
int score := 0;
score(originalText)
{
var shuffled := self.toArray();
var original := originalText.toArray();
int score := 0;
for (int i := 0, i < original.Length, i += 1) {
if (original[i] == shuffled[i]) { score += 1 }
};
for (int i := 0; i < original.Length; i += 1) {
if (original[i] == shuffled[i]) { score += 1 }
};
^ score
}
^ score
}
}
public program()
{
new string[]{"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}.forEach:(s)
{
var shuffled_s := s.Shuffled;
new string[]{"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}.forEach::(s)
{
var shuffled_s := s.Shuffled;
console.printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s.score(s),")")
};
console.printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s.score(s),")")
};
console.readChar()
console.readChar()
}

View file

@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Drawing;
public class BifidCipher
{
public static void Main(string[] args)
{
string message1 = "ATTACKATDAWN";
string message2 = "FLEEATONCE";
string message3 = "The invasion will start on the first of January".ToUpper().Replace(" ", "");
Bifid bifid1 = new Bifid(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ");
Bifid bifid2 = new Bifid(5, "BGWKZQPNDSIOAXEFCLUMTHYVR");
RunTest(bifid1, message1);
RunTest(bifid2, message2);
RunTest(bifid2, message1);
RunTest(bifid1, message2);
Bifid bifid3 = new Bifid(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
RunTest(bifid3, message3);
}
private static void RunTest(Bifid bifid, string message)
{
Console.WriteLine("Using Polybius square:");
bifid.Display();
Console.WriteLine("Message: " + message);
string encrypted = bifid.Encrypt(message);
Console.WriteLine("Encrypted: " + encrypted);
string decrypted = bifid.Decrypt(encrypted);
Console.WriteLine("Decrypted: " + decrypted);
Console.WriteLine();
}
}
public class Bifid
{
private char[,] grid;
private Dictionary<char, Point> coordinates = new Dictionary<char, Point>();
public Bifid(int n, string text)
{
if (text.Length != n * n)
{
throw new ArgumentException("Incorrect length of text");
}
grid = new char[n, n];
int row = 0;
int col = 0;
foreach (char ch in text)
{
grid[row, col] = ch;
coordinates[ch] = new Point(row, col);
col += 1;
if (col == n)
{
col = 0;
row += 1;
}
}
if (n == 5)
{
coordinates['J'] = coordinates['I'];
}
}
public string Encrypt(string text)
{
List<int> rowOne = new List<int>();
List<int> rowTwo = new List<int>();
foreach (char ch in text)
{
Point coordinate = coordinates[ch];
rowOne.Add(coordinate.X);
rowTwo.Add(coordinate.Y);
}
rowOne.AddRange(rowTwo);
var result = new System.Text.StringBuilder();
for (int i = 0; i < rowOne.Count - 1; i += 2)
{
result.Append(grid[rowOne[i], rowOne[i + 1]]);
}
return result.ToString();
}
public string Decrypt(string text)
{
List<int> row = new List<int>();
foreach (char ch in text)
{
Point coordinate = coordinates[ch];
row.Add(coordinate.X);
row.Add(coordinate.Y);
}
int middle = row.Count / 2;
List<int> rowOne = row.GetRange(0, middle);
List<int> rowTwo = row.GetRange(middle, row.Count - middle);
var result = new System.Text.StringBuilder();
for (int i = 0; i < middle; i++)
{
result.Append(grid[rowOne[i], rowTwo[i]]);
}
return result.ToString();
}
public void Display()
{
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
Console.Write(grid[i, j] + " ");
}
Console.WriteLine();
}
}
}

View file

@ -0,0 +1,62 @@
clear local fn recode( t as CFStringRef, code as CFStringRef ) as CFStringRef
CFStringRef s = @""
Short i, k, w = sqr( len( code ) )
for i = 0 to len( t ) - 1 step 2
k = intval( mid( t, i, 2 ) ) // Get coordinates of char in code string
k = w * ( k / 10 ) + k mod 10
s = fn StringByAppendingString( s, mid( code, k, 1 ) )
next
end fn = s
//
clear local fn encode( s as CFStringRef, code as CFStringRef ) as CFStringRef
CFStringRef a = @"", b = @"", c
Short i, k, w = sqr( len( code ) )
if w == 5 then s = fn StringByReplacingOccurrencesOfString( s, @"J", @"I" )
print s
for i = 0 to len( s ) - 1
c = mid( s, i, 1 )
k = instr( 0, code, c ) // Put row in one string, column in the other
a = fn StringByAppendingString( a, fn StringWithFormat( @"%d", k / w ) )
b = fn StringByAppendingString( b, fn StringWithFormat( @"%d", k mod w ) )
next
a = fn StringByAppendingString( a, b ) // Combine the two strings, and recode
end fn = fn recode( a, code )
//
clear local fn decode( s as CFStringRef, code as CFStringRef ) as CFStringRef
CFStringRef a = @"", b = @"", c
Short i, k, w = sqr( len( code ) )
for i = 0 to ( len( s ) - 1 )
c = mid( s, i, 1 )
k = instr( 0, code, c ) // Put row and columm in one long string
a = fn StringByAppendingString( a, fn StringWithFormat( @"%d%d", k / w, k mod w ) )
next
for i = 0 to len( a ) / 2 - 1 // Take row from first half of string, column from second
c = fn StringByAppendingString( mid( a, i, 1 ), mid( a, i + len( a ) / 2 , 1 ) )
b = fn StringByAppendingString( b , c ) // Combine, and recode
next
end fn = fn recode( b, code )
//
print fn encode( @"ATTACKATDAWN", @"ABCDEFGHIKLMNOPQRSTUVWXYZ" )
print fn decode( @"DQBDAXDQPDQH", @"ABCDEFGHIKLMNOPQRSTUVWXYZ" )
print
print fn encode( @"FLEEATONCE", @"BGWKZQPDNSIOAXEFCLUMTHYVR" )
print fn decode( @"UAEOLWRINS", @"BGWKZQPDNSIOAXEFCLUMTHYVR" )
print
print fn encode( @"HAPPY40THDAD", @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" )
print fn decode( @"GO31GAGVANJD", @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" )
handleevents

View file

@ -0,0 +1,40 @@
object Bins extends App {
def bins[T](limits: List[T], data: Iterable[T])(implicit ord: Ordering[T]): Array[Int] = {
val result = new Array[Int](limits.size + 1)
for (n <- data) {
val i = limits.search(n)(ord) match {
case scala.collection.Searching.Found(i) => i + 1
case scala.collection.Searching.InsertionPoint(i) => i
}
result(i) += 1
}
result
}
def printBins(limits: List[_], bins: Array[Int]): Unit = {
val n = limits.size
if (n == 0) return
assert(n + 1 == bins.length)
println(f" < ${limits.head}%3s: ${bins(0)}%2d")
for (i <- 1 until n) {
println(f">= ${limits(i - 1)}%3s and < ${limits(i)}%3s: ${bins(i)}%2d")
}
println(f">= ${limits.last}%3s : ${bins(n)}%2d")
}
val limits1 = List(23, 37, 43, 53, 67, 83)
val data1 = List(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)
println("Example 1:")
printBins(limits1, bins(limits1, data1))
val limits2 = List(14, 18, 249, 312, 389, 392, 513, 591, 634, 720)
val data2 = List(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)
println()
println("Example 2:")
printBins(limits2, bins(limits2, data2))
}

View file

@ -1,14 +1,11 @@
func$ bin num .
b$ = ""
if num = 0
b$ = "0"
.
while num > 0
while num > 1
b$ = num mod 2 & b$
num = num div 2
.
return b$
return num & b$
.
print bin 2
print bin 5
print bin 50
print bin 9000

View file

@ -3,7 +3,7 @@ import extensions;
public program()
{
new int[]{5,50,9000}.forEach:(n)
new int[]{5,50,9000}.forEach::(n)
{
console.printLine(n.toString(2))
}

View file

@ -0,0 +1,15 @@
$ENTRY Go {
= <Prout <Binary 5>
<Binary 50>
<Binary 9000>>;
};
Binary {
0 = '0\n';
s.N = <Binary1 s.N> '\n';
};
Binary1 {
0 = ;
s.N, <Divmod s.N 2>: (s.R) s.D = <Binary1 s.R> <Symb s.D>;
};

View file

@ -0,0 +1,6 @@
binstr : Int * -> Str
binstr = \n ->
if n < 2 then
Num.toStr n
else
Str.concat (binstr (Num.shiftRightZfBy n 1)) (Num.toStr (Num.bitwiseAnd n 1))

View file

@ -0,0 +1,18 @@
:import std/Combinator .
:import std/Math .
:import std/List .
:import std/Option .
binary-search [y [[[[[2 <? 3 none go]]]]] (+0) --(∀0) 0]
go [compare-case eq lt gt (2 !! 0) 1] /²(3 + 2)
eq some 0
lt 5 4 --0 2 1
gt 5 ++0 3 2 1
# example using sorted list of x^3, x=[-50,50]
find [[map-or "not found" [0 : (1 !! 0)] (binary-search 0 1)] lst]
lst take (+100) ((\pow (+3)) <$> (iterate ++‣ (-50)))
:test (find (+100)) ("not found")
:test ((head (find (+125))) =? (+55)) ([[1]])
:test ((head (find (+117649))) =? (+99)) ([[1]])

View file

@ -0,0 +1,64 @@
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import kotlin.math.roundToInt
import kotlin.math.sin
fun main() {
val datePairs = listOf(
listOf("1943-03-09", "1972-07-11"),
listOf("1809-01-12", "1863-11-19"),
listOf("1809-02-12", "1863-11-19")
)
for (datePair in datePairs) {
calculateBiorhythms(datePair)
}
}
fun calculateBiorhythms(datePair: List<String>) {
val formatter = DateTimeFormatter.ISO_LOCAL_DATE
val birthDate = LocalDate.parse(datePair[0], formatter)
val targetDate = LocalDate.parse(datePair[1], formatter)
val daysBetween = ChronoUnit.DAYS.between(birthDate, targetDate).toInt()
println("Birth date $birthDate, Target date $targetDate")
println("Days between: $daysBetween")
for (cycle in Cycle.values()) {
val cycleLength = cycle.getLength()
val positionInCycle = daysBetween % cycleLength
val quadrantIndex = 4 * positionInCycle / cycleLength
val percentage = (100 * sin(2 * Math.PI * positionInCycle / cycleLength)).roundToInt()
val description = when {
percentage > 95 -> "peak"
percentage < -95 -> "valley"
Math.abs(percentage) < 5 -> "critical transition"
else -> {
val daysToTransition = (cycleLength * (quadrantIndex + 1) / 4) - positionInCycle
val transitionDate = targetDate.plusDays(daysToTransition.toLong())
val (trend, nextTransition) = cycle.descriptions(quadrantIndex)
"$percentage% ($trend, next $nextTransition $transitionDate)"
}
}
println("${cycle.name} day $positionInCycle: $description")
}
println()
}
enum class Cycle(private val length: Int) {
PHYSICAL(23), EMOTIONAL(28), MENTAL(33);
fun getLength() = length
fun descriptions(index: Int): Pair<String, String> {
val descriptions = listOf(
listOf("up and rising", "peak"),
listOf("up but falling", "transition"),
listOf("down and falling", "valley"),
listOf("down but rising", "transition")
)
return descriptions[index][0] to descriptions[index][1]
}
}

View file

@ -0,0 +1,67 @@
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import scala.collection.JavaConverters._
object Biorythms extends App {
val datePairs = List(
List("1943-03-09", "1972-07-11"),
List("1809-01-12", "1863-11-19"),
List("1809-02-12", "1863-11-19")
)
datePairs.foreach(biorhythms)
def biorhythms(aDatePair: List[String]): Unit = {
val formatter = DateTimeFormatter.ISO_LOCAL_DATE
val birthDate = LocalDate.parse(aDatePair.head, formatter)
val targetDate = LocalDate.parse(aDatePair(1), formatter)
val daysBetween = ChronoUnit.DAYS.between(birthDate, targetDate).toInt
println(s"Birth date $birthDate, Target date $targetDate")
println(s"Days between: $daysBetween")
for (cycle <- Cycle.values) {
val cycleLength = cycle.length
val positionInCycle = daysBetween % cycleLength
val quadrantIndex = 4 * positionInCycle / cycleLength
val percentage = Math.round(100 * Math.sin(2 * Math.PI * positionInCycle / cycleLength)).toInt
val description = if (percentage > 95) {
"peak"
} else if (percentage < -95) {
"valley"
} else if (Math.abs(percentage) < 5) {
"critical transition"
} else {
val daysToTransition = (cycleLength * (quadrantIndex + 1) / 4) - positionInCycle
val transitionDate = targetDate.plusDays(daysToTransition)
val descriptions = cycle.descriptions(quadrantIndex).asScala
val trend = descriptions.head
val nextTransition = descriptions(1)
s"$percentage% ($trend, next $nextTransition $transitionDate)"
}
println(s"${cycle} day $positionInCycle: $description")
}
println()
}
enum Cycle(val length: Int) {
case PHYSICAL extends Cycle(23)
case EMOTIONAL extends Cycle(28)
case MENTAL extends Cycle(33)
def descriptions(number: Int): java.util.List[String] = Cycle.DESCRIPTIONS.get(number)
}
object Cycle {
private val DESCRIPTIONS = java.util.List.of(
java.util.List.of("up and rising", "peak"),
java.util.List.of("up but falling", "transition"),
java.util.List.of("down and falling", "valley"),
java.util.List.of("down but rising", "transition")
)
}
}

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