task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#zkl
zkl
const S_IFCHR=0x2000; fcn S_ISCHR(f){ f.info()[4].bitAnd(S_IFCHR).toBool() } S_ISCHR(File.stdout).println();
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 vmode: equ 0Fh ; Get current video mode time: equ 2Ch ; Get current system time CGALO: equ 4 ; Low-res (4-color) CGA mode MDA: equ 7 ; MDA text mode section .text org 100h mov ah,vmode ; Get current video mode int 10h cmp al,MDA ; If MDA mode, no CGA supported, so stop jne gr_ok ret gr_ok: push ax ; Store old video mode on stack mov ax,CGALO ; Switch to low-resolution CGA mode int 10h mov ah,time ; Get system time int 21h mov di,cx ; Store as RNG seed mov bp,dx genX: call random ; Generate random X coordinate cmp al,200 jae genX mov dh,al ; DH = X genY: call random ; Generate random Y coordinate cmp al,173 jae genY mov dl,al ; DL = Y mloop: mov ah,1 ; Is a key pressed? int 16h jz point ; If not, calculate another point pop ax ; But if so, restore the old video mode cbw int 10h ret ; And quit point: call random ; Generate random direction and al,3 cmp al,3 je point mov ah,al ; Keep direction (for color later) dec al ; Select direction jz d2 dec al jz d3 shr dh,1 ; X /= 2 shr dl,1 ; Y /= 2 jmp plot d2: mov cl,ah ; Keep color in CL mov si,100 ; X = 100+(100-X)/2 xor ax,ax ; (doing intermediate math in 16 bits) mov al,dh neg ax add ax,si shr ax,1 add ax,si mov dh,al mov si,173 ; Y = 173-(173-Y)/2 xor ax,ax ; (doing intermediate math in 16 bits) mov al,dl neg ax add ax,si shr ax,1 neg ax add ax,si mov dl,al mov ah,cl ; Restore color jmp plot d3: mov cl,ah ; Keep color mov si,200 ; X = 200-(200-X)/2 xor ax,ax ; (doing intermediate math in 16 bits) mov al,dh neg ax add ax,si shr ax,1 neg ax add ax,si mov dh,al mov ah,cl ; Restore color shr dl,1 ; Y /= 2 plot: mov cl,dl ; There's a plot function in the BIOS, but it's clc ; behind an INT and needs all the registers, rcr cl,1 ; so we'll do it by hand. sbb bh,bh ; The even rows are at B800:NNNN, odd at BA00, xor bl,bl ; CL (Y coord) is divided by two, and if odd and bh,2 ; we add 2(00) to B8(00) to get the right add bh,0B8h ; segment. mov ds,bx ; We can safely stick it in DS since we're not xor bx,bx ; using any RAM otherwise. 80 bytes per line, mov bl,cl ; so BX=Y * 80, xor ch,ch shl bx,1 shl bx,1 add bx,cx mov cl,4 shl bx,cl mov cl,dh ; and 4 pixels per byte, so BX += Y/4 shr cl,1 shr cl,1 add bx,cx inc ah ; Add 1 to direction to get 1 of 3 colors mov ch,dh ; See which pixel within the byte we're and ch,3 ; looking at mov cl,3 ; Leftmost pixel is in highest bits sub cl,ch shl cl,1 ; Pixels are 2 bits wide shl ah,cl ; Shift AH into place or [bx],ah ; Set the pixel in video memory jmp mloop ; Next pixel random: xchg bx,bp ; Load RNG state into byte-addressable xchg cx,di ; registers. inc bl ; X++ xor bh,ch ; A ^= C xor bh,bl ; A ^= X add cl,bh ; B += A mov al,cl ; C' = B shr al,1 ; C' >>= 1 add al,ch ; C' += C xor al,bh ; C' ^= A mov ch,al ; C = C' xchg bx,bp ; Restore the registers xchg cx,di ret
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#C
C
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h>   int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len);   struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE];   void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; }   void CloseConnection(int handle) { char buf[512]; int j;   FD_CLR(handle, &status);   if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name);   for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); }   void strip(char *buf) { char *x;   x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } }   int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; }   end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0';   strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; }   if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); }   strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; }   void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos;   for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i];   if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j;   while (RelayText(handle)); }     int ChatLoop() { int i, j; FD_ZERO(&status);   FD_SET(tsocket, &status); FD_SET(0, &status);   while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status);   AddConnection(handle); } } } /* Read data, relay to others. */ else { char buf[512]; int b;   b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } /* While 1 */ }   int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0);   tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));   if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; }   if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); }   ChatLoop();   return 0; }
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Factor
Factor
USING: combinators formatting kernel locals math sequences ; IN: rosetta-code.machin   : tan+ ( x y -- z ) [ + ] [ * 1 swap - / ] 2bi ;   :: tan-eval ( coef frac -- x ) { { [ coef zero? ] [ 0 ] } { [ coef neg? ] [ coef neg frac tan-eval neg ] } { [ coef odd? ] [ frac coef 1 - frac tan-eval tan+ ] } [ coef 2/ frac tan-eval dup tan+ ] } cond ;   : tans ( seq -- x ) [ first2 tan-eval ] [ tan+ ] map-reduce ;   : machin ( -- ) { { { 1 1/2 } { 1 1/3 } } { { 2 1/3 } { 1 1/7 } } { { 4 1/5 } { -1 1/239 } } { { 5 1/7 } { 2 3/79 } } { { 5 29/278 } { 7 3/79 } } { { 1 1/2 } { 1 1/5 } { 1 1/8 } } { { 5 1/7 } { 4 1/53 } { 2 1/4443 } } { { 6 1/8 } { 2 1/57 } { 1 1/239 } } { { 8 1/10 } { -1 1/239 } { -4 1/515 } } { { 12 1/18 } { 8 1/57 } { -5 1/239 } } { { 16 1/21 } { 3 1/239 } { 4 3/1042 } } { { 22 1/28 } { 2 1/443 } { -5 1/1393 } { -10 1/11018 } } { { 22 1/38 } { 17 7/601 } { 10 7/8149 } } { { 44 1/57 } { 7 1/239 } { -12 1/682 } { 24 1/12943 } } { { 88 1/172 } { 51 1/239 } { 32 1/682 } { 44 1/5357 } { 68 1/12943 } } { { 88 1/172 } { 51 1/239 } { 32 1/682 } { 44 1/5357 } { 68 1/12944 } } } [ dup tans "tan %u = %u\n" printf ] each ;   MAIN: machin
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#FreeBASIC
FreeBASIC
' version 07-04-2018 ' compile with: fbc -s console   #Include "gmp.bi"   #Define _a(Q) (@(Q)->_mp_num) 'a #Define _b(Q) (@(Q)->_mp_den) 'b   Data "[1, 1, 2] [1, 1, 3]" Data "[2, 1, 3] [1, 1, 7]" Data "[4, 1, 5] [-1, 1, 239]" Data "[5, 1, 7] [2, 3, 79]" Data "[1, 1, 2] [1, 1, 5] [1, 1, 8]" Data "[4, 1, 5] [-1, 1, 70] [1, 1, 99]" Data "[5, 1, 7] [4, 1, 53] [2, 1, 4443]" Data "[6, 1, 8] [2, 1, 57] [1, 1, 239]" Data "[8, 1, 10] [-1, 1, 239] [-4, 1, 515]" Data "[12, 1, 18] [8, 1, 57] [-5, 1, 239]" Data "[16, 1, 21] [3, 1, 239] [4, 3, 1042]" Data "[22, 1, 28] [2, 1, 443] [-5, 1, 1393] [-10, 1, 11018]" Data "[22, 1, 38] [17, 7, 601] [10, 7, 8149]" Data "[44, 1, 57] [7, 1, 239] [-12, 1, 682] [24, 1, 12943]" Data "[88, 1, 172] [51, 1, 239] [32, 1, 682] [44, 1, 5357] [68, 1, 12943]" Data "[88, 1, 172] [51, 1, 239] [32, 1, 682] [44, 1, 5357] [68, 1, 12944]" Data ""   Sub work2do (ByRef a As LongInt, f1 As mpq_ptr)   Dim As LongInt flag = -1   Dim As Mpq_ptr x, y, z x = Allocate(Len(__mpq_struct)) : Mpq_init(x) y = Allocate(Len(__mpq_struct)) : Mpq_init(y) z = Allocate(Len(__mpq_struct)) : Mpq_init(z)   Dim As Mpz_ptr temp1, temp2 temp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp1) temp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp2)   mpq_set(y, f1)   While a > 0 If (a And 1) = 1 Then If flag = -1 Then mpq_set(x, y) flag = 0 Else Mpz_mul(temp1, _a(x), _b(y)) Mpz_mul(temp2, _b(x), _a(y)) Mpz_add(_a(z), temp1, temp2) Mpz_mul(temp1, _b(x), _b(y)) Mpz_mul(temp2, _a(x), _a(y)) Mpz_sub(_b(z), temp1, temp2) mpq_canonicalize(z) mpq_set(x, z) End If End If   Mpz_mul(temp1, _a(y), _b(y)) Mpz_mul(temp2, _b(y), _a(y)) Mpz_add(_a(z), temp1, temp2) Mpz_mul(temp1, _b(y), _b(y)) Mpz_mul(temp2, _a(y), _a(y)) Mpz_sub(_b(z), temp1, temp2) mpq_canonicalize(z) mpq_set(y, z)   a = a Shr 1 Wend   mpq_set(f1, x)   End Sub   ' ------=< MAIN >=------   Dim As Mpq_ptr f1, f2, f3 f1 = Allocate(Len(__mpq_struct)) : Mpq_init(f1) f2 = Allocate(Len(__mpq_struct)) : Mpq_init(f2) f3 = Allocate(Len(__mpq_struct)) : Mpq_init(f3)   Dim As Mpz_ptr temp1, temp2 temp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp1) temp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(temp2)   Dim As mpf_ptr float float = Allocate(Len(__mpf_struct)) : Mpf_init(float)   Dim As LongInt m1, a1, b1, flag, t1, t2, t3, t4 Dim As String s, s1, s2, s3, sign Dim As ZString Ptr zstr   Do   Read s If s = "" Then Exit Do flag = -1   While s <> "" t1 = InStr(s, "[") +1 t2 = InStr(t1, s, ",") +1 t3 = InStr(t2, s, ",") +1 t4 = InStr(t3, s, "]") s1 = Trim(Mid(s, t1, t2 - t1 -1)) s2 = Trim(Mid(s, t2, t3 - t2 -1)) s3 = Trim(Mid(s, t3, t4 - t3)) m1 = Val(s1) a1 = Val(s2) b1 = Val(s3)   sign = IIf(m1 < 0, " - ", " + ") If m1 < 0 Then a1 = -a1 : m1 = Abs(m1) s = Mid(s, t4 +1) Print IIf(flag = 0, sign, ""); IIf(m1 = 1, "", Str(m1)); Print "Atn("; s2; "/" ;s3; ")";   If flag = -1 Then flag = 0 Mpz_set_si(_a(f1), a1) Mpz_set_si(_b(f1), b1) If m1 > 1 Then work2do(m1, f1) Continue While End If   Mpz_set_si(_a(f2), a1) Mpz_set_si(_b(f2), b1) If m1 > 1 Then work2do(m1, f2)   Mpz_mul(temp1, _a(f1), _b(f2)) Mpz_mul(temp2, _b(f1), _a(f2)) Mpz_add(_a(f3), temp1, temp2) Mpz_mul(temp1, _b(f1), _b(f2)) Mpz_mul(temp2, _a(f1), _a(f2)) Mpz_sub(_b(f3), temp1, temp2) mpq_canonicalize(f3) mpq_set(f1, f3)   Wend   If Mpz_cmp_ui(_b(f1), 1) = 0 AndAlso Mpz_cmp(_a(f1), _b(f1)) = 0 Then Print " = 1" Else Mpf_set_q(float, f1) gmp_printf(!" = %.*Ff\n", 15, float) End If   Loop   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#ActionScript
ActionScript
trace(String.fromCharCode(97)); //prints 'a' trace("a".charCodeAt(0));//prints '97'
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Char_Code is begin Put_Line (Character'Val (97) & " =" & Integer'Image (Character'Pos ('a'))); end Char_Code;
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Fantom
Fantom
** ** Cholesky decomposition **   class Main { // create an array of Floats, initialised to 0.0 Float[][] makeArray (Int i, Int j) { Float[][] result := [,] i.times { result.add ([,]) } i.times |Int x| { j.times { result[x].add(0f) } } return result }   // perform the Cholesky decomposition Float[][] cholesky (Float[][] array) { m := array.size Float[][] l := makeArray (m, m) m.times |Int i| { (i+1).times |Int k| { Float sum := (0..<k).toList.reduce (0f) |Float a, Int j -> Float| { a + l[i][j] * l[k][j] } if (i == k) l[i][k] = (array[i][i]-sum).sqrt else l[i][k] = (1.0f / l[k][k]) * (array[i][k] - sum) } } return l }   Void runTest (Float[][] array) { echo (array) echo (cholesky (array)) }   Void main () { runTest ([[25f,15f,-5f],[15f,18f,0f],[-5f,0f,11f]]) runTest ([[18f,22f,54f,42f],[22f,70f,86f,62f],[54f,86f,174f,134f],[42f,62f,134f,106f]]) } }
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Fortran
Fortran
Program Cholesky_decomp ! *************************************************! ! LBH @ ULPGC 06/03/2014 ! Compute the Cholesky decomposition for a matrix A ! after the attached ! http://rosettacode.org/wiki/Cholesky_decomposition ! note that the matrix A is complex since there might ! be values, where the sqrt has complex solutions. ! Here, only the real values are taken into account !*************************************************! implicit none   INTEGER, PARAMETER :: m=3 !rows INTEGER, PARAMETER :: n=3 !cols COMPLEX, DIMENSION(m,n) :: A REAL, DIMENSION(m,n) :: L REAL :: sum1, sum2 INTEGER i,j,k   ! Assign values to the matrix A(1,:)=(/ 25, 15, -5 /) A(2,:)=(/ 15, 18, 0 /) A(3,:)=(/ -5, 0, 11 /) ! !!!!!!!!!!!another example!!!!!!! ! A(1,:) = (/ 18, 22, 54, 42 /) ! A(2,:) = (/ 22, 70, 86, 62 /) ! A(3,:) = (/ 54, 86, 174, 134 /) ! A(4,:) = (/ 42, 62, 134, 106 /)           ! Initialize values L(1,1)=real(sqrt(A(1,1))) L(2,1)=A(2,1)/L(1,1) L(2,2)=real(sqrt(A(2,2)-L(2,1)*L(2,1))) L(3,1)=A(3,1)/L(1,1) ! for greater order than m,n=3 add initial row value ! for instance if m,n=4 then add the following line ! L(4,1)=A(4,1)/L(1,1)           do i=1,n do k=1,i sum1=0 sum2=0 do j=1,k-1 if (i==k) then sum1=sum1+(L(k,j)*L(k,j)) L(k,k)=real(sqrt(A(k,k)-sum1)) elseif (i > k) then sum2=sum2+(L(i,j)*L(k,j)) L(i,k)=(1/L(k,k))*(A(i,k)-sum2) else L(i,k)=0 end if end do end do end do   ! write output do i=1,m print "(3(1X,F6.1))",L(i,:) end do   End program Cholesky_decomp
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#D
D
import std.algorithm.iteration : filter, joiner, map; import std.algorithm.searching : canFind; import std.algorithm.sorting : sort; import std.array : array; import std.datetime.date : Date, Month; import std.stdio : writeln;   void main() { auto choices = [ // Month.jan Date(2019, Month.may, 15), Date(2019, Month.may, 16), Date(2019, Month.may, 19), // unique day (1)   Date(2019, Month.jun, 17), Date(2019, Month.jun, 18), // unique day (1)   Date(2019, Month.jul, 14), Date(2019, Month.jul, 16), // final answer   Date(2019, Month.aug, 14), Date(2019, Month.aug, 15), Date(2019, Month.aug, 17), ];   // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer auto uniqueMonths = choices.sort!"a.day < b.day".groupBy.filter!"a.array.length == 1".joiner.map!"a.month"; // writeln(uniqueMonths.save); auto filter1 = choices.filter!(a => !canFind(uniqueMonths.save, a.month)).array;   // Bernard now knows the answer, so the day must be unique within the remaining choices auto uniqueDays = filter1.sort!"a.day < b.day".groupBy.filter!"a.array.length == 1".joiner.map!"a.day"; auto filter2 = filter1.filter!(a => canFind(uniqueDays.save, a.day)).array;   // Albert knows the answer too, so the month must be unique within the remaining choices auto birthDay = filter2.sort!"a.month < b.month".groupBy.filter!"a.array.length == 1".joiner.front;   // print the result writeln(birthDay.month, " ", birthDay.day); }
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Java
Java
import java.util.Scanner; import java.util.Random;   public class CheckpointSync{ public static void main(String[] args){ System.out.print("Enter number of workers to use: "); Scanner in = new Scanner(System.in); Worker.nWorkers = in.nextInt(); System.out.print("Enter number of tasks to complete:"); runTasks(in.nextInt()); }   /* * Informs that workers started working on the task and * starts running threads. Prior to proceeding with next * task syncs using static Worker.checkpoint() method. */ private static void runTasks(int nTasks){ for(int i = 0; i < nTasks; i++){ System.out.println("Starting task number " + (i+1) + "."); runThreads(); Worker.checkpoint(); } }   /* * Creates a thread for each worker and runs it. */ private static void runThreads(){ for(int i = 0; i < Worker.nWorkers; i ++){ new Thread(new Worker(i+1)).start(); } }   /* * Worker inner static class. */ public static class Worker implements Runnable{ public Worker(int threadID){ this.threadID = threadID; } public void run(){ work(); }   /* * Notifies that thread started running for 100 to 1000 msec. * Once finished increments static counter 'nFinished' * that counts number of workers finished their work. */ private synchronized void work(){ try { int workTime = rgen.nextInt(900) + 100; System.out.println("Worker " + threadID + " will work for " + workTime + " msec."); Thread.sleep(workTime); //work for 'workTime' nFinished++; //increases work finished counter System.out.println("Worker " + threadID + " is ready"); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } }   /* * Used to synchronize Worker threads using 'nFinished' static integer. * Waits (with step of 10 msec) until 'nFinished' equals to 'nWorkers'. * Once they are equal resets 'nFinished' counter. */ public static synchronized void checkpoint(){ while(nFinished != nWorkers){ try { Thread.sleep(10); } catch (InterruptedException e) { System.err.println("Error: thread execution interrupted"); e.printStackTrace(); } } nFinished = 0; }   /* inner class instance variables */ private int threadID;   /* static variables */ private static Random rgen = new Random(); private static int nFinished = 0; public static int nWorkers = 0; } }
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Groovy
Groovy
def emptyList = [] assert emptyList.isEmpty() : "These are not the items you're looking for" assert emptyList.size() == 0 : "Empty list has size 0" assert ! emptyList : "Empty list evaluates as boolean 'false'"   def initializedList = [ 1, "b", java.awt.Color.BLUE ] assert initializedList.size() == 3 assert initializedList : "Non-empty list evaluates as boolean 'true'" assert initializedList[2] == java.awt.Color.BLUE : "referencing a single element (zero-based indexing)" assert initializedList[-1] == java.awt.Color.BLUE : "referencing a single element (reverse indexing of last element)"   def combinedList = initializedList + [ "more stuff", "even more stuff" ] assert combinedList.size() == 5 assert combinedList[1..3] == ["b", java.awt.Color.BLUE, "more stuff"] : "referencing a range of elements"   combinedList << "even more stuff" assert combinedList.size() == 6 assert combinedList[-1..-3] == \ ["even more stuff", "even more stuff", "more stuff"] \  : "reverse referencing last 3 elements" println ([combinedList: combinedList])
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Maxima
Maxima
next_comb(n, p, a) := block( [a: copylist(a), i: p], if a[1] + p = n + 1 then return(und), while a[i] - i >= n - p do i: i - 1, a[i]: a[i] + 1, for j from i + 1 thru p do a[j]: a[j - 1] + 1, a )$   combinations(n, p) := block( [a: makelist(i, i, 1, p), v: [ ]], while a # 'und do (v: endcons(a, v), a: next_comb(n, p, a)), v )$   combinations(5, 3); /* [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]] */
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Retro
Retro
condition [ true statements ] if condition [ false statements ] -if condition [ true statements ] [ false statements ] choose
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#Delphi
Delphi
  program ChineseRemainderTheorem;   uses System.SysUtils, Velthuis.BigIntegers;   function mulInv(a, b: BigInteger): BigInteger; var b0, x0, x1, q, amb, xqx: BigInteger; begin b0 := b; x0 := 0; x1 := 1;   if (b = 1) then exit(1);   while (a > 1) do begin q := a div b; amb := a mod b; a := b; b := amb; xqx := x1 - q * x0; x1 := x0; x0 := xqx; end;   if (x1 < 0) then x1 := x1 + b0;   Result := x1; end;   function chineseRemainder(n: TArray<BigInteger>; a: TArray<BigInteger>) : BigInteger; var i: Integer; prod, p, sm: BigInteger; begin prod := 1;   for i := 0 to High(n) do prod := prod * n[i];   p := 0; sm := 0;   for i := 0 to High(n) do begin p := prod div n[i]; sm := sm + a[i] * mulInv(p, n[i]) * p; end; Result := sm mod prod; end;   var n, a: TArray<BigInteger>;   begin n := [3, 5, 7]; a := [2, 3, 2];   Writeln(chineseRemainder(n, a).ToString); end.
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#jq
jq
def add(stream): reduce stream as $x (0; . + $x);   # input should be an integer def commatize: def digits: tostring | explode | reverse; if . == null then "" elif . < 0 then "-" + ((- .) | commatize) else [foreach digits[] as $d (-1; .+1; # "," is 44 (select(. > 0 and . % 3 == 0)|44), $d)] | reverse | implode end;   def count(stream): reduce stream as $i (0; . + 1);   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   # To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # unordered def proper_divisors: . as $n | if $n > 1 then 1, ( range(2; 1 + (sqrt|floor)) as $i | if ($n % $i) == 0 then $i, (($n / $i) | if . == $i then empty else . end) else empty end) else empty end;   def chowla: if . == 1 then 0 else add(proper_divisors) - 1 end;   # Input: a positive integer def is_chowla_prime: . > 1 and chowla == 0;   # In the interests of green(er) computing ... def chowla_primes($n): 2, range(3; $n; 2) | select(is_chowla_prime);   def report_chowla_primes: reduce range(2; 10000000) as $i (null; if $i | is_chowla_prime then if $i < 10000000 then .[7] += 1 else . end | if $i < 1000000 then .[6] += 1 else . end | if $i < 100000 then .[5] += 1 else . end | if $i < 10000 then .[4] += 1 else . end | if $i < 1000 then .[3] += 1 else . end | if $i < 100 then .[2] += 1 else . end else . end) | (range(2;8) as $i | "10 ^ \($i) \(.[$i]|commatize|lpad(16))") ;   def is_chowla_perfect: (. > 1) and (chowla == . - 1);   def task: " n\("chowla"|lpad(16))", (range(1;38) | "\(lpad(3)): \(chowla|lpad(10))"), "\n n \("Primes < n"|lpad(10))", report_chowla_primes, # "\nPerfect numbers up to 35e6", # (range(1; 35e6) | select(is_chowla_perfect) | commatize) "" ;   task
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Julia
Julia
using Primes, Formatting   function chowla(n) if n < 1 throw("Chowla function argument must be positive") elseif n < 4 return zero(n) else f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end return sum(f) - one(n) - n end end   function countchowlas(n, asperfect=false, verbose=false) count = 0 for i in 2:n # 1 is not prime or perfect so skip chow = chowla(i) if (asperfect && chow == i - 1) || (!asperfect && chow == 0) count += 1 verbose && println("The number $(format(i, commas=true)) is ", asperfect ? "perfect." : "prime.") end end count end   function testchowla() println("The first 37 chowla numbers are:") for i in 1:37 println("Chowla($i) is ", chowla(i)) end for i in [100, 1000, 10000, 100000, 1000000, 10000000] println("The count of the primes up to $(format(i, commas=true)) is $(format(countchowlas(i), commas=true))") end println("The count of perfect numbers up to 35,000,000 is $(countchowlas(35000000, true, true)).") end   testchowla()  
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Prolog
Prolog
church_zero(z).   church_successor(Z, c(Z)).   church_add(z, Z, Z). church_add(c(X), Y, c(Z)) :- church_add(X, Y, Z).   church_multiply(z, _, z). church_multiply(c(X), Y, R) :- church_add(Y, S, R), church_multiply(X, Y, S).   % N ^ M church_power(z, z, z). church_power(N, c(z), N). church_power(N, c(c(Z)), R) :- church_multiply(N, R1, R), church_power(N, c(Z), R1).   int_church(0, z). int_church(I, c(Z)) :- int_church(Is, Z), succ(Is, I).   run :- int_church(3, Three), church_successor(Three, Four), church_add(Three, Four, Sum), church_multiply(Three, Four, Product), church_power(Four, Three, Power43), church_power(Three, Four, Power34),   int_church(ISum, Sum), int_church(IProduct, Product), int_church(IPower43, Power43), int_church(IPower34, Power34),   !, maplist(format('~w '), [ISum, IProduct, IPower43, IPower34]), nl.
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#GLSL
GLSL
  struct Rectangle{ float width; float height; };   Rectangle new(float width,float height){ Rectangle self; self.width = width; self.height = height; return self; }   float area(Rectangle self){ return self.width*self.height; }   float perimeter(Rectangle self){ return (self.width+self.height)*2.0; }  
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Julia
Julia
function closestpair(P::Vector{Vector{T}}) where T <: Number N = length(P) if N < 2 return (Inf, ()) end mindst = norm(P[1] - P[2]) minpts = (P[1], P[2]) for i in 1:N-1, j in i+1:N tmpdst = norm(P[i] - P[j]) if tmpdst < mindst mindst = tmpdst minpts = (P[i], P[j]) end end return mindst, minpts end   closestpair([[0, -0.3], [1., 1.], [1.5, 2], [2, 2], [3, 3]])
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#R
R
  # assign 's' a list of ten functions s <- sapply (1:10, # integers 1..10 become argument 'x' below function (x) { x # force evaluation of promise x function (i=x) i*i # this *function* is the return value })   s[[5]]() # call the fifth function in the list of returned functions [1] 25 # returns vector of length 1 with the value 25  
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Racket
Racket
  #lang racket (define functions (for/list ([i 10]) (λ() (* i i)))) (map (λ(f) (f)) functions)  
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Factor
Factor
USING: accessors combinators combinators.short-circuit formatting io kernel literals locals math math.distances math.functions prettyprint sequences strings ; IN: rosetta-code.circles DEFER: find-circles   ! === Input ====================================================   TUPLE: input p1 p2 r ;   CONSTANT: test-cases { T{ input f { 0.1234 0.9876 } { 0.8765 0.2345 } 2 } T{ input f { 0 2 } { 0 0 } 1 } T{ input f { 0.1234 0.9876 } { 0.1234 0.9876 } 2 } T{ input f { 0.1234 0.9876 } { 0.8765 0.2345 } 0.5 } T{ input f { 0.1234 0.9876 } { 0.1234 0.9876 } 0 } }   ! === Edge case handling =======================================   CONSTANT: infinite "there could be an infinite number of circles."   CONSTANT: too-far "points are too far apart to form circles."   : coincident? ( input -- ? ) [ p1>> ] [ p2>> ] bi = ;   : degenerate? ( input -- ? ) { [ r>> zero? ] [ coincident? ] } 1&& ;   : infinite? ( input -- ? ) { [ r>> zero? not ] [ coincident? ] } 1&& ;   : too-far? ( input -- ? ) [ r>> 2 * ] [ p1>> ] [ p2>> ] tri euclidian-distance < ;   : degenerate ( input -- str ) p1>> [ first ] [ second ] bi "one degenerate circle found at (%.4f, %.4f).\n" sprintf ;   : check-input ( input -- obj ) { { [ dup infinite? ] [ drop infinite ] } { [ dup too-far? ] [ drop too-far ] } { [ dup degenerate? ] [ degenerate ] } [ find-circles ] } cond ;   ! === Program Logic ============================================   :: (circle-coords) ( a b c r q quot -- x ) a r sq q 2 / sq - sqrt b c - * q / quot call ; inline   : circle-coords ( quot -- x y ) [ + ] over [ - ] [ [ call ] dip (circle-coords) ] 2bi@ ; inline   :: find-circles ( input -- circles ) input [ r>> ] [ p1>> ] [ p2>> ] tri  :> ( r p1 p2 ) p1 p2 [ [ first ] [ second ] bi ] bi@  :> ( x1 y1 x2 y2 ) x1 x2 y1 y2 [ + 2 / ] 2bi@  :> ( x3 y3 ) p1 p2 euclidian-distance  :> q [ x3 y1 y2 r q ] [ y3 x2 x1 r q ] [ circle-coords ] bi@ :> ( x w y z ) { x y } { w z } = { { x y } } { { w z } { x y } } ? ;   ! === Output ===================================================   : .point ( seq -- ) [ first ] [ second ] bi "(%.4f, %.4f)" printf ;   : .given ( input -- ) [ r>> ] [ p2>> ] [ p1>> ] tri "Given points " write .point ", " write .point ", and radius %.2f,\n" printf ;   : .one ( seq -- ) first "one circle found at " write .point "." print ;   : .two ( seq -- ) [ first ] [ second ] bi "two circles found at " write .point " and " write .point "." print ;   : .circles ( seq -- ) dup length 1 = [ .one ] [ .two ] if ;   ! === Main word ================================================   : circles-demo ( -- ) test-cases [ dup .given check-input dup string? [ print ] [ .circles ] if nl ] each ;   MAIN: circles-demo
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Delphi
Delphi
  program Chinese_zodiac;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils, System.Math;   type TElements = array of array of char;   TChineseZodiac = record Year: Integer; Yyear: string; Animal: string; Element: string; AnimalChar: char; ElementChar: char; procedure Assign(aYear: Integer); function ToString: string; end;   const animals: TArray<string> = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']; elements: TArray<string> = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']; animalChars: TArray<char> = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']; elementChars: TElements = [['甲', '丙', '戊', '庚', '壬'], ['乙', '丁', '己', '辛', '癸']];     function getYY(year: Integer): string; begin if (year mod 2) = 0 then begin Exit('yang'); end; Exit('yin'); end;   { TChineseZodiac }   procedure TChineseZodiac.Assign(aYear: Integer); var ei, ai: Integer; begin ei := Trunc(Floor((Trunc(aYear - 4.0) mod 10) / 2)); ai := (aYear - 4) mod 12; year := aYear; Element := elements[ei]; Animal := animals[ai]; ElementChar := elementChars[aYear mod 2, ei]; AnimalChar := animalChars[(aYear - 4) mod 12]; Yyear := getYY(aYear); end;   var z: TChineseZodiac; years: TArray<Integer> = [1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017]; year: integer;   function TChineseZodiac.ToString: string; begin Result := Format('%d is the year of the %s %s (%s). %s%s', [year, Element, Animal, Yyear, ElementChar, AnimalChar]); end;   var Outfile: TextFile; Written: Cardinal;   begin SetConsoleOutputCP(CP_UTF8);   AssignFile(Outfile, 'Output.txt', CP_UTF8); Rewrite(Outfile);   for year in years do begin z.Assign(year); Writeln(Outfile, z.ToString); Writeln(z.ToString); end;   CloseFile(Outfile); Readln; end.
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Arturo
Arturo
checkIfExists: function [fpath][ (or? exists? fpath exists? .directory fpath)? -> print [fpath "exists"] -> print [fpath "doesn't exist"] ]   checkIfExists "input.txt" checkIfExists "docs"   checkIfExists "/input.txt" checkIfExists "/docs"
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#AutoHotkey
AutoHotkey
; FileExist() function examples ShowFileExist("input.txt") ShowFileExist("\input.txt") ShowFolderExist("docs") ShowFolderExist("\docs")   ; IfExist/IfNotExist command examples (from documentation) IfExist, D:\ MsgBox, The drive exists. IfExist, D:\Docs\*.txt MsgBox, At least one .txt file exists. IfNotExist, C:\Temp\FlagFile.txt MsgBox, The target file does not exist.   Return   ShowFileExist(file) { If (FileExist(file) && !InStr(FileExist(file), "D")) MsgBox, file: %file% exists. Else MsgBox, file: %file% does NOT exist. Return }   ShowFolderExist(folder) { If InStr(FileExist(folder), "D") MsgBox, folder: %folder% exists. Else MsgBox, folder: %folder% does NOT exist. Return }
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Action.21
Action!
PROC Main() INT x,w=[220],h=[190] BYTE y,i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   x=Rand(w) y=Rand(h) DO i=Rand(3) IF i=0 THEN x==/2 y==/2 ELSEIF i=1 THEN x=w/2+(w/2-x)/2 y=h-(h-y)/2 ELSE x=w-(w-x)/2 y=y/2 FI Plot((320-w)/2+x,191-y) UNTIL CH#$FF OD CH=$FF RETURN
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Amazing_Hopper
Amazing Hopper
  /* Chaos game - JAMBO hopper */   #include <jambo.h>   #define LIMITE 50000   Main ancho = 700, alto = 150 x=0,y=0,color=0 vertice=0, c=0, Let( c := Utf8(Chr(219))) Let(x := Int(Rand(ancho))) Let(y := Int(Rand(alto)))   mid ancho=0, Let( mid ancho:= Div(ancho,2))   i=LIMITE Void(pixeles) Loop Ceil(Rand(3)), Move to (vertice) If( Eq(vertice,1) ) Let(x := Div(x, 2)) Let(y := Div(y, 2)) color=9 Else If( Eq(vertice,2)) Let(x := Add( mid ancho, Div(Sub(mid ancho, x), 2) ) ) Let(y := Sub( alto, Div( Sub(alto, y), 2 ))) color=10 Else Let(x := Sub(ancho, Div( Sub(ancho, x), 2))) Let(y := Div(y, 2)) color=4 End If Set( Int(y), Int(x), color),Apndrow(pixeles) --i Back if (i) is not zero   Set video graph(2) Canvas-term Cls i=1 Iterator(++i, Leq(i,LIMITE), Colorfore([i,3]Get(pixeles)), \ Locate( [i,1]Get(pixeles), [i,2]Get(pixeles) ), Print(c) ); Prnl Pause Set video text End  
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#C.23
C#
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading;   namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder();   public string Name { get; }   public State(string name, TcpClient client) { Name = name; this.client = client; }   public void Add(byte b) { sb.Append((char)b); }   public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } }   class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>();   static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); }   private static void DoListen() { // Listen listen.Start(); Console.WriteLine("Server: Started server");   while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited");   // New thread with client Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } }   private static void DoClient(object client) { // Read data TcpClient tClient = (TcpClient)client;   Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length);   string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); // Kill thread. }   name = Receive(tClient); done = true;   if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done);   connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name));   do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; }   if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true);   Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); }   private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { //ignore continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } }   // Pause Thread.Sleep(100); } while (true); }   private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#GAP
GAP
TanPlus := function(a, b) return (a + b) / (1 - a * b); end;   TanTimes := function(n, a) local x; x := 0; while n > 0 do if IsOddInt(n) then x := TanPlus(x, a); fi; a := TanPlus(a, a); n := QuoInt(n, 2); od; return x; end;   Check := function(a) local x, p; x := 0; for p in a do x := TanPlus(x, SignInt(p[1]) * TanTimes(AbsInt(p[1]), p[2])); od; return x = 1; end;   ForAll([ [[1, 1/2], [1, 1/3]], [[2, 1/3], [1, 1/7]], [[4, 1/5], [-1, 1/239]], [[5, 1/7], [2, 3/79]], [[5, 29/278], [7, 3/79]], [[1, 1/2], [1, 1/5], [1, 1/8]], [[5, 1/7], [4, 1/53], [2, 1/4443]], [[6, 1/8], [2, 1/57], [1, 1/239]], [[8, 1/10], [-1, 1/239], [-4, 1/515]], [[12, 1/18], [8, 1/57], [-5, 1/239]], [[16, 1/21], [3, 1/239], [4, 3/1042]], [[22, 1/28], [2, 1/443], [-5, 1/1393], [-10, 1/11018]], [[22, 1/38], [17, 7/601], [10, 7/8149]], [[44, 1/57], [7, 1/239], [-12, 1/682], [24, 1/12943]], [[88, 1/172], [51, 1/239], [32, 1/682], [44, 1/5357], [68, 1/12943]]], Check);   Check([[88, 1/172], [51, 1/239], [32, 1/682], [44, 1/5357], [68, 1/12944]]);
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Go
Go
package main   import ( "fmt" "math/big" )   type mTerm struct { a, n, d int64 }   var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}}, {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}}, {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}}, {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}}, {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}}, {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}}, {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}}, {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}}, }   func main() { for _, m := range testCases { fmt.Printf("tan %v = %v\n", m, tans(m)) } }   var one = big.NewRat(1, 1)   func tans(m []mTerm) *big.Rat { if len(m) == 1 { return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d)) } half := len(m) / 2 a := tans(m[:half]) b := tans(m[half:]) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }   func tanEval(coef int64, f *big.Rat) *big.Rat { if coef == 1 { return f } if coef < 0 { r := tanEval(-coef, f) return r.Neg(r) } ca := coef / 2 cb := coef - ca a := tanEval(ca, f) b := tanEval(cb, f) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#Aime
Aime
# prints "97" o_integer('a'); o_byte('\n'); # prints "a" o_byte(97); o_byte('\n');
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#ALGOL_68
ALGOL 68
main:( printf(($gl$, ABS "a")); # for ASCII this prints "+97" EBCDIC prints "+129" # printf(($gl$, REPR 97)) # for ASCII this prints "a"; EBCDIC prints "/" # )
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#FreeBASIC
FreeBASIC
' version 18-01-2017 ' compile with: fbc -s console   Sub Cholesky_decomp(array() As Double)   Dim As Integer i, j, k Dim As Double s, l(UBound(array), UBound(array, 2))   For i = 0 To UBound(array) For j = 0 To i s = 0 For k = 0 To j -1 s += l(i, k) * l(j, k) Next If i = j Then l(i, j) = Sqr(array(i, i) - s) Else l(i, j) = (array(i, j) - s) / l(j, j) End If Next Next   For i = 0 To UBound(array) For j = 0 To UBound(array, 2) Swap array(i, j), l(i, j) Next Next   End Sub   Sub Print_(array() As Double)   Dim As Integer i, j   For i = 0 To UBound(array) For j = 0 To UBound(array, 2) Print Using "###.#####";array(i,j); Next Print Next   End Sub   ' ------=< MAIN >=------   Dim m1(2,2) As Double => {{25, 15, -5}, _ {15, 18, 0}, _ {-5, 0, 11}}   Dim m2(3, 3) As Double => {{18, 22, 54, 42}, _ {22, 70, 86, 62}, _ {54, 86, 174, 134}, _ {42, 62, 134, 106}}   Cholesky_decomp(m1()) Print_(m1())   Print Cholesky_decomp(m2()) Print_(m2())   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#F.23
F#
  //Find Cheryl's Birthday. Nigel Galloway: October 23rd., 2018 type Month = |May |June |July |August let fN n= n |> List.filter(fun (_,n)->(List.length n) < 2) |> List.unzip let dates = [(May,15);(May,16);(May,19);(June,17);(June,18);(July,14);(July,16);(August,14);(August,15);(August,17)] let _,n = dates |> List.groupBy snd |> fN let i = n |> List.concat |> List.map fst |> Set.ofList let _,g = dates |> List.filter(fun (n,_)->not (Set.contains n i)) |> List.groupBy snd |> fN let _,e = List.concat g |> List.groupBy fst |> fN printfn "%A" e  
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Julia
Julia
  function runsim(numworkers, runs) for count in 1:runs @sync begin for worker in 1:numworkers @async begin tasktime = rand() sleep(tasktime) println("Worker $worker finished after $tasktime seconds") end end end println("Checkpoint reached for run $count.") end println("Finished all runs.\n") end   const trials = [[3, 2], [4, 1], [2, 5], [7, 6]] for trial in trials runsim(trial[1], trial[2]) end
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Kotlin
Kotlin
// Version 1.2.41   import java.util.Random   val rgen = Random() var nWorkers = 0 var nTasks = 0   class Worker(private val threadID: Int) : Runnable {   @Synchronized override fun run() { try { val workTime = rgen.nextInt(900) + 100L // 100..999 msec. println("Worker $threadID will work for $workTime msec.") Thread.sleep(workTime) nFinished++ println("Worker $threadID is ready") } catch (e: InterruptedException) { println("Error: thread execution interrupted") e.printStackTrace() } }   companion object { private var nFinished = 0   @Synchronized fun checkPoint() { while (nFinished != nWorkers) { try { Thread.sleep(10) } catch (e: InterruptedException) { println("Error: thread execution interrupted") e.printStackTrace() } } nFinished = 0 // reset } } }   fun runTasks() { for (i in 1..nTasks) { println("\nStarting task number $i.") // Create a thread for each worker and run it. for (j in 1..nWorkers) Thread(Worker(j)).start() Worker.checkPoint() // wait for all workers to finish the task } }   fun main(args: Array<String>) { print("Enter number of workers to use: ") nWorkers = readLine()!!.toInt() print("Enter number of tasks to complete: ") nTasks = readLine()!!.toInt() runTasks() }
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Haskell
Haskell
[1, 2, 3, 4, 5]
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Modula-2
Modula-2
  MODULE Combinations; FROM STextIO IMPORT WriteString, WriteLn; FROM SWholeIO IMPORT WriteInt;   CONST MMax = 3; NMax = 5;   VAR Combination: ARRAY [0 .. MMax] OF CARDINAL;   PROCEDURE Generate(M: CARDINAL); VAR N, I: CARDINAL; BEGIN IF (M > MMax) THEN FOR I := 1 TO MMax DO WriteInt(Combination[I], 1); WriteString(' '); END; WriteLn; ELSE FOR N := 1 TO NMax DO IF (M = 1) OR (N > Combination[M - 1]) THEN Combination[M] := N; Generate(M + 1); END END END END Generate;   BEGIN Generate(1); END Combinations.  
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#REXX
REXX
if y then @=6 /* Y must be either 0 or 1 */   if t**2>u then x=y /*simple IF with THEN & ELSE. */ else x=-y   if t**2>u then do j=1 for 10; say prime(j); end /*THEN DO loop.*/ else x=-y /*simple ELSE. */   if z>w+4 then do /*THEN DO group.*/ z=abs(z) say 'z='z end else do; z=0; say 'failed.'; end /*ELSE DO group.*/   if x>y & c*d<sqrt(pz) |, /*this statement is continued [,]*/ substr(abc,4,1)=='~' then if z=0 then call punt else nop /*NOP pairs up IF*/ else if z<0 then z=-y /*alignment helps*/
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#EasyLang
EasyLang
func mul_inv a b . x1 . b0 = b x1 = 1 if b <> 1 while a > 1 q = a div b t = b b = a mod b a = t t = x0 x0 = x1 - q * x0 x1 = t . if x1 < 0 x1 += b0 . . . func remainder . n[] a[] r . prod = 1 sum = 0 for i range len n[] prod *= n[i] . for i range len n[] p = prod / n[i] call mul_inv p n[i] h sum += a[i] * h * p r = sum mod prod . . n[] = [ 3 5 7 ] a[] = [ 2 3 2 ] call remainder n[] a[] h print h
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#EchoLisp
EchoLisp
  (lib 'math) math.lib v1.10 ® EchoLisp Lib: math.lib loaded.   (crt-solve '(2 3 2) '(3 5 7)) → 23 (crt-solve '(2 3 2) '(7 1005 15)) 💥 error: mod[i] must be co-primes : assertion failed : 1005  
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Kotlin
Kotlin
// Version 1.3.21   fun chowla(n: Int): Int { if (n < 1) throw RuntimeException("argument must be a positive integer") var sum = 0 var i = 2 while (i * i <= n) { if (n % i == 0) { val j = n / i sum += if (i == j) i else i + j } i++ } return sum }   fun sieve(limit: Int): BooleanArray { // True denotes composite, false denotes prime. // Only interested in odd numbers >= 3 val c = BooleanArray(limit) for (i in 3 until limit / 3 step 2) { if (!c[i] && chowla(i) == 0) { for (j in 3 * i until limit step 2 * i) c[j] = true } } return c }   fun main() { for (i in 1..37) { System.out.printf("chowla(%2d) = %d\n", i, chowla(i)) } println()   var count = 1 var limit = 10_000_000 val c = sieve(limit) var power = 100 for (i in 3 until limit step 2) { if (!c[i]) count++ if (i == power - 1) { System.out.printf("Count of primes up to %,-10d = %,d\n", power, count) power *= 10 } }   println() count = 0 limit = 35_000_000 var i = 2 while (true) { val p = (1 shl (i - 1)) * ((1 shl i) - 1) // perfect numbers must be of this form if (p > limit) break if (chowla(p) == p - 1) { System.out.printf("%,d is a perfect number\n", p) count++ } i++ } println("There are $count perfect numbers <= 35,000,000") }
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Python
Python
'''Church numerals'''   from itertools import repeat from functools import reduce     # ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------   def churchZero(): '''The identity function. No applications of any supplied f to its argument. ''' return lambda f: identity     def churchSucc(cn): '''The successor of a given Church numeral. One additional application of f. Equivalent to the arithmetic addition of one. ''' return lambda f: compose(f)(cn(f))     def churchAdd(m): '''The arithmetic sum of two Church numerals.''' return lambda n: lambda f: compose(m(f))(n(f))     def churchMult(m): '''The arithmetic product of two Church numerals.''' return lambda n: compose(m)(n)     def churchExp(m): '''Exponentiation of Church numerals. m^n''' return lambda n: n(m)     def churchFromInt(n): '''The Church numeral equivalent of a given integer. ''' return lambda f: ( foldl (compose) (identity) (replicate(n)(f)) )     # OR, alternatively: def churchFromInt_(n): '''The Church numeral equivalent of a given integer, by explicit recursion. ''' if 0 == n: return churchZero() else: return churchSucc(churchFromInt(n - 1))     def intFromChurch(cn): '''The integer equivalent of a given Church numeral. ''' return cn(succ)(0)     # ------------------------- TEST ------------------------- # main :: IO () def main(): 'Tests'   cThree = churchFromInt(3) cFour = churchFromInt(4)   print(list(map(intFromChurch, [ churchAdd(cThree)(cFour), churchMult(cThree)(cFour), churchExp(cFour)(cThree), churchExp(cThree)(cFour), ])))     # ------------------ GENERIC FUNCTIONS -------------------   # compose (flip (.)) :: (a -> b) -> (b -> c) -> a -> c def compose(f): '''A left to right composition of two functions f and g''' return lambda g: lambda x: g(f(x))     # foldl :: (a -> b -> a) -> a -> [b] -> a def foldl(f): '''Left to right reduction of a list, using the binary operator f, and starting with an initial value a. ''' def go(acc, xs): return reduce(lambda a, x: f(a)(x), xs, acc) return lambda acc: lambda xs: go(acc, xs)     # identity :: a -> a def identity(x): '''The identity function.''' return x     # replicate :: Int -> a -> [a] def replicate(n): '''A list of length n in which every element has the value x. ''' return lambda x: repeat(x, n)     # succ :: Enum a => a -> a def succ(x): '''The successor of a value. For numeric types, (1 +). ''' return 1 + x if isinstance(x, int) else ( chr(1 + ord(x)) )     if __name__ == '__main__': main()
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Go
Go
package main   import "fmt"   // a basic "class." // In quotes because Go does not use that term or have that exact concept. // Go simply has types that can have methods. type picnicBasket struct { nServings int // "instance variables" corkscrew bool }   // a method (yes, Go uses the word method!) func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew }   // a "constructor." // Also in quotes as Go does not have that exact mechanism as part of the // language. A common idiom however, is a function with the name new<Type>, // that returns a new object of the type, fully initialized as needed and // ready to use. It makes sense to use this kind of constructor function when // non-trivial initialization is needed. In cases where the concise syntax // shown is sufficient however, it is not idiomatic to define the function. // Rather, code that needs a new object would simply contain &picnicBasket{... func newPicnicBasket(nPeople int) *picnicBasket { // arbitrary code to interpret arguments, check resources, etc. // ... // return data new object. // this is the concise syntax. there are other ways of doing it. return &picnicBasket{nPeople, nPeople > 0} }   // how to instantiate it. func main() { var pb picnicBasket // create on stack (probably) pbl := picnicBasket{} // equivalent to above pbp := &picnicBasket{} // create on heap. pbp is pointer to object. pbn := new(picnicBasket) // equivalent to above forTwo := newPicnicBasket(2) // using constructor // equivalent to above. field names, called keys, are optional. forToo := &picnicBasket{nServings: 2, corkscrew: true}   fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Kotlin
Kotlin
// version 1.1.2   typealias Point = Pair<Double, Double>   fun distance(p1: Point, p2: Point) = Math.hypot(p1.first- p2.first, p1.second - p2.second)   fun bruteForceClosestPair(p: List<Point>): Pair<Double, Pair<Point, Point>> { val n = p.size if (n < 2) throw IllegalArgumentException("Must be at least two points") var minPoints = p[0] to p[1] var minDistance = distance(p[0], p[1]) for (i in 0 until n - 1) for (j in i + 1 until n) { val dist = distance(p[i], p[j]) if (dist < minDistance) { minDistance = dist minPoints = p[i] to p[j] } } return minDistance to Pair(minPoints.first, minPoints.second) }   fun optimizedClosestPair(xP: List<Point>, yP: List<Point>): Pair<Double, Pair<Point, Point>> { val n = xP.size if (n <= 3) return bruteForceClosestPair(xP) val xL = xP.take(n / 2) val xR = xP.drop(n / 2) val xm = xP[n / 2 - 1].first val yL = yP.filter { it.first <= xm } val yR = yP.filter { it.first > xm } val (dL, pairL) = optimizedClosestPair(xL, yL) val (dR, pairR) = optimizedClosestPair(xR, yR) var dmin = dR var pairMin = pairR if (dL < dR) { dmin = dL pairMin = pairL } val yS = yP.filter { Math.abs(xm - it.first) < dmin } val nS = yS.size var closest = dmin var closestPair = pairMin for (i in 0 until nS - 1) { var k = i + 1 while (k < nS && (yS[k].second - yS[i].second < dmin)) { val dist = distance(yS[k], yS[i]) if (dist < closest) { closest = dist closestPair = Pair(yS[k], yS[i]) } k++ } } return closest to closestPair }     fun main(args: Array<String>) { val points = listOf( listOf( 5.0 to 9.0, 9.0 to 3.0, 2.0 to 0.0, 8.0 to 4.0, 7.0 to 4.0, 9.0 to 10.0, 1.0 to 9.0, 8.0 to 2.0, 0.0 to 10.0, 9.0 to 6.0 ), listOf( 0.654682 to 0.925557, 0.409382 to 0.619391, 0.891663 to 0.888594, 0.716629 to 0.996200, 0.477721 to 0.946355, 0.925092 to 0.818220, 0.624291 to 0.142924, 0.211332 to 0.221507, 0.293786 to 0.691701, 0.839186 to 0.728260 ) ) for (p in points) { val (dist, pair) = bruteForceClosestPair(p) println("Closest pair (brute force) is ${pair.first} and ${pair.second}, distance $dist") val xP = p.sortedBy { it.first } val yP = p.sortedBy { it.second } val (dist2, pair2) = optimizedClosestPair(xP, yP) println("Closest pair (optimized) is ${pair2.first} and ${pair2.second}, distance $dist2\n") } }
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Raku
Raku
my @c = gather for ^10 -> $i { take { $i * $i } }   .().say for @c.pick(*); # call them in random order
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Red
Red
  funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]]   >> funs/7 == 49  
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Fortran
Fortran
  ! Implemented by Anant Dixit (Nov. 2014) ! Transpose elements in find_center to obtain correct results. R.N. McLean (Dec 2017) program circles implicit none double precision :: P1(2), P2(2), R   P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.8765d0,0.2345d0/) R = 2.0d0 call print_centers(P1,P2,R)   P1 = (/0.0d0, 2.0d0/) P2 = (/0.0d0,0.0d0/) R = 1.0d0 call print_centers(P1,P2,R)   P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.1234d0, 0.9876d0/) R = 2.0d0 call print_centers(P1,P2,R)   P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.8765d0, 0.2345d0/) R = 0.5d0 call print_centers(P1,P2,R)   P1 = (/0.1234d0, 0.9876d0/) P2 = (/0.1234d0, 0.9876d0/) R = 0.0d0 call print_centers(P1,P2,R) end program circles   subroutine print_centers(P1,P2,R) implicit none double precision :: P1(2), P2(2), R, Center(2,2) integer :: Res call test_inputs(P1,P2,R,Res) write(*,*) write(*,'(A10,F7.4,A1,F7.4)') 'Point1  : ', P1(1), ' ', P1(2) write(*,'(A10,F7.4,A1,F7.4)') 'Point2  : ', P2(1), ' ', P2(2) write(*,'(A10,F7.4)') 'Radius  : ', R if(Res.eq.1) then write(*,*) 'Same point because P1=P2 and r=0.' elseif(Res.eq.2) then write(*,*) 'No circles can be drawn because r=0.' elseif(Res.eq.3) then write(*,*) 'Infinite circles because P1=P2 for non-zero radius.' elseif(Res.eq.4) then write(*,*) 'No circles with given r can be drawn because points are far apart.' elseif(Res.eq.0) then call find_center(P1,P2,R,Center) if(Center(1,1).eq.Center(2,1) .and. Center(1,2).eq.Center(2,2)) then write(*,*) 'Points lie on the diameter. A single circle can be drawn.' write(*,'(A10,F7.4,A1,F7.4)') 'Center  : ', Center(1,1), ' ', Center(1,2) else write(*,*) 'Two distinct circles found.' write(*,'(A10,F7.4,A1,F7.4)') 'Center1 : ', Center(1,1), ' ', Center(1,2) write(*,'(A10,F7.4,A1,F7.4)') 'Center2 : ', Center(2,1), ' ', Center(2,2) end if elseif(Res.lt.0) then write(*,*) 'Incorrect value for r.' end if write(*,*) end subroutine print_centers   subroutine test_inputs(P1,P2,R,Res) implicit none double precision :: P1(2), P2(2), R, dist integer :: Res if(R.lt.0.0d0) then Res = -1 return elseif(R.eq.0.0d0 .and. P1(1).eq.P2(1) .and. P1(2).eq.P2(2)) then Res = 1 return elseif(R.eq.0.0d0) then Res = 2 return elseif(P1(1).eq.P2(1) .and. P1(2).eq.P2(2)) then Res = 3 return else dist = sqrt( (P1(1)-P2(1))**2 + (P1(2)-P2(2))**2 ) if(dist.gt.2.0d0*R) then Res = 4 return else Res = 0 return end if end if end subroutine test_inputs   subroutine find_center(P1,P2,R,Center) implicit none double precision :: P1(2), P2(2), MP(2), Center(2,2), R, dm, dd MP = (P1 + P2)/2.0d0 dm = sqrt((P1(1) - P2(1))**2 + (P1(2) - P2(2))**2) dd = sqrt(R**2 - (dm/2.0d0)**2) Center(1,1) = MP(1) - dd*(P2(2) - P1(2))/dm Center(1,2) = MP(2) + dd*(P2(1) - P1(1))/dm   Center(2,1) = MP(1) + dd*(P2(2) - P1(2))/dm Center(2,2) = MP(2) - dd*(P2(1) - P1(1))/dm end subroutine find_center
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Excel
Excel
CNZODIAC =LAMBDA(y, APPENDCOLS( APPENDCOLS( APPENDCOLS( CNYEARNAME(y) )( CNYEARELEMENT(y) ) )( CNYEARANIMAL(y) ) )( CNYEARYINYANG(y) ) )     CNYEARANIMAL =LAMBDA(y, LET( shengxiao, { "鼠","shǔ","rat"; "牛","niú","ox"; "虎","hǔ","tiger"; "兔","tù","rabbit"; "龍","lóng","dragon"; "蛇","shé","snake"; "馬","mǎ","horse"; "羊","yáng","goat"; "猴","hóu","monkey"; "鸡","jī","rooster"; "狗","gǒu","dog"; "豬","zhū","pig" },   iYear, y - 4, iBranch, 1 + MOD(iYear, 12),   TRANSPOSE( INDEX(shengxiao, iBranch) ) ) )     CNYEARELEMENT =LAMBDA(y, LET( wuxing, { "木","mù","wood"; "火","huǒ","fire"; "土","tǔ","earth"; "金","jīn","metal"; "水","shuǐ","water" },   iYear, y - 4, iStem, MOD(iYear, 10),   TRANSPOSE( INDEX( wuxing, 1 + QUOTIENT( iStem, 2 ) ) ) ) )     CNYEARNAME =LAMBDA(y, LET( tiangan, { "甲","jiă"; "乙","yĭ"; "丙","bĭng"; "丁","dīng"; "戊","wù"; "己","jĭ"; "庚","gēng"; "辛","xīn"; "壬","rén"; "癸","gŭi" },   dizhi, { "子","zĭ"; "丑","chŏu"; "寅","yín"; "卯","măo"; "辰","chén"; "巳","sì"; "午","wŭ"; "未","wèi"; "申","shēn"; "酉","yŏu"; "戌","xū"; "亥","hài" },     iYear, y - 4, iStem, 1 + MOD(iYear, 10), iBranch, 1 + MOD(iYear, 12), iIndex, 1 + MOD(iYear, 60),   stem, INDEX(tiangan, iStem), branch, INDEX(dizhi, iBranch),   APPENDROWS( APPENDROWS( CONCAT(INDEX(stem, 1), INDEX(branch, 1)) )( CONCAT(INDEX(stem, 2), INDEX(branch, 2)) ) )(iIndex & "/60") ) )     CNYEARYINYANG =LAMBDA(y, LET( yinyang, { "阳","yáng", "bright"; "阴","yīn", "dark" },   TRANSPOSE( INDEX( yinyang, 1 + MOD(y - 4, 2) ) ) ) )
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#AWK
AWK
@load "filefuncs"   function exists(name ,fd) { if ( stat(name, fd) == -1) print name " doesn't exist" else print name " exists" } BEGIN { exists("input.txt") exists("/input.txt") exists("docs") exists("/docs") }
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Axe
Axe
If GetCalc("appvINPUT") Disp "EXISTS",i Else Disp "DOES NOT EXIST",i End
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#BASIC
BASIC
10 SCREEN 1 20 X = INT(RND(0) * 200) 30 Y = INT(RND(0) * 173) 40 FOR I=1 TO 20000 50 V = INT(RND(0) * 3) + 1 60 ON V GOTO 70,100,130 70 X = X/2 80 Y = Y/2 90 GOTO 150 100 X = 100 + (100-X)/2 110 Y = 173 - (173-Y)/2 120 GOTO 150 130 X = 200 - (200-X)/2 140 Y = Y/2 150 PSET X,Y,V 160 NEXT I
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#C
C
  #include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #include<time.h>   #define pi M_PI   int main(){   time_t t; double side, vertices[3][3],seedX,seedY,windowSide; int i,iter,choice;   printf("Enter triangle side length : "); scanf("%lf",&side);   printf("Enter number of iterations : "); scanf("%d",&iter);   windowSide = 10 + 2*side;   initwindow(windowSide,windowSide,"Sierpinski Chaos");   for(i=0;i<3;i++){ vertices[i][0] = windowSide/2 + side*cos(i*2*pi/3); vertices[i][1] = windowSide/2 + side*sin(i*2*pi/3); putpixel(vertices[i][0],vertices[i][1],15); }   srand((unsigned)time(&t));   seedX = rand()%(int)(vertices[0][0]/2 + (vertices[1][0] + vertices[2][0])/4); seedY = rand()%(int)(vertices[0][1]/2 + (vertices[1][1] + vertices[2][1])/4);   putpixel(seedX,seedY,15);   for(i=0;i<iter;i++){ choice = rand()%3;   seedX = (seedX + vertices[choice][0])/2; seedY = (seedY + vertices[choice][1])/2;   putpixel(seedX,seedY,15); }   getch();   closegraph();   return 0; }
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#CoffeeScript
CoffeeScript
  net = require("net") sys = require("sys") EventEmitter = require("events").EventEmitter   isNicknameLegal = (nickname) -> return false unless nickname.replace(/[A-Za-z0-9]*/, "") is "" for used_nick of @chatters return false if used_nick is nickname true   class ChatServer constructor: -> @chatters = {} @server = net.createServer @handleConnection @server.listen 1212, "localhost"   handleConnection: (connection) => console.log "Incoming connection from " + connection.remoteAddress connection.setEncoding "utf8" chatter = new Chatter(connection, this) chatter.on "chat", @handleChat chatter.on "join", @handleJoin chatter.on "leave", @handleLeave   handleChat: (chatter, message) => @sendToEveryChatterExcept chatter, chatter.nickname + ": " + message   handleJoin: (chatter) => console.log chatter.nickname + " has joined the chat." @sendToEveryChatter chatter.nickname + " has joined the chat." @addChatter chatter   handleLeave: (chatter) => console.log chatter.nickname + " has left the chat." @removeChatter chatter @sendToEveryChatter chatter.nickname + " has left the chat."   addChatter: (chatter) => @chatters[chatter.nickname] = chatter   removeChatter: (chatter) => delete @chatters[chatter.nickname]   sendToEveryChatter: (data) => for nickname of @chatters @chatters[nickname].send data   sendToEveryChatterExcept: (chatter, data) => for nickname of @chatters @chatters[nickname].send data unless nickname is chatter.nickname     class Chatter extends EventEmitter constructor: (socket, server) -> EventEmitter.call this @socket = socket @server = server @nickname = "" @lineBuffer = new SocketLineBuffer(socket) @lineBuffer.on "line", @handleNickname @socket.on "close", @handleDisconnect @send "Welcome! What is your nickname?"   handleNickname: (nickname) => if isNicknameLegal(nickname) @nickname = nickname @lineBuffer.removeAllListeners "line" @lineBuffer.on "line", @handleChat @send "Welcome to the chat, " + nickname + "!" @emit "join", this else @send "Sorry, but that nickname is not legal or is already in use!" @send "What is your nickname?"   handleChat: (line) => @emit "chat", this, line   handleDisconnect: => @emit "leave", this   send: (data) => @socket.write data + "\r\n"     class SocketLineBuffer extends EventEmitter constructor: (socket) -> EventEmitter.call this @socket = socket @buffer = "" @socket.on "data", @handleData   handleData: (data) => console.log "Handling data", data i = 0   while i < data.length char = data.charAt(i) @buffer += char if char is "\n" @buffer = @buffer.replace("\r\n", "") @buffer = @buffer.replace("\n", "") @emit "line", @buffer console.log "incoming line: #{@buffer}" @buffer = "" i++   server = new ChatServer()  
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Haskell
Haskell
import Data.Ratio import Data.List (foldl')   tanPlus :: Fractional a => a -> a -> a tanPlus a b = (a + b) / (1 - a * b)   tanEval :: (Integral a, Fractional b) => (a, b) -> b tanEval (0,_) = 0 tanEval (coef,f) | coef < 0 = -tanEval (-coef, f) | odd coef = tanPlus f $ tanEval (coef - 1, f) | otherwise = tanPlus a a where a = tanEval (coef `div` 2, f)   tans :: (Integral a, Fractional b) => [(a, b)] -> b tans = foldl' tanPlus 0 . map tanEval   machins = [ [(1, 1%2), (1, 1%3)], [(2, 1%3), (1, 1%7)], [(12, 1%18), (8, 1%57), (-5, 1%239)], [(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12943)]]   not_machin = [(88, 1%172), (51, 1%239), (32 , 1%682), (44, 1%5357), (68, 1%12944)]   main = do putStrLn "Machins:" mapM_ (\x -> putStrLn $ show (tans x) ++ " <-- " ++ show x) machins   putStr "\nnot Machin: "; print not_machin print (tans not_machin)
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#ALGOL_W
ALGOL W
begin  % display the character code of "a" (97 in ASCII)  % write( decode( "a" ) );  % display the character corresponding to 97 ("a" in ASCII)  % write( code( 97 ) ); end.
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#APL
APL
⎕UCS 97 a
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Go
Go
package main   import ( "fmt" "math" )   // symmetric and lower use a packed representation that stores only // the lower triangle.   type symmetric struct { order int ele []float64 }   type lower struct { order int ele []float64 }   // symmetric.print prints a square matrix from the packed representation, // printing the upper triange as a transpose of the lower. func (s *symmetric) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range s.ele { fmt.Printf(eleFmt, e) if i == diag { for j, col := diag+row, row; col < s.order; j += col { fmt.Printf(eleFmt, s.ele[j]) col++ } fmt.Println() row++ diag += row } } }   // lower.print prints a square matrix from the packed representation, // printing the upper triangle as all zeros. func (l *lower) print() { const eleFmt = "%10.5f " row, diag := 1, 0 for i, e := range l.ele { fmt.Printf(eleFmt, e) if i == diag { for j := row; j < l.order; j++ { fmt.Printf(eleFmt, 0.) } fmt.Println() row++ diag += row } } }   // choleskyLower returns the cholesky decomposition of a symmetric real // matrix. The matrix must be positive definite but this is not checked. func (a *symmetric) choleskyLower() *lower { l := &lower{a.order, make([]float64, len(a.ele))} row, col := 1, 1 dr := 0 // index of diagonal element at end of row dc := 0 // index of diagonal element at top of column for i, e := range a.ele { if i < dr { d := (e - l.ele[i]) / l.ele[dc] l.ele[i] = d ci, cx := col, dc for j := i + 1; j <= dr; j++ { cx += ci ci++ l.ele[j] += d * l.ele[cx] } col++ dc += col } else { l.ele[i] = math.Sqrt(e - l.ele[i]) row++ dr += row col = 1 dc = 0 } } return l }   func main() { demo(&symmetric{3, []float64{ 25, 15, 18, -5, 0, 11}}) demo(&symmetric{4, []float64{ 18, 22, 70, 54, 86, 174, 42, 62, 134, 106}}) }   func demo(a *symmetric) { fmt.Println("A:") a.print() fmt.Println("L:") a.choleskyLower().print() }
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Factor
Factor
USING: assocs calendar.english fry io kernel prettyprint sequences sets.extras ;   : unique-by ( seq quot -- newseq ) 2dup map non-repeating '[ @ _ member? ] filter ; inline   ALIAS: day first ALIAS: month second   { { 15 5 } { 16 5 } { 19 5 } { 17 6 } { 18 6 } { 14 7 } { 16 7 } { 14 8 } { 15 8 } { 17 8 } }   ! the month cannot have a unique day dup [ day ] map non-repeating over extract-keys values '[ month _ member? ] reject   ! of the remaining dates, day must be unique [ day ] unique-by   ! of the remaining dates, month must be unique [ month ] unique-by   ! print a date that looks like { { 16 7 } } first first2 month-name write bl .
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Go
Go
package main   import ( "fmt" "time" )   type birthday struct{ month, day int }   func (b birthday) String() string { return fmt.Sprintf("%s %d", time.Month(b.month), b.day) }   func (b birthday) monthUniqueIn(bds []birthday) bool { count := 0 for _, bd := range bds { if bd.month == b.month { count++ } } if count == 1 { return true } return false }   func (b birthday) dayUniqueIn(bds []birthday) bool { count := 0 for _, bd := range bds { if bd.day == b.day { count++ } } if count == 1 { return true } return false }   func (b birthday) monthWithUniqueDayIn(bds []birthday) bool { for _, bd := range bds { if bd.month == b.month && bd.dayUniqueIn(bds) { return true } } return false }   func main() { choices := []birthday{ {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}, }   // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. var filtered []birthday for _, bd := range choices { if !bd.monthUniqueIn(choices) { filtered = append(filtered, bd) } }   // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. var filtered2 []birthday for _, bd := range filtered { if !bd.monthWithUniqueDayIn(filtered) { filtered2 = append(filtered2, bd) } }   // Bernard now knows the answer. // So the day must be unique within the remaining choices. var filtered3 []birthday for _, bd := range filtered2 { if bd.dayUniqueIn(filtered2) { filtered3 = append(filtered3, bd) } }   // Albert now knows the answer too. // So the month must be unique within the remaining choices. var filtered4 []birthday for _, bd := range filtered3 { if bd.monthUniqueIn(filtered3) { filtered4 = append(filtered4, bd) } }   if len(filtered4) == 1 { fmt.Println("Cheryl's birthday is", filtered4[0]) } else { fmt.Println("Something went wrong!") } }
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Logtalk
Logtalk
  :- object(checkpoint).   :- threaded.   :- public(run/3). :- mode(run(+integer,+integer,+float), one). :- info(run/3, [ comment is 'Assemble items using a team of workers with a maximum time per item assembly.', arguments is ['Workers'-'Number of workers', 'Items'-'Number of items to assemble', 'Time'-'Maximum time in seconds to assemble one item'] ]).   :- public(run/0). :- mode(run, one). :- info(run/0, [ comment is 'Assemble three items using a team of five workers with a maximum of 0.1 seconds per item assembly.' ]).   :- uses(integer, [between/3]). :- uses(random, [random/3]).   run(Workers, Items, Time) :- % start the workers forall( between(1, Workers, Worker), threaded_ignore(worker(Worker, Items, Time)) ), % assemble the items checkpoint_loop(Workers, Items).   run :- % default values run(5, 3, 0.100).   checkpoint_loop(_, 0) :- !, write('All assemblies done.'), nl. checkpoint_loop(Workers, Item) :- % wait for all threads to reach the checkpoint forall( between(1, Workers, Worker), threaded_wait(done(Worker, Item)) ), write('Assembly of item '), write(Item), write(' done.'), nl, % signal the workers to procede to the next assembly NextItem is Item - 1, forall( between(1, Workers, Worker), threaded_notify(next(Worker, NextItem)) ), checkpoint_loop(Workers, NextItem).   worker(_, 0, _) :- !. worker(Worker, Item, Time) :- % the time necessary to assemble one item varies between 0.0 and Time seconds random(0.0, Time, AssemblyTime), thread_sleep(AssemblyTime), write('Worker '), write(Worker), write(' item '), write(Item), nl, % notify checkpoint that the worker have done his/her part of this item threaded_notify(done(Worker, Item)), % wait for green light to move to the next item NextItem is Item - 1, threaded_wait(next(Worker, NextItem)), worker(Worker, NextItem, Time).   :- end_object.  
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Icon_and_Unicon
Icon and Unicon
# Creation of collections: s := "abccd" # string, an ordered collection of characters, immutable c := 'abcd' # cset, an unordered collection of characters, immutable S := set() # set, an unordered collection of unique values, mutable, contents may be of any type T := table() # table, an associative array of values accessed via unordered keys, mutable, contents may be of any type L := [] # list, an ordered collection of values indexed by position 1..n or as stack/queue, mutable, contents may be of any type record constructorname(field1,field2,fieldetc) # record, a collection of values stored in named fields, mutable, contents may be of any type (declare outside procedures) R := constructorname() # record (creation)
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Nim
Nim
iterator comb(m, n: int): seq[int] = var c = newSeq[int](n) for i in 0 ..< n: c[i] = i   block outer: while true: yield c   var i = n - 1 inc c[i] if c[i] <= m - 1: continue   while c[i] >= m - n + i: dec i if i < 0: break outer inc c[i] while i < n-1: c[i+1] = c[i] + 1 inc i   for i in comb(5, 3): echo i
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Rhope
Rhope
If[cond] |: Do Something[] :||: Do Something Else[] :|
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#Elixir
Elixir
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end   IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#Erlang
Erlang
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]).   egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}.   mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end.   mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end.   calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end.   chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Lua
Lua
function chowla(n) local sum = 0 local i = 2 local j = 0 while i * i <= n do if n % i == 0 then j = math.floor(n / i) sum = sum + i if i ~= j then sum = sum + j end end i = i + 1 end return sum end   function sieve(limit) -- True denotes composite, false denotes prime. -- Only interested in odd numbers >= 3 local c = {} local i = 3 while i * 3 < limit do if not c[i] and (chowla(i) == 0) then local j = 3 * i while j < limit do c[j] = true j = j + 2 * i end end i = i + 2 end return c end   function main() for i = 1, 37 do print(string.format("chowla(%d) = %d", i, chowla(i))) end local count = 1 local limit = math.floor(1e7) local power = 100 local c = sieve(limit) local i = 3 while i < limit do if not c[i] then count = count + 1 end if i == power - 1 then print(string.format("Count of primes up to %10d = %d", power, count)) power = power * 10 end i = i + 2 end   count = 0 limit = 350000000 local k = 2 local kk = 3 local p = 0 i = 2 while true do p = k * kk if p > limit then break end if chowla(p) == p - 1 then print(string.format("%10d is a number that is perfect", p)) count = count + 1 end k = kk + 1 kk = kk + k i = i + 1 end print(string.format("There are %d perfect numbers <= 35,000,000", count)) end   main()
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Quackery
Quackery
[ this nested ] is zero ( --> cn )   [ this nested join ] is succ ( cn --> cn )   [ zero [ 2dup = if done succ rot succ unrot recurse ] 2drop ] is add ( cn cn --> cn )   [ zero unrot zero [ 2dup = if done succ 2swap tuck add swap 2swap recurse ] 2drop drop ] is mul ( cn cn --> cn )   [ zero succ unrot zero [ 2dup = if done succ 2swap tuck mul swap 2swap recurse ] 2drop drop ] is exp ( cn cn --> cn )   [ zero swap times succ ] is n->cn ( n --> cn )   [ size 1 - ] is cn->n ( cn --> n )   ( - - - - - - - - - - - - - - - - - - - - - - - - )   [ zero succ succ succ ] is three ( --> cn )   [ three succ ] is four ( --> cn )   four three add cn->n echo sp four three mul cn->n echo sp four three exp cn->n echo sp three four exp cn->n echo
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Groovy
Groovy
/** Ye olde classe declaration */ class Stuff { /** Heare bee anne instance variable declared */ def guts   /** This constructor converts bits into Stuff */ Stuff(injectedGuts) { guts = injectedGuts }   /** Brethren and sistren, let us flangulate with this fine flangulating method */ def flangulate() { println "This stuff is flangulating its guts: ${guts}" } }
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Liberty_BASIC
Liberty BASIC
  N =10   dim x( N), y( N)   firstPt =0 secondPt =0   for i =1 to N read f: x( i) =f read f: y( i) =f next i   minDistance =1E6   for i =1 to N -1 for j =i +1 to N dxSq =( x( i) -x( j))^2 dySq =( y( i) -y( j))^2 D =abs( ( dxSq +dySq)^0.5) if D <minDistance then minDistance =D firstPt =i secondPt =j end if next j next i   print "Distance ="; minDistance; " between ( "; x( firstPt); ", "; y( firstPt); ") and ( "; x( secondPt); ", "; y( secondPt); ")"   end   data 0.654682, 0.925557 data 0.409382, 0.619391 data 0.891663, 0.888594 data 0.716629, 0.996200 data 0.477721, 0.946355 data 0.925092, 0.818220 data 0.624291, 0.142924 data 0.211332, 0.221507 data 0.293786, 0.691701 data 0.839186, 0.72826    
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#REXX
REXX
/*REXX program has a list of ten functions, each returns its invocation (index) squared.*/ parse arg seed base $ /*obtain optional arguments from the CL*/ if datatype(seed, 'W') then call random ,,seed /*Not given? Use random start seed. */ if base=='' | base="," then base=0 /* " " Use a zero─based list. */ if $='' then $= 8 5 4 9 1 3 2 7 6 0 /* " " Use ordered function list*/ /*the $ list must contain 10 functions.*/ say 'the' word("zero one", base+1)'─based list is: ' $ /*show list of functions.*/ /*BASED must be either 1 or 0. */ ?='.'random(0, 9) /*get a random name of a function. */ interpret 'CALL'  ? /*invoke a randomly selected function. */ say 'function '  ? " returned " result /*display the value of random function.*/ exit /*stick a fork in it, we're all done. */ /*────────────────────────[Below are the closest things to anonymous functions in REXX].*/ .0: return .(0) /*function .0 ─── bump its counter. */ .1: return .(1) /* ' .1 " " " " */ .2: return .(2) /* ' .2 " " " " */ .3: return .(3) /* ' .3 " " " " */ .4: return .(4) /* ' .4 " " " " */ .5: return .(5) /* ' .5 " " " " */ .6: return .(6) /* ' .6 " " " " */ .7: return .(7) /* ' .7 " " " " */ .8: return .(8) /* ' .8 " " " " */ .9: return .(9) /* ' .9 " " " " */ /*──────────────────────────────────────────────────────────────────────────────────────*/ .: arg #; _=wordpos(#,$); if _==0 then return 'not in the list.'; return (_-(\base))**2
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#FreeBASIC
FreeBASIC
Type Point As Double x,y Declare Property length As Double End Type   Property point.length As Double Return Sqr(x*x+y*y) End Property   Sub circles(p1 As Point,p2 As Point,radius As Double) Print "Points ";"("&p1.x;","&p1.y;"),("&p2.x;","&p2.y;")";", Rad ";radius Var ctr=Type<Point>((p1.x+p2.x)/2,(p1.y+p2.y)/2) Var half=Type<Point>(p1.x-ctr.x,p1.y-ctr.y) Var lenhalf=half.length If radius<lenhalf Then Print "Can't solve":Print:Exit Sub If lenhalf=0 Then Print "Points are the same":Print:Exit Sub Var dist=Sqr(radius^2-lenhalf^2)/lenhalf Var rot= Type<Point>(-dist*(p1.y-ctr.y) +ctr.x,dist*(p1.x-ctr.x) +ctr.y) Print " -> Circle 1 ("&rot.x;","&rot.y;")" rot= Type<Point>(-(rot.x-ctr.x) +ctr.x,-((rot.y-ctr.y)) +ctr.y) Print" -> Circle 2 ("&rot.x;","&rot.y;")" Print End Sub     Dim As Point p1=(.1234,.9876),p2=(.8765,.2345) circles(p1,p2,2) p1=Type<Point>(0,2):p2=Type<Point>(0,0) circles(p1,p2,1) p1=Type<Point>(.1234,.9876):p2=p1 circles(p1,p2,2) p1=Type<Point>(.1234,.9876):p2=Type<Point>(.8765,.2345) circles(p1,p2,.5) p1=Type<Point>(.1234,.9876):p2=p1 circles(p1,p2,0)   Sleep
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#F.23
F#
  open System   let animals = ["Rat";"Ox";"Tiger";"Rabbit";"Dragon";"Snake";"Horse";"Goat";"Monkey";"Rooster";"Dog";"Pig"] let elements = ["Wood";"Fire";"Earth";"Metal";"Water"] let years = [1935;1938;1968;1972;1976;1984;1985;2017]   let getZodiac(year: int) = let animal = animals.Item((year-4)%12) let element = elements.Item(((year-4)%10)/2) let yy = if year%2 = 0 then "(Yang)" else "(Yin)"   String.Format("{0} is the year of the {1} {2} {3}", year, element, animal, yy)   [<EntryPoint>] let main argv = let mutable string = "" for i in years do string <- getZodiac(i) printf "%s" string Console.ReadLine() |> ignore 0 // return an integer exit code  
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#BASIC
BASIC
  ON ERROR GOTO ohNo f$ = "input.txt" GOSUB opener f$ = "\input.txt" GOSUB opener   'can't directly check for directories, 'but can check for the NUL device in the desired dir f$ = "docs\nul" GOSUB opener f$ = "\docs\nul" GOSUB opener END   opener: e$ = " found" OPEN f$ FOR INPUT AS 1 PRINT f$; e$ CLOSE RETURN   ohNo: IF (53 = ERR) OR (76 = ERR) THEN e$ = " not" + e$ ELSE e$ = "Unknown error" END IF RESUME NEXT  
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#C.23
C#
using System.Diagnostics; using System.Drawing;   namespace RosettaChaosGame { class Program { static void Main(string[] args) { var bm = new Bitmap(600, 600);   var referencePoints = new Point[] { new Point(0, 600), new Point(600, 600), new Point(300, 81) }; var r = new System.Random(); var p = new Point(r.Next(600), r.Next(600)); for (int count = 0; count < 10000; count++) { bm.SetPixel(p.X, p.Y, Color.Magenta); int i = r.Next(3); p.X = (p.X + referencePoints[i].X) / 2; p.Y = (p.Y + referencePoints[i].Y) / 2; } const string filename = "Chaos Game.png"; bm.Save(filename); Process.Start(filename); } } }
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#D
D
  import std.getopt; import std.socket; import std.stdio; import std.string;   struct client { int pos; char[] name; char[] buffer; Socket socket; }   void broadcast(client[] connections, size_t self, const char[] message) { writeln(message); for (size_t i = 0; i < connections.length; i++) { if (i == self) continue;   connections[i].socket.send(message); connections[i].socket.send("\r\n"); } }   bool registerClient(client[] connections, size_t self) { for (size_t i = 0; i < connections.length; i++) { if (i == self) continue;   if (icmp(connections[i].name, connections[self].name) == 0) { return false; } }   return true; }   void main(string[] args) { ushort port = 4004;   auto helpInformation = getopt ( args, "port|p", "The port to listen to chat clients on [default is 4004]", &port );   if (helpInformation.helpWanted) { defaultGetoptPrinter("A simple chat server based on a task in rosettacode.", helpInformation.options); return; }   auto listener = new TcpSocket(); assert(listener.isAlive); listener.blocking = false; listener.bind(new InternetAddress(port)); listener.listen(10); writeln("Listening on port: ", port);   enum MAX_CONNECTIONS = 60; auto socketSet = new SocketSet(MAX_CONNECTIONS + 1); client[] connections;   while(true) { socketSet.add(listener);   foreach (con; connections) { socketSet.add(con.socket); }   Socket.select(socketSet, null, null);   for (size_t i = 0; i < connections.length; i++) { if (socketSet.isSet(connections[i].socket)) { char[1024] buf; auto datLength = connections[i].socket.receive(buf[]);   if (datLength == Socket.ERROR) { writeln("Connection error."); } else if (datLength != 0) { if (buf[0] == '\n' || buf[0] == '\r') { if (connections[i].buffer == "/quit") { connections[i].socket.close(); if (connections[i].name.length > 0) { writeln("Connection from ", connections[i].name, " closed."); } else { writeln("Connection from ", connections[i].socket.remoteAddress(), " closed."); }   connections[i] = connections[$-1]; connections.length--; i--;   writeln("\tTotal connections: ", connections.length); continue; } else if (connections[i].name.length == 0) { connections[i].buffer = strip(connections[i].buffer); if (connections[i].buffer.length > 0) { connections[i].name = connections[i].buffer; if (registerClient(connections, i)) { connections.broadcast(i, "+++ " ~ connections[i].name ~ " arrived +++"); } else { connections[i].socket.send("Name already registered. Please enter your name: "); connections[i].name.length = 0; } } else { connections[i].socket.send("A name is required. Please enter your name: "); } } else { connections.broadcast(i, connections[i].name ~ "> " ~ connections[i].buffer); } connections[i].buffer.length = 0; } else { connections[i].buffer ~= buf[0..datLength]; } } else { try { if (connections[i].name.length > 0) { writeln("Connection from ", connections[i].name, " closed."); } else { writeln("Connection from ", connections[i].socket.remoteAddress(), " closed."); } } catch (SocketException) { writeln("Connection closed."); } } } }   if (socketSet.isSet(listener)) { Socket sn = null; scope(failure) { writeln("Error accepting");   if (sn) { sn.close(); } } sn = listener.accept(); assert(sn.isAlive); assert(listener.isAlive);   if (connections.length < MAX_CONNECTIONS) { client newclient;   writeln("Connection from ", sn.remoteAddress(), " established."); sn.send("Enter name: ");   newclient.socket = sn; connections ~= newclient;   writeln("\tTotal connections: ", connections.length); } else { writeln("Rejected connection from ", sn.remoteAddress(), "; too many connections."); sn.close(); assert(!sn.isAlive); assert(listener.isAlive); } }   socketSet.reset(); } }  
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#J
J
machin =: 1r4p1 = [: +/ ({. * _3 o. %/@:}.)"1@:x:
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Java
Java
  import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class CheckMachinFormula {   private static String FILE_NAME = "MachinFormula.txt";   public static void main(String[] args) { try { runPrivate(); } catch (Exception e) { e.printStackTrace(); } }   private static void runPrivate() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { String inLine = null; while ( (inLine = reader.readLine()) != null ) { String[] split = inLine.split("="); System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); } } }   private static String tanLeft(String formula) { if ( formula.compareTo("pi/4") == 0 ) { return "1"; } throw new RuntimeException("ERROR 104: Unknown left side: " + formula); }   private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)");   private static Fraction tanRight(String formula) { Matcher matcher = ARCTAN_PATTERN.matcher(formula); List<Term> terms = new ArrayList<>(); while ( matcher.find() ) { terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); } return evaluateArctan(terms); }   private static Fraction evaluateArctan(List<Term> terms) { if ( terms.size() == 1 ) { Term term = terms.get(0); return evaluateArctan(term.coefficient, term.fraction); } int size = terms.size(); List<Term> left = terms.subList(0, (size+1) / 2); List<Term> right = terms.subList((size+1) / 2, size); return arctanFormula(evaluateArctan(left), evaluateArctan(right)); }   private static Fraction evaluateArctan(int coefficient, Fraction fraction) { //System.out.println("C = " + coefficient + ", F = " + fraction); if ( coefficient == 1 ) { return fraction; } else if ( coefficient < 0 ) { return evaluateArctan(-coefficient, fraction).negate(); } if ( coefficient % 2 == 0 ) { Fraction f = evaluateArctan(coefficient/2, fraction); return arctanFormula(f, f); } Fraction a = evaluateArctan(coefficient/2, fraction); Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); return arctanFormula(a, b); }   private static Fraction arctanFormula(Fraction f1, Fraction f2) { return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); }   private static class Fraction {   public static final Fraction ONE = new Fraction("1", "1");   private BigInteger numerator; private BigInteger denominator;   public Fraction(String num, String den) { numerator = new BigInteger(num); denominator = new BigInteger(den); }   public Fraction(BigInteger num, BigInteger den) { numerator = num; denominator = den; }   public Fraction negate() { return new Fraction(numerator.negate(), denominator); }   public Fraction add(Fraction f) { BigInteger gcd = denominator.gcd(f.denominator); BigInteger first = numerator.multiply(f.denominator.divide(gcd)); BigInteger second = f.numerator.multiply(denominator.divide(gcd)); return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); }   public Fraction subtract(Fraction f) { return add(f.negate()); }   public Fraction multiply(Fraction f) { BigInteger num = numerator.multiply(f.numerator); BigInteger den = denominator.multiply(f.denominator); BigInteger gcd = num.gcd(den); return new Fraction(num.divide(gcd), den.divide(gcd)); }   public Fraction divide(Fraction f) { return multiply(new Fraction(f.denominator, f.numerator)); }   @Override public String toString() { if ( denominator.compareTo(BigInteger.ONE) == 0 ) { return numerator.toString(); } return numerator + " / " + denominator; } }   private static class Term {   private int coefficient; private Fraction fraction;   public Term(int c, Fraction f) { coefficient = c; fraction = f; } }   }  
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#AppleScript
AppleScript
log(id of "a") log(id of "aA")
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program character.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessCodeChar: .ascii "The code of character is :" sZoneconv: .fill 12,1,' ' szCarriageReturn: .asciz "\n"   /* UnInitialized data */ .bss   /* code section */ .text .global main main: /* entry of program */ push {fp,lr} /* saves 2 registers */   mov r0,#'A' ldr r1,iAdrsZoneconv bl conversion10S ldr r0,iAdrszMessCodeChar bl affichageMess mov r0,#'a' ldr r1,iAdrsZoneconv bl conversion10S ldr r0,iAdrszMessCodeChar bl affichageMess mov r0,#'1' ldr r1,iAdrsZoneconv bl conversion10S ldr r0,iAdrszMessCodeChar bl affichageMess   100: /* standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrsZoneconv: .int sZoneconv iAdrszMessCodeChar: .int szMessCodeChar /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */   /***************************************************/ /* conversion register signed décimal */ /***************************************************/ /* r0 contient le registre */ /* r1 contient l adresse de la zone de conversion */ conversion10S: push {r0-r5,lr} /* save des registres */ mov r2,r1 /* debut zone stockage */ mov r5,#'+' /* par defaut le signe est + */ cmp r0,#0 /* nombre négatif ? */ movlt r5,#'-' /* oui le signe est - */ mvnlt r0,r0 /* et inversion en valeur positive */ addlt r0,#1 mov r4,#10 /* longueur de la zone */ 1: /* debut de boucle de conversion */ bl divisionpar10 /* division */ add r1,#48 /* ajout de 48 au reste pour conversion ascii */ strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */ sub r4,r4,#1 /* position précedente */ cmp r0,#0 bne 1b /* boucle si quotient different de zéro */ strb r5,[r2,r4] /* stockage du signe à la position courante */ subs r4,r4,#1 /* position précedente */ blt 100f /* si r4 < 0 fin */ /* sinon il faut completer le debut de la zone avec des blancs */ mov r3,#' ' /* caractere espace */ 2: strb r3,[r2,r4] /* stockage du byte */ subs r4,r4,#1 /* position précedente */ bge 2b /* boucle si r4 plus grand ou egal a zero */ 100: /* fin standard de la fonction */ pop {r0-r5,lr} /*restaur desregistres */ bx lr   /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 contient le dividende */ /* r0 retourne le quotient */ /* r1 retourne le reste */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save registers */ mov r4,r0 ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ bx lr /* leave function */ .Ls_magic_number_10: .word 0x66666667      
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Groovy
Groovy
def decompose = { a -> assert a.size > 0 && a[0].size == a.size def m = a.size def l = [].withEagerDefault { [].withEagerDefault { 0 } } (0..<m).each { i -> (0..i).each { k -> Number s = (0..<k).sum { j -> l[i][j] * l[k][j] } ?: 0 l[i][k] = (i == k) ? Math.sqrt(a[i][i] - s)  : (1.0 / l[k][k] * (a[i][k] - s)) } } l }
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Groovy
Groovy
import java.time.Month   class Main { private static class Birthday { private Month month private int day   Birthday(Month month, int day) { this.month = month this.day = day }   Month getMonth() { return month }   int getDay() { return day }   @Override String toString() { return month.toString() + " " + day } }   static void main(String[] args) { List<Birthday> choices = [ new Birthday(Month.MAY, 15), new Birthday(Month.MAY, 16), new Birthday(Month.MAY, 19), new Birthday(Month.JUNE, 17), new Birthday(Month.JUNE, 18), new Birthday(Month.JULY, 14), new Birthday(Month.JULY, 16), new Birthday(Month.AUGUST, 14), new Birthday(Month.AUGUST, 15), new Birthday(Month.AUGUST, 17) ] println("There are ${choices.size()} candidates remaining.")   // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer Set<Birthday> uniqueMonths = choices.groupBy { it.getDay() } .values() .findAll() { it.size() == 1 } .flatten() .collect { ((Birthday) it).getMonth() } .toSet() as Set<Birthday> def f1List = choices.findAll { !uniqueMonths.contains(it.getMonth()) } println("There are ${f1List.size()} candidates remaining.")   // Bernard now knows the answer, so the day must be unique within the remaining choices List<Birthday> f2List = f1List.groupBy { it.getDay() } .values() .findAll { it.size() == 1 } .flatten() .toList() as List<Birthday> println("There are ${f2List.size()} candidates remaining.")   // Albert knows the answer too, so the month must be unique within the remaining choices List<Birthday> f3List = f2List.groupBy { it.getMonth() } .values() .findAll { it.size() == 1 } .flatten() .toList() as List<Birthday> println("There are ${f3List.size()} candidates remaining.")   if (f3List.size() == 1) { println("Cheryl's birthday is ${f3List.head()}") } else { System.out.println("No unique choice found") } } }
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Nim
Nim
import locks import os import random import strformat   const NWorkers = 3 # Number of workers. NTasks = 4 # Number of tasks. StopOrder = 0 # Order 0 is the request to stop.   var randLock: Lock # Lock to access random number generator. orders: array[1..NWorkers, Channel[int]] # Channel to send orders to workers. responses: Channel[int] # Channel to receive responses from workers. working: int # Current number of workers actually working. threads: array[1..NWorkers, Thread[int]] # Array of running threads.   #---------------------------------------------------------------------------------------------------   proc worker(num: int) {.thread.} = ## Worker thread.   while true: # Wait for order from main thread (this is the checkpoint). let order = orders[num].recv if order == StopOrder: break # Get a random time to complete the task. var time: int withLock(randLock): time = rand(200..1000) echo fmt"Worker {num}: starting task number {order}" # Work on task during "time" ms. sleep(time) echo fmt"Worker {num}: task number {order} terminated after {time} ms" # Send message to indicate that the task is terminated. responses.send(num)   #---------------------------------------------------------------------------------------------------   # Initializations. randomize() randLock.initLock() for num in 1..NWorkers: orders[num].open() responses.open()   # Create the worker threads. for num in 1..NWorkers: createThread(threads[num], worker, num)   # Send orders and wait for responses. for task in 1..NTasks: echo fmt"Sending order to start task number {task}" # Send order (task number) to workers. for num in 1..NWorkers: orders[num].send(task) working = NWorkers # All workers are now working. # Wait to receive responses from workers. while working > 0: discard responses.recv() # Here, we don't care about the message content. dec working   # We have terminated: send stop order to workers. echo "Sending stop order to workers." for num in 1..NWorkers: orders[num].send(StopOrder) joinThreads(threads) echo "All workers stopped."   # Clean up. for num in 1..NWorkers: orders[num].close() responses.close() deinitLock(randLock)
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Oforth
Oforth
: task(n, jobs, myChannel) while(true) [ System.Out "TASK " << n << " : Beginning my work..." << cr System sleep(1000 rand) System.Out "TASK " << n << " : Finish, sendind done and waiting for others..." << cr jobs send($jobDone) drop myChannel receive drop ] ;   : checkPoint(n, jobs, channels) while(true) [ #[ jobs receive drop ] times(n) "CHECKPOINT : All jobs done, sending done to all tasks" println channels apply(#[ send($allDone) drop ]) ] ;   : testCheckPoint(n) | jobs channels i | ListBuffer init(n, #[ Channel new ]) dup freeze ->channels Channel new ->jobs   #[ checkPoint(n, jobs, channels) ] & n loop: i [ #[ task(i, jobs, channels at(i)) ] & ] ;
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use v5.10;   use Socket;   my $nr_items = 3;   sub short_sleep($) { (my $seconds) = @_; select undef, undef, undef, $seconds; }   # This is run in a worker thread. It repeatedly waits for a character from # the main thread, and sends a value back to the main thread. A short # sleep introduces random timing, just to keep us honest.   sub be_worker($$) { my ($socket, $value) = @_; for (1 .. $nr_items) { sysread $socket, my $dummy, 1; short_sleep rand 0.5; syswrite $socket, $value; ++$value; }   exit; }   # This function forks a worker and sends it a socket on which to talk to # the main thread, as well as an initial value to work with. It returns # (to the main thread) a socket on which to talk to the worker.   sub fork_worker($) { (my $value) = @_; socketpair my $kidsock, my $dadsock, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die "socketpair: $!";   if (fork // die "fork: $!") { # We're the parent close $dadsock; return $kidsock; } else { # We're the child close $kidsock; be_worker $dadsock, $value; # Never returns } }   # Fork two workers, send them start signals, retrieve the values they send # back, and print them   my $alpha_sock = fork_worker 'A'; my $digit_sock = fork_worker 1;   for (1 .. $nr_items) { syswrite $_, 'x' for $alpha_sock, $digit_sock; sysread $alpha_sock, my $alpha, 1; sysread $digit_sock, my $digit, 1; say $alpha, $digit; }   # If the main thread were planning to run for a long time after the # workers had terminate, it would need to reap them to avoid zombies:   wait; wait;
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#J
J
c =: 0 10 20 30 40 NB. A collection   c, 50 NB. Append 50 to the collection 0 10 20 30 40 50 _20 _10 , c NB. Prepend _20 _10 to the collection _20 _10 0 10 20 30 40   ,~ c NB. Self-append 0 10 20 30 40 0 10 20 30 40 ,:~ c NB. Duplicate 0 10 20 30 40 0 10 20 30 40   30 e. c NB. Is 30 in the collection? 1 30 i.~c NB. Where? 3 30 80 e. c NB. Don't change anything to test multiple values -- collections are native. 1 0   2 1 4 2 { c NB. From the collection, give me items two, one, four, and two again. 20 10 40 20   |.c NB. Reverse the collection 40 30 20 10 0 1+c NB. Increment the collection 1 11 21 31 41 c%10 NB. Decimate the collection (divide by 10) 0 1 2 3 4   {. c NB. Give me the first item 0 {: c NB. And the last 40 3{.c NB. Give me the first 3 items 0 10 20 3}.c NB. Throw away the first 3 items 30 40 _3{.c NB. Give me the last 3 items 20 30 40 _3}.c NB. (Guess) 0 10   keys_map_ =: 'one';'two';'three' vals_map_ =: 'alpha';'beta';'gamma' lookup_map_ =: a:& $: : (dyad def ' (keys i. y) { vals,x')&boxopen exists_map_ =: verb def 'y e. keys'&boxopen   exists_map_ 'bad key' 0 exists_map_ 'two';'bad key' 1 0   lookup_map_ 'one' +-----+ |alpha| +-----+ lookup_map_ 'three';'one';'two';'one' +-----+-----+----+-----+ |gamma|alpha|beta|alpha| +-----+-----+----+-----+ lookup_map_ 'bad key' ++ || ++ 'some other default' lookup_map_ 'bad key' +------------------+ |some other default| +------------------+ 'some other default' lookup_map_ 'two';'bad key' +----+------------------+ |beta|some other default| +----+------------------+   +/ c NB. Sum of collection 100 */ c NB. Product of collection 0   i.5 NB. Generate the first 5 nonnegative integers 0 1 2 3 4 10*i.5 NB. Looks familiar 0 10 20 30 40 c = 10*i.5 NB. Test each for equality 1 1 1 1 1 c -: 10 i.5 NB. Test for identicality 1
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#OCaml
OCaml
let combinations m n = let rec c = function | (0,_) -> [[]] | (_,0) -> [] | (p,q) -> List.append (List.map (List.cons (n-q)) (c (p-1, q-1))) (c (p , q-1)) in c (m , n)     let () = let rec print_list = function | [] -> print_newline () | hd :: tl -> print_int hd ; print_string " "; print_list tl in List.iter print_list (combinations 3 5)  
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Ring
Ring
If x == 1 SomeFunc1() But x == 2 SomeFunc2() Else SomeFunc() Ok
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#F.23
F#
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n)   [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(N) ENTRY TO CHOWLA. SUM = 0 THROUGH LOOP, FOR I=2, 1, I*I.G.N J = N/I WHENEVER J*I.E.N SUM = SUM + I WHENEVER I.NE.J, SUM = SUM + J END OF CONDITIONAL LOOP CONTINUE FUNCTION RETURN SUM END OF FUNCTION   VECTOR VALUES CHWFMT = $7HCHOWLA(,I2,4H) = ,I2*$ THROUGH CH37, FOR CH=1, 1, CH.G.37 CH37 PRINT FORMAT CHWFMT, CH, CHOWLA.(CH)   VECTOR VALUES PRIMES = 0 $10HTHERE ARE ,I6,S1,13HPRIMES BELOW ,I8*$   POWER = 100 COUNT = 0 THROUGH PRM, FOR CH=2, 1, CH.G.10000000 WHENEVER CHOWLA.(CH).E.0, COUNT = COUNT + 1 WHENEVER (CH/POWER)*POWER.E.CH PRINT FORMAT PRIMES, COUNT, POWER POWER = POWER * 10 PRM END OF CONDITIONAL   COUNT = 0 LIMIT = 35000000 VECTOR VALUES PERFCT = $I8,S1,20HIS A PERFECT NUMBER.*$ VECTOR VALUES PRFCNT = 0 $10HTHERE ARE ,I1,S1,22HPERFECT NUMBERS BELOW ,I8*$ K = 2 KK = 3 LOOP CH = K * KK WHENEVER CH.G.LIMIT, TRANSFER TO DONE WHENEVER CHOWLA.(CH).E.CH-1 PRINT FORMAT PERFCT, CH COUNT = COUNT + 1 END OF CONDITIONAL K = KK + 1 KK = KK + K TRANSFER TO LOOP   DONE PRINT FORMAT PRFCNT, COUNT, LIMIT   END OF PROGRAM
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Maple
Maple
ChowlaFunction := n -> NumberTheory:-SumOfDivisors(n) - n - 1;   PrintChowla := proc(n::posint) local i; printf("Integer : Chowla Number\n"); for i to n do printf("%d  :  %d\n", i, ChowlaFunction(i)); end do; end proc:   countPrimes := n -> nops([ListTools[SearchAll](0, map(ChowlaFunction, [seq(1 .. n)]))]);   findPerfect := proc(n::posint) local to_check, found, k; to_check := map(ChowlaFunction, [seq(1 .. n)]); found := []; for k to n do if to_check(k) = k - 1 then found := [found, k]; end if; end do; end proc:   PrintChowla(37); countPrimes(100); countPrimes(1000); countPrimes(10000); countPrimes(100000); countPrimes(1000000); countPrimes(10000000); findPerfect(35000000)
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#R
R
zero <- function(f) {function(x) x} succ <- function(n) {function(f) {function(x) f(n(f)(x))}} add <- function(n) {function(m) {function(f) {function(x) m(f)(n(f)(x))}}} mult <- function(n) {function(m) {function(f) m(n(f))}} expt <- function(n) {function(m) m(n)} natToChurch <- function(n) {if(n == 0) zero else succ(natToChurch(n - 1))} churchToNat <- function(n) {(n(function(x) x + 1))(0)}   three <- natToChurch(3) four <- natToChurch(4)   churchToNat(add(three)(four)) churchToNat(mult(three)(four)) churchToNat(expt(three)(four)) churchToNat(expt(four)(three))
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Haskell
Haskell
class Shape a where perimeter :: a -> Double area :: a -> Double {- A type class Shape. Types belonging to Shape must support two methods, perimeter and area. -}   data Rectangle = Rectangle Double Double {- A new type with a single constructor. In the case of data types which have only one constructor, we conventionally give the constructor the same name as the type, though this isn't mandatory. -}   data Circle = Circle Double   instance Shape Rectangle where perimeter (Rectangle width height) = 2 * width + 2 * height area (Rectangle width height) = width * height {- We made Rectangle an instance of the Shape class by implementing perimeter, area :: Rectangle -> Int. -}   instance Shape Circle where perimeter (Circle radius) = 2 * pi * radius area (Circle radius) = pi * radius^2   apRatio :: Shape a => a -> Double {- A simple polymorphic function. -} apRatio shape = area shape / perimeter shape   main = do print $ apRatio $ Circle 5 print $ apRatio $ Rectangle 5 5 {- The correct version of apRatio (and hence the correct implementations of perimeter and area) is chosen based on the type of the argument. -}
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Maple
Maple
ClosestPair := module()   local ModuleApply := proc(L::list,$) local Lx, Ly, out; Ly := sort(L, 'key'=(i->i[2]), 'output'='permutation'); Lx := sort(L, 'key'=(i->i[1]), 'output'='permutation'); out := Recurse(L, Lx, Ly, 1, numelems(L)); return sqrt(out[1]), out[2]; end proc; # ModuleApply   local BruteForce := proc(L, Lx, r1:=1, r2:=numelems(L), $) local d, p, n, i, j; d := infinity; for i from r1 to r2-1 do for j from i+1 to r2 do n := dist( L[Lx[i]], L[Lx[j]] ); if n < d then d := n; p := [ L[Lx[i]], L[Lx[j]] ]; end if; end do; # j end do; # i return (d, p); end proc; # BruteForce   local dist := (p, q)->(( (p[1]-q[1])^2+(p[2]-q[2])^2 ));   local Recurse := proc(L, Lx, Ly, r1, r2) local m, xm, rDist, rPair, lDist, lPair, minDist, minPair, S, i, j, Lyr, Lyl;   if r2-r1 <= 3 then return BruteForce(L, Lx, r1, r2); end if;   m := ceil((r2-r1)/2)+r1; xm := (L[Lx[m]][1] + L[Lx[m-1]][1])/2;   (Lyr, Lyl) := selectremove( i->L[i][1] < xm, Ly);   (rDist, rPair) := thisproc(L, Lx, Lyr, r1, m-1); (lDist, lPair) := thisproc(L, Lx, Lyl, m, r2);   if rDist < lDist then minDist := rDist; minPair := rPair; else minDist := lDist; minPair := lPair; end if;   S := [ seq( `if`(abs(xm - L[i][1])^2< minDist, L[i], NULL ), i in Ly ) ];   for i from 1 to nops(S)-1 do for j from i+1 to nops(S) do if abs( S[i][2] - S[j][2] )^2 >= minDist then break; elif dist(S[i], S[j]) < minDist then minDist := dist(S[i], S[j]); minPair := [S[i], S[j]]; end if; end do; end do;   return (minDist, minPair);   end proc; #Recurse   end module; #ClosestPair
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Ring
Ring
  x = funcs(7) see x + nl   func funcs n fn = list(n) for i = 1 to n fn[i] =i*i next return fn  
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Ruby
Ruby
procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda p procs[7].call # => 49
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Go
Go
package main   import ( "fmt" "math" )   var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe only a single circle." Far = "Points too far apart to form circles." )   type point struct{ x, y float64 }   func circles(p1, p2 point, r float64) (c1, c2 point, Case string) { if p1 == p2 { if r == 0 { return p1, p1, CoR0 } Case = Co return } if r == 0 { return p1, p2, R0 } dx := p2.x - p1.x dy := p2.y - p1.y q := math.Hypot(dx, dy) if q > 2*r { Case = Far return } m := point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2} if q == 2*r { return m, m, Diam } d := math.Sqrt(r*r - q*q/4) ox := d * dx / q oy := d * dy / q return point{m.x - oy, m.y + ox}, point{m.x + oy, m.y - ox}, Two }   var td = []struct { p1, p2 point r float64 }{ {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 2.0}, {point{0.0000, 2.0000}, point{0.0000, 0.0000}, 1.0}, {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 2.0}, {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 0.5}, {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 0.0}, }   func main() { for _, tc := range td { fmt.Println("p1: ", tc.p1) fmt.Println("p2: ", tc.p2) fmt.Println("r: ", tc.r) c1, c2, Case := circles(tc.p1, tc.p2, tc.r) fmt.Println(" ", Case) switch Case { case CoR0, Diam: fmt.Println(" Center: ", c1) case Two: fmt.Println(" Center 1: ", c1) fmt.Println(" Center 2: ", c2) } fmt.Println() } }
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Factor
Factor
USING: circular formatting io kernel math qw sequences sequences.repeating ; IN: rosetta-code.zodiac   <PRIVATE   ! Offset start index by -4 because first cycle started on 4 CE. : circularize ( seq -- obj ) [ -4 ] dip <circular> [ change-circular-start ] keep ;   : animals ( -- obj ) qw{ Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig } circularize ;   : elements ( -- obj ) qw{ Wood Fire Earth Metal Water } 2 <repeats> circularize ;   PRIVATE>   : zodiac ( n -- str ) dup [ elements nth ] [ animals nth ] [ even? "yang" "yin" ? ] tri "%d is the year of the %s %s (%s)." sprintf ;   : zodiac-demo ( -- ) { 1935 1938 1968 1972 1976 1984 1985 2017 } [ zodiac print ] each ;   MAIN: zodiac-demo
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#FreeBASIC
FreeBASIC
dim as string yy(0 to 1) = {"yang", "yin"} dim as string elements(0 to 4) = {"Wood", "Fire", "Earth", "Metal", "Water"} dim as string animals(0 to 11) = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",_ "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}   dim as uinteger yr, y, e, a, i, tests(0 to 5) = {1801, 1861, 1984, 2020, 2186, 76543} dim as string outstr   for i = 0 to 5 yr = tests(i) y = yr mod 2 e = (yr - 4) mod 5 a = (yr - 4) mod 12 outstr = str(yr)+" is the year of the " outstr += elements(e)+" " + animals(a) + " (" + yy(y) + ")."   print outstr next i